Skip to content

Commit

Permalink
feat: embed support send file function
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Jun 4, 2021
1 parent 5b43293 commit 8a684e9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
11 changes: 7 additions & 4 deletions docs/middlewares.md
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,8 @@ func main() {
package main

import (
"time"

"github.com/vicanso/elton"
"github.com/vicanso/elton/middleware"
)
Expand All @@ -720,9 +722,9 @@ func main() {
e.GET("/*", middleware.NewStaticServe(sf, middleware.StaticServeConfig{
Path: "/tmp",
// 客户端缓存一年
MaxAge: 365 * 24 * 3600,
MaxAge: 365 * 24 * time.Hour,
// 缓存服务器缓存一个小时
SMaxAge: 60 * 60,
SMaxAge: time.Hour,
DenyQueryString: true,
DisableLastModified: true,
// 如果使用packr,它不支持Stat,因此需要用强ETag
Expand All @@ -745,6 +747,7 @@ package main
import (
"bytes"
"io"
"time"
"os"

packr "github.com/gobuffalo/packr/v2"
Expand Down Expand Up @@ -789,9 +792,9 @@ func main() {
// static file route
e.GET("/static/*", middleware.NewStaticServe(sf, middleware.StaticServeConfig{
// 客户端缓存一年
MaxAge: 365 * 24 * 3600,
MaxAge: 365 * 24 * time.Hour,
// 缓存服务器缓存一个小时
SMaxAge: 60 * 60,
SMaxAge: time.Hour,
DenyQueryString: true,
DisableLastModified: true,
}))
Expand Down
15 changes: 15 additions & 0 deletions middleware/static_embed.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import (
"io"
"os"
"path/filepath"

"github.com/vicanso/elton"
)

type embedStaticFS struct {
Expand Down Expand Up @@ -77,3 +79,16 @@ func (es *embedStaticFS) NewReader(file string) (io.Reader, error) {
}
return bytes.NewReader(buf), nil
}

// SendFile sends file to http response and set content type
func (es *embedStaticFS) SendFile(c *elton.Context, file string) (err error) {
// 因为静态文件打包至程序中,直接读取
buf, err := es.Get(file)
if err != nil {
return
}
// 根据文件后续设置类型
c.SetContentTypeByExt(file)
c.BodyBuffer = bytes.NewBuffer(buf)
return
}

0 comments on commit 8a684e9

Please sign in to comment.