當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。