mirror of
https://github.com/labstack/echo.git
synced 2025-07-15 01:34:53 +02:00
29
context.go
29
context.go
@ -7,7 +7,6 @@ import (
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"time"
|
||||
@ -134,6 +133,11 @@ type (
|
||||
// Echo returns the `Echo` instance.
|
||||
Echo() *Echo
|
||||
|
||||
// ServeContent sends static content from `io.Reader` and handles caching
|
||||
// via `If-Modified-Since` request header. It automatically sets `Content-Type`
|
||||
// and `Last-Modified` response headers.
|
||||
ServeContent(http.File) error
|
||||
|
||||
// Object returns the `context` instance.
|
||||
Object() *context
|
||||
|
||||
@ -376,10 +380,8 @@ func (c *context) File(file string) error {
|
||||
if err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
fi, _ = f.Stat()
|
||||
}
|
||||
|
||||
return ServeContent(c.Request(), c.Response(), f, fi)
|
||||
return c.ServeContent(f)
|
||||
}
|
||||
|
||||
func (c *context) Attachment(r io.Reader, name string) (err error) {
|
||||
@ -420,13 +422,24 @@ func (c *context) Object() *context {
|
||||
return c
|
||||
}
|
||||
|
||||
// ServeContent sends a response from `io.Reader`. It automatically sets the `Content-Type`
|
||||
// and `Last-Modified` headers.
|
||||
func ServeContent(rq engine.Request, rs engine.Response, f http.File, fi os.FileInfo) error {
|
||||
func (c *context) ServeContent(f http.File) error {
|
||||
rq := c.Request()
|
||||
rs := c.Response()
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if t, err := time.Parse(http.TimeFormat, rq.Header().Get(IfModifiedSince)); err == nil && fi.ModTime().Before(t.Add(1*time.Second)) {
|
||||
rs.Header().Del(ContentType)
|
||||
rs.Header().Del(ContentLength)
|
||||
return c.NoContent(http.StatusNotModified)
|
||||
}
|
||||
|
||||
rs.Header().Set(ContentType, detectContentType(fi.Name()))
|
||||
rs.Header().Set(LastModified, fi.ModTime().UTC().Format(http.TimeFormat))
|
||||
rs.WriteHeader(http.StatusOK)
|
||||
_, err := io.Copy(rs, f)
|
||||
_, err = io.Copy(rs, f)
|
||||
return err
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user