本文整理汇总了Golang中net/http.ServeContent函数的典型用法代码示例。如果您正苦于以下问题:Golang ServeContent函数的具体用法?Golang ServeContent怎么用?Golang ServeContent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ServeContent函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serveResource
func (s *Server) serveResource(w http.ResponseWriter, r *http.Request, serveContent bool) {
path := s.url2path(r.URL)
f, err := s.Fs.Open(path)
if err != nil {
http.Error(w, r.RequestURI, StatusNotFound)
return
}
defer f.Close()
// TODO: what if path is collection?
fi, err := f.Stat()
if err != nil {
http.Error(w, r.RequestURI, StatusNotFound)
return
}
modTime := fi.ModTime()
if serveContent {
http.ServeContent(w, r, path, modTime, f)
} else {
// TODO: better way to send only head
http.ServeContent(w, r, path, modTime, emptyFile{})
}
}
示例2: serveFile
func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem,
name string, redirect bool, disableCache bool) {
// try to serve gziped file; ignore request for gz files
if !strings.HasSuffix(strings.ToLower(name), ".gz") && supportsGzip(r) {
if file, stat, err := open(fs, name+".gz"); file != nil && err == nil {
defer file.Close()
setContentType(w, name, file)
w.Header().Set("Content-Encoding", "gzip")
if disableCache {
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
w.Header().Set("Pragma", "no-cache")
} else {
w.Header().Set("Cache-Control", "must_revalidate, private, max-age=604800")
}
http.ServeContent(w, r, name, stat.ModTime(), file)
return
}
}
// serve requested file
if file, stat, err := open(fs, name); file != nil && err == nil {
defer file.Close()
if disableCache {
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
w.Header().Set("Pragma", "no-cache")
} else {
w.Header().Set("Cache-Control", "must_revalidate, private, max-age=604800")
}
http.ServeContent(w, r, stat.Name(), stat.ModTime(), file)
} else {
log.Error("Asset open error", "name", name, "err", err.Error())
http.NotFound(w, r)
}
}
示例3: initScript
// initScript concatenates all the javascript files needed to render
// the tour UI and serves the result on /script.js.
func initScript(root string) error {
modTime := time.Now()
b := new(bytes.Buffer)
content, ok := static.Files["playground.js"]
if !ok {
return fmt.Errorf("playground.js not found in static files")
}
b.WriteString(content)
// Keep this list in dependency order
files := []string{
"static/lib/jquery.min.js",
"static/lib/jquery-ui.min.js",
"static/lib/angular.min.js",
"static/lib/codemirror/lib/codemirror.js",
"static/lib/codemirror/mode/go/go.js",
"static/lib/angular-ui.min.js",
"static/js/app.js",
"static/js/controllers.js",
"static/js/directives.js",
"static/js/services.js",
"static/js/values.js",
}
for _, file := range files {
f, err := ioutil.ReadFile(filepath.Join(root, file))
if err != nil {
return fmt.Errorf("couldn't open %v: %v", file, err)
}
_, err = b.Write(f)
if err != nil {
return fmt.Errorf("error concatenating %v: %v", file, err)
}
}
var gzBuf bytes.Buffer
gz, err := gzip.NewWriterLevel(&gzBuf, gzip.BestCompression)
if err != nil {
return err
}
gz.Write(b.Bytes())
gz.Close()
http.HandleFunc("/script.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "application/javascript")
// Set expiration time in one week.
w.Header().Set("Cache-control", "max-age=604800")
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
http.ServeContent(w, r, "", modTime, bytes.NewReader(b.Bytes()))
} else {
w.Header().Set("Content-Encoding", "gzip")
http.ServeContent(w, r, "", modTime, bytes.NewReader(gzBuf.Bytes()))
}
})
return nil
}
示例4: ServeArt
// ServeArt provides a common method for serving and resizing Art, based on
// an input HTTP request.
func ServeArt(w http.ResponseWriter, r *http.Request, art *data.Art) error {
// Attempt to access art data stream
stream, err := art.Stream()
if err != nil {
return err
}
// Check for resize request, if none, serve directly
size := r.URL.Query().Get("size")
if size == "" {
// Serve content directly, account for range headers, and enabling caching.
http.ServeContent(w, r, art.FileName, time.Unix(art.LastModified, 0), stream)
return nil
}
// Ensure size is a valid integer
sizeInt, err := strconv.Atoi(size)
if err != nil {
return ErrInvalidIntegerSize
}
// Verify positive integer
if sizeInt < 1 {
return ErrNegativeIntegerSize
}
// Decode input image stream
img, imgFormat, err := image.Decode(stream)
if err != nil {
return err
}
// Generate a thumbnail image of the specified size
img = resize.Resize(uint(sizeInt), 0, img, resize.NearestNeighbor)
// Encode to original format for output
buffer := bytes.NewBuffer(nil)
if imgFormat == "jpeg" {
// JPEG, lossy encoding, default quality
if err := jpeg.Encode(buffer, img, nil); err != nil {
return err
}
} else {
// Always send PNG as a backup
// PNG, lossless encoding
if err := png.Encode(buffer, img); err != nil {
return err
}
}
// Serve content directly, account for range headers, and enabling caching.
http.ServeContent(w, r, art.FileName, time.Unix(art.LastModified, 0), bytes.NewReader(buffer.Bytes()))
return nil
}
示例5: serveFile
func (m *Static) serveFile(w http.ResponseWriter, r *http.Request, name string) {
if m.prefix != "" {
name = strings.TrimPrefix(name, m.prefix)
}
if !m.noCache {
if f, ok := m.c.GetOk(name); ok {
http.ServeContent(w, r, f.Name(), f.ModTime(), f)
return
}
}
f, err := m.fs.Open(name)
if err != nil {
m.serveError(w, r, err)
return
}
defer f.Close()
nf, err := NewFromHTTPFile(f)
if err != nil {
m.serveError(w, r, err)
return
}
supported := []string{".css", ".js"}
var found bool
xt := filepath.Ext(nf.Name())
for _, v := range supported {
if v == xt {
found = true
break
}
}
defer func() {
if !m.noCache && found {
m.c.Set(name, nf)
}
}()
if nf.IsDir() {
http.NotFound(w, r)
return
}
if len(m.chains) > 0 {
if found {
for k := range m.chains {
nf = m.chains[k](nf)
}
}
}
http.ServeContent(w, r, nf.Name(), nf.ModTime(), nf)
}
示例6: serveFile
func serveFile(w http.ResponseWriter, r *http.Request, fname string) {
f, err := os.Open(fname)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
fi, err := f.Stat()
if err == nil {
http.ServeContent(w, r, fname, fi.ModTime(), f)
} else {
http.ServeContent(w, r, fname, time.Time{}, f)
}
}
示例7: serveFile
func (e *Echo) serveFile(dir, file string, c *Context) (err error) {
fs := http.Dir(dir)
f, err := fs.Open(file)
if err != nil {
return NewHTTPError(http.StatusNotFound)
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
/* NOTE:
Not checking the Last-Modified header as it caches the response `304` when
changing differnt directories for the same path.
*/
d := f
// Index file
file = path.Join(file, indexPage)
f, err = fs.Open(file)
if err != nil {
if e.autoIndex {
// Auto index
return listDir(d, c)
}
return NewHTTPError(http.StatusForbidden)
}
fi, _ = f.Stat() // Index file stat
}
http.ServeContent(c.response, c.request, fi.Name(), fi.ModTime(), f)
return
}
示例8: handleImageRequest
func handleImageRequest(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
}
w.Header().Set("Cache-Control", "public, max-age=31536000")
// Client is checking for a cached URI, assume it is valid
// and return a 304
if r.Header.Get("If-Modified-Since") != "" {
w.WriteHeader(http.StatusNotModified)
return
}
gc := fetch.RequestContext(r)
var data []byte
err := cache.Get(gc, gc.CacheKey(), groupcache.AllocatingByteSliceSink(&data))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", http.DetectContentType(data))
http.ServeContent(w, r, gc.ImageId, time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), bytes.NewReader(data))
}
示例9: Apply
func (r *StaticBinaryResult) Apply(req *revel.Request, resp *revel.Response) {
// If we have a ReadSeeker, delegate to http.ServeContent
if rs, ok := r.Reader.(io.ReadSeeker); ok {
// http.ServeContent doesn't know about response.ContentType, so we set the respective header.
if resp.ContentType != "" {
resp.Out.Header().Set("Content-Type", resp.ContentType)
} else {
contentType := revel.ContentTypeByFilename(r.Name)
resp.Out.Header().Set("Content-Type", contentType)
}
http.ServeContent(resp.Out, req.Request, r.Name, r.ModTime, rs)
} else {
// Else, do a simple io.Copy.
if r.Length != -1 {
resp.Out.Header().Set("Content-Length", strconv.FormatInt(r.Length, 10))
}
resp.WriteHeader(http.StatusOK, revel.ContentTypeByFilename(r.Name))
io.Copy(resp.Out, r.Reader)
}
// Close the Reader if we can
if v, ok := r.Reader.(io.Closer); ok {
v.Close()
}
}
示例10: ServeHTTP
func (a asset) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if a.etag != "" && w.Header().Get("ETag") == "" {
w.Header().Set("ETag", a.etag)
}
body := strings.NewReader(a.Content)
http.ServeContent(w, req, a.Name, time.Time{}, body)
}
示例11: PhotoDownloadGET
func PhotoDownloadGET(w http.ResponseWriter, r *http.Request) {
// Get session
sess := session.Instance(r)
var params = context.Get(r, "params").(httprouter.Params)
//userid := params.ByName("userid")
pic_id := params.ByName("picid")
//user_id, _ := strconv.Atoi(userid)
user_id := uint64(sess.Values["id"].(uint32))
userid := strconv.Itoa(int(user_id))
if allowed, mark, err := photoAccessAllowed(r, user_id, pic_id); allowed {
buffer, err := renderImage(w, r, userid, pic_id, mark)
if err != nil {
log.Println(err)
Error500(w, r)
return
}
// Force download
w.Header().Set("Content-Disposition", `attachment; filename="`+pic_id+`"`)
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
http.ServeContent(w, r, pic_id, time.Now(), bytes.NewReader(buffer.Bytes()))
} else if err != sql.ErrNoRows {
log.Println(err)
Error500(w, r)
return
} else {
//log.Println("User does not have access to the photo.")
Error401(w, r)
return
}
}
示例12: ServeHttp
func (sh *StaticHandler) ServeHttp(responseWriter http.ResponseWriter, request *http.Request) {
staticFilePath := staticFilePath(request)
fileHandle, error := sh.Open(staticFilePath)
if serve404OnErr(error, responseWriter) {
return
}
defer fileHandle.Close()
fileInfo, error := fileHandle.Stat()
if serve404OnErr(error, responseWriter) {
return
}
if fileInfo.IsDir() {
if request.URL.Path[len(request.URL.Path)-1] != '/' {
http.Redirect(responseWriter, request, request.URL.Path+"/", http.StatusFound)
return
}
fileHandle, error = sh.Open(staticFilePath + "/index.html")
if serve404OnErr(error, responseWriter) {
return
}
defer fileHandle.Close()
fileInfo, error = fileHandle.Stat()
if serve404OnErr(error, responseWriter) {
return
}
}
http.ServeContent(responseWriter, request, fileInfo.Name(), fileInfo.ModTime(), fileHandle)
}
示例13: Execute
func (file *FileStreamResult) Execute(ctx *HttpContext) error {
//Set ContentType = "application/octet-stream";
if file.DownloadName != "" {
ctx.SetHeader("Content-Disposition", "attachment; filename=\""+file.DownloadName+"\";")
}
if ctype := ctx.Resonse.Header().Get("Content-Type"); ctype == "" {
ctype = file.Type()
if ctype != "" {
ctx.ContentType(ctype)
}
}
if rs, ok := file.Data.(io.ReadSeeker); ok {
http.ServeContent(ctx.Resonse, ctx.Request, file.DownloadName, file.ModifyTime, rs)
return nil
}
if checkLastModified(ctx.Resonse, ctx.Request, file.ModifyTime) {
return nil
}
io.Copy(ctx.Resonse, file.Data)
return nil
}
示例14: ServeStatic
func ServeStatic(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
} else if data, ok := go_bindata[r.URL.Path]; !ok {
http.NotFound(w, r)
} else {
if r.Header.Get("Range") != "" {
// Bypass setting/checking ETag for range requests.
} else if hash, ok := hashes[r.URL.Path]; ok {
quotedHash := `"` + hash + `"`
w.Header().Set("ETag", quotedHash)
if r.Header.Get("If-None-Match") == quotedHash {
w.WriteHeader(http.StatusNotModified)
return
}
}
ext := path.Ext(r.URL.Path)
mimeType, ok := extToMime[ext]
if !ok {
mimeType = "application/octet-stream"
}
w.Header().Set("Content-Type", mimeType)
http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(data()))
}
}
示例15: handleRoot
//handleRoot return handler that handles url not defined other handlers.
//if root, print titles of threads. if not, serve files on disk.
func handleRoot() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
gateway.PrintTitle(w, r)
return
}
pathOnDisk := filepath.Join(cfg.Docroot, r.URL.Path)
if util.IsFile(pathOnDisk) {
http.ServeFile(w, r, pathOnDisk)
return
}
pathOnAsset := path.Join("www", r.URL.Path)
if c, err := util.Asset(pathOnAsset); err == nil {
i, err := util.AssetInfo(pathOnAsset)
if err != nil {
log.Fatal(err)
}
reader := bytes.NewReader(c)
http.ServeContent(w, r, path.Base(r.URL.Path), i.ModTime(), reader)
return
}
log.Println("not found", r.URL.Path)
http.NotFound(w, r)
}
}