当前位置: 首页>>代码示例>>Golang>>正文


Golang http.DetectContentType函数代码示例

本文整理汇总了Golang中net/http.DetectContentType函数的典型用法代码示例。如果您正苦于以下问题:Golang DetectContentType函数的具体用法?Golang DetectContentType怎么用?Golang DetectContentType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DetectContentType函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: uploadPic

func (c *appContext) uploadPic(a *multipart.FileHeader) (string, string) {
	log.Println("In upload pic territory")

	bucket := c.bucket

	file, err := a.Open()
	defer file.Close()
	if err != nil {
		panic(err.Error())
	}

	if err != nil {
		panic(err)
	}

	buf, _ := ioutil.ReadAll(file)

	fn := uuid.New()
	fname := "places/" + fn + path.Ext(a.Filename)
	thumbname := "placesthumb/" + fn + path.Ext(a.Filename)
	log.Println(fname)

	b := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + fname
	d := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + thumbname

	filetype := http.DetectContentType(buf)

	err = bucket.Put(fname, buf, filetype, s3.PublicRead)

	if err != nil {
		log.Println("bucket put error for main image")
		panic(err.Error())

	}
	log.Print("added a full image")
	img, err := jpeg.Decode(bytes.NewReader(buf))

	if err != nil {
		log.Println(err.Error())
	}

	m := resize.Resize(200, 200, img, resize.Lanczos2)

	buf2 := new(bytes.Buffer)
	err = jpeg.Encode(buf2, m, nil)
	if err != nil {
		fmt.Println(err.Error())
	}
	thumb := buf2.Bytes()
	filetype2 := http.DetectContentType(thumb)
	err = bucket.Put(thumbname, thumb, filetype2, s3.PublicRead)

	if err != nil {
		log.Println("bucket put error for thumbnail")
		panic(err.Error())
	}
	log.Println("uploaded one thumb image")
	return b, d

}
开发者ID:kolawoletech,项目名称:kaku-go,代码行数:60,代码来源:utils.go

示例2: GetThumbnail

func (a *Api) GetThumbnail(w rest.ResponseWriter, r *rest.Request) {
	name := r.PathParam("name")
	exists, data := a.binthumb.Retrieve(name)
	if exists {
		w.Header().Add("Content-Type", http.DetectContentType(data))
		w.(http.ResponseWriter).Write(data)
	} else {
		_, data = a.binimage.Retrieve(name)
		datatype := http.DetectContentType(data)
		outbuf := bytes.NewBuffer([]byte{})

		if datatype == "video/webm" {
			//v := nutil.GetVideoFrame(bytes.NewBuffer(data))
			//i, _, _ = image.Decode(v)
			v := nutil.GetGifThumbnail(bytes.NewBuffer(data))
			outbuf.ReadFrom(v)

		} else {
			i, _, _ := image.Decode(bytes.NewReader(data))
			thmb := nutil.MakePropThumbnail(i, 314, 0)
			jpeg.Encode(outbuf, thmb, nil)
		}

		a.binthumb.Insert(name, outbuf.Bytes())
		w.Header().Add("Content-Type", http.DetectContentType(outbuf.Bytes()))
		w.(http.ResponseWriter).Write(outbuf.Bytes())
	}

	return
}
开发者ID:aimless,项目名称:g0,代码行数:30,代码来源:api.go

示例3: mainHandler

func mainHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
			return []byte(serectkey), nil
		})
		if err == nil && token.Valid {
			log.Println("Executing mainHandler")
			log.Println("Content-Length:", r.ContentLength)
			if r.ContentLength == 0 {
				w.Header().Set("xxx", "xxx")
				log.Println(http.StatusText(400))
				http.Error(w, http.StatusText(400), 400)
				return
			}
			buf := new(bytes.Buffer)
			buf.ReadFrom(r.Body)
			d := buf.Bytes()
			log.Println("Content-Type:", http.DetectContentType(d))
			//log.Println(string(d[:33]))
			if http.DetectContentType(buf.Bytes()) != "text/plain; charset=utf-8" {
				w.Header().Set("xxx", "xxx")
				http.Error(w, http.StatusText(415), 415)
				return
			}
			h.ServeHTTP(w, r)
			log.Println("Executing mainHandler again")
		} else {
			log.Println("Invalid Token!")
			return
		}
	})
}
开发者ID:wal99d,项目名称:Go,代码行数:33,代码来源:HTTPMiddleware_v1.0.go

示例4: DecideFile

//判断文件协议content-type,0表示xml,1表示
//alter:    ,by:   ,time:  ,#第几次修改
func DecideFile(body []byte) int {
	if http.DetectContentType(body) == "text/xml; charset=utf-8" {
		return 0
	} else if http.DetectContentType(body) == "text/plain; charset=utf-8" {
		return 1
	}
	return 3
}
开发者ID:slygo,项目名称:360baosdk,代码行数:10,代码来源:utils.go

示例5: PutObject

// PutObject uploads a Google Cloud Storage object.
// shouldRetry will be true if the put failed due to authorization, but
// credentials have been refreshed and another attempt is likely to succeed.
// In this case, content will have been consumed.
func (gsa *Client) PutObject(obj *Object, content io.Reader) error {
	if err := obj.valid(); err != nil {
		return err
	}
	const maxSlurp = 2 << 20
	var buf bytes.Buffer
	n, err := io.CopyN(&buf, content, maxSlurp)
	if err != nil && err != io.EOF {
		return err
	}
	contentType := http.DetectContentType(buf.Bytes())
	if contentType == "application/octet-stream" && n < maxSlurp && utf8.Valid(buf.Bytes()) {
		contentType = "text/plain; charset=utf-8"
	}

	objURL := gsAccessURL + "/" + obj.Bucket + "/" + obj.Key
	var req *http.Request
	if req, err = http.NewRequest("PUT", objURL, ioutil.NopCloser(io.MultiReader(&buf, content))); err != nil {
		return err
	}
	req.Header.Set("x-goog-api-version", "2")
	req.Header.Set("Content-Type", contentType)

	var resp *http.Response
	if resp, err = gsa.client.Do(req); err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("Bad put response code: %v", resp.Status)
	}
	return nil
}
开发者ID:rfistman,项目名称:camlistore,代码行数:37,代码来源:googlestorage.go

示例6: HttpWriteFile

func (cache *FileCache) HttpWriteFile(w http.ResponseWriter, r *http.Request) {
	path, err := url.QueryUnescape(r.URL.String())
	if err != nil {
		http.ServeFile(w, r, r.URL.Path)
	} else if len(path) > 1 {
		path = path[1:len(path)]
	} else {
		http.ServeFile(w, r, ".")
		return
	}

	if cache.InCache(path) {
		itm := cache.items[path]
		ctype := http.DetectContentType(itm.Access())
		mtype := mime.TypeByExtension(filepath.Ext(path))
		if mtype != "" && mtype != ctype {
			ctype = mtype
		}
		w.Header().Set("content-length", fmt.Sprintf("%d", itm.Size))
		w.Header().Set("content-disposition",
			fmt.Sprintf("filename=%s", filepath.Base(path)))
		w.Header().Set("content-type", ctype)
		w.Write(itm.Access())
		return
	}
	go cache.Cache(path)
	http.ServeFile(w, r, path)
}
开发者ID:youkebing,项目名称:filecache,代码行数:28,代码来源:filecache.go

示例7: GetFileBase64

func (this *FileService) GetFileBase64(userId, fileId string) (str string, mine string) {
	defer func() { // 必须要先声明defer,否则不能捕获到panic异常
		if err := recover(); err != nil {
			fmt.Println(err) // 这里的err其实就是panic传入的内容,55
		}
	}()

	path := this.GetFile(userId, fileId)

	if path == "" {
		return "", ""
	}

	path = revel.BasePath + "/" + strings.TrimLeft(path, "/")

	ff, err := ioutil.ReadFile(path)
	if err != nil {
		return "", ""
	}

	e64 := base64.StdEncoding
	maxEncLen := e64.EncodedLen(len(ff))
	encBuf := make([]byte, maxEncLen)

	e64.Encode(encBuf, ff)

	mime := http.DetectContentType(ff)

	str = string(encBuf)
	return str, mime
}
开发者ID:ClaudeXin,项目名称:leanote,代码行数:31,代码来源:FileService.go

示例8: Put

func (s *staticDB) Put(file *os.File, size int) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if _, ok := s.assets[file.Name()]; ok {
		return fmt.Errorf("file already known, %q", file.Name())
	}

	buf := bytes.NewBuffer(nil)

	_, err := io.Copy(buf, file)
	if err != nil {
		return err
	}

	data := buf.Bytes()

	mimetype := mime.TypeByExtension(filepath.Ext(file.Name()))
	if mimetype == "" {
		log.Printf("[INFO] Couldn't detect mimetype from exntension, sniffing content: %q", file.Name())
		mimetype = http.DetectContentType(data)
	}
	log.Printf("[INFO] Mimetype of %q: %q", file.Name(), mimetype)

	h := md5.New()
	_, _ = h.Write(data)

	s.assets[file.Name()] = &asset{
		md5hex:   hex.EncodeToString(h.Sum(nil)),
		content:  data,
		mimetype: mimetype,
	}

	return nil
}
开发者ID:mokelab,项目名称:pkgname,代码行数:35,代码来源:static.go

示例9: ConvertToResponseDetailsView

func (r *ResponseDetails) ConvertToResponseDetailsView() views.ResponseDetailsView {
	needsEncoding := false

	// Check headers for gzip
	contentEncodingValues := r.Headers["Content-Encoding"]
	if len(contentEncodingValues) > 0 {
		needsEncoding = true
	} else {
		mimeType := http.DetectContentType([]byte(r.Body))
		needsEncoding = true
		for _, v := range supportedMimeTypes {
			if strings.Contains(mimeType, v) {
				needsEncoding = false
				break
			}
		}
	}

	// If contains gzip, base64 encode
	body := r.Body
	if needsEncoding {
		body = base64.StdEncoding.EncodeToString([]byte(r.Body))
	}

	return views.ResponseDetailsView{Status: r.Status, Body: body, Headers: r.Headers, EncodedBody: needsEncoding}
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:26,代码来源:payload.go

示例10: changeAvatar

// Helper function to change the avatar
func changeAvatar(s *discordgo.Session) {

	resp, err := http.Get(URL)
	if err != nil {
		fmt.Println("Error retrieving the file, ", err)
		return
	}

	defer func() {
		_ = resp.Body.Close()
	}()

	img, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading the response, ", err)
		return
	}

	base64 := base64.StdEncoding.EncodeToString(img)

	avatar := fmt.Sprintf("data:%s;base64,%s", http.DetectContentType(img), base64)

	_, err = s.UserUpdate("", "", BotUsername, avatar, "")
	if err != nil {
		fmt.Println("Error setting the avatar, ", err)
	}

}
开发者ID:42wim,项目名称:matterbridge,代码行数:29,代码来源:main.go

示例11: writeCloudStorageObject

func writeCloudStorageObject(httpClient *http.Client) {
	content := os.Stdin
	const maxSlurp = 1 << 20
	var buf bytes.Buffer
	n, err := io.CopyN(&buf, content, maxSlurp)
	if err != nil && err != io.EOF {
		log.Fatalf("Error reading from stdin: %v, %v", n, err)
	}
	contentType := http.DetectContentType(buf.Bytes())

	req, err := http.NewRequest("PUT", "https://storage.googleapis.com/"+*writeObject, io.MultiReader(&buf, content))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("x-goog-api-version", "2")
	req.Header.Set("x-goog-acl", "public-read")
	req.Header.Set("Content-Type", contentType)
	res, err := httpClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode != 200 {
		res.Write(os.Stderr)
		log.Fatalf("Failed.")
	}
	log.Printf("Success.")
	os.Exit(0)
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:28,代码来源:create.go

示例12: sniff

func (w *EncodedResponseWriter) sniff(bytes []byte) {
	if w.sniffDone {
		return
	}
	w.sniffDone = true
	// Check the content type, sniffing the initial data if necessary:
	respType := w.Header().Get("Content-Type")
	if respType == "" && bytes != nil {
		respType = http.DetectContentType(bytes)
		w.Header().Set("Content-Type", respType)
	}

	// Can/should we compress the response?
	if w.status >= 300 || w.Header().Get("Content-Encoding") != "" ||
		(!strings.HasPrefix(respType, "application/json") && !strings.HasPrefix(respType, "text/")) {
		return
	}

	// OK, we can compress the response:
	//base.LogTo("HTTP+", "GZip-compressing response")
	w.Header().Set("Content-Encoding", "gzip")
	w.Header().Del("Content-Length") // length is unknown due to compression

	// Get a gzip writer from the cache, or create a new one if it's empty:
	select {
	case w.gz = <-zipperCache:
		w.gz.Reset(w.ResponseWriter)
	default:
		w.gz = gzip.NewWriter(w.ResponseWriter)
	}
}
开发者ID:rajasaur,项目名称:sync_gateway,代码行数:31,代码来源:encoded_response_writer.go

示例13: Write

func (w gzipResponseWriter) Write(b []byte) (int, error) {
	if "" == w.Header().Get("Content-Type") {
		// If no content type, apply sniffing algorithm to un-gzipped body.
		w.Header().Set("Content-Type", http.DetectContentType(b))
	}
	return w.Writer.Write(b)
}
开发者ID:postfix,项目名称:gozim,代码行数:7,代码来源:gzip.go

示例14: Write

func (w *gzipResponseWriter) Write(b []byte) (int, error) {
	if !w.sniffDone && w.Header().Get("Content-Type") == "" {
		w.Header().Set("Content-Type", http.DetectContentType(b))
		w.sniffDone = true
	}
	return w.gzipWriter.Write(b)
}
开发者ID:nhooyr,项目名称:goWiki,代码行数:7,代码来源:main.go

示例15: PutObject

//Upload object by its remote path and local file path. The format of remote path is "/bucketName/objectName".
func (c *Client) PutObject(opath string, filepath string) (err error) {
	if strings.HasPrefix(opath, "/") == false {
		opath = "/" + opath
	}

	//reqUrl := "http://" + c.Host + opath
	buffer := new(bytes.Buffer)

	fh, err := os.Open(filepath)
	if err != nil {
		return
	}
	defer fh.Close()
	io.Copy(buffer, fh)

	contentType := http.DetectContentType(buffer.Bytes())
	params := map[string]string{}
	params["Content-Type"] = contentType

	resp, err := c.doRequest("PUT", opath, opath, params, buffer)
	if err != nil {
		return
	}

	body, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		err = errors.New(resp.Status)
		fmt.Println(string(body))
		return
	}
	return
}
开发者ID:jirentabu,项目名称:ossgoapi,代码行数:35,代码来源:oss.go


注:本文中的net/http.DetectContentType函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。