feat: enhance static file serving capabilities
- Add documentation for serving local files and embedded folders in README.md - Add new example code for serving embedded folders in Go - Create new `embed_folder.go` file with functions to serve embedded folders - Create new `embed_folder_test.go` file with tests for serving embedded folders - Add HTML template files for embedded server example - Rename `static.go` to `local_file.go` and remove unused code - Create new `local_file_test.go` file with tests for serving local files - Create new `serve.go` file with middleware handler for serving static files - Rename `static_test.go` to `serve_test.go` and refactor test functions - Remove redundant test case `TestListIndex` from `serve_test.go` Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
commit
acf41a9a1a
35
README.md
35
README.md
|
@ -27,6 +27,8 @@ import "github.com/gin-contrib/static"
|
|||
|
||||
See the [example](_example)
|
||||
|
||||
#### Serve local file
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
|
@ -48,6 +50,39 @@ func main() {
|
|||
c.String(200, "test")
|
||||
})
|
||||
// Listen and Server in 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
||||
```
|
||||
|
||||
#### Serve embed folder
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
//go:embed data
|
||||
var server embed.FS
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.Use(static.Serve("/", static.EmbedFolder(server, "data/server")))
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "test")
|
||||
})
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
fmt.Printf("%s doesn't exists, redirect on /\n", c.Request.URL.Path)
|
||||
c.Redirect(http.StatusMovedPermanently, "/")
|
||||
})
|
||||
// Listen and Server in 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
if err := r.Run(":8080"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
package static
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type embedFileSystem struct {
|
||||
http.FileSystem
|
||||
}
|
||||
|
||||
func (e embedFileSystem) Exists(prefix string, path string) bool {
|
||||
_, err := e.Open(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem {
|
||||
fsys, err := fs.Sub(fsEmbed, targetPath)
|
||||
if err != nil {
|
||||
log.Fatalf("static.EmbedFolder - Invalid targetPath value - %s", err)
|
||||
}
|
||||
return embedFileSystem{
|
||||
FileSystem: http.FS(fsys),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package static
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
//go:embed test/data/server
|
||||
var server embed.FS
|
||||
|
||||
var embedTests = []struct {
|
||||
targetURL string // input
|
||||
httpCode int // expected http code
|
||||
httpBody string // expected http body
|
||||
name string // test name
|
||||
}{
|
||||
{"/404.html", 301, "<a href=\"/\">Moved Permanently</a>.\n\n", "Unknown file"},
|
||||
{"/", 200, "<h1>Hello Embed</h1>", "Root"},
|
||||
{"/index.html", 301, "", "Root by file name automatic redirect"},
|
||||
{"/static.html", 200, "<h1>Hello Gin Static</h1>", "Other file"},
|
||||
}
|
||||
|
||||
func TestEmbedFolder(t *testing.T) {
|
||||
router := gin.New()
|
||||
router.Use(Serve("/", EmbedFolder(server, "test/data/server")))
|
||||
router.NoRoute(func(c *gin.Context) {
|
||||
fmt.Printf("%s doesn't exists, redirect on /\n", c.Request.URL.Path)
|
||||
c.Redirect(301, "/")
|
||||
})
|
||||
|
||||
for _, tt := range embedTests {
|
||||
w := PerformRequest(router, "GET", tt.targetURL)
|
||||
assert.Equal(t, tt.httpCode, w.Code, tt.name)
|
||||
assert.Equal(t, tt.httpBody, w.Body.String(), tt.name)
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
<h1>Hello Embed</h1>
|
|
@ -0,0 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
//go:embed data
|
||||
var server embed.FS
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.Use(static.Serve("/", static.EmbedFolder(server, "data/server")))
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.String(200, "test")
|
||||
})
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
fmt.Printf("%s doesn't exists, redirect on /\n", c.Request.URL.Path)
|
||||
c.Redirect(http.StatusMovedPermanently, "/")
|
||||
})
|
||||
// Listen and Server in 0.0.0.0:8080
|
||||
r.Run(":8080")
|
||||
}
|
|
@ -11,11 +11,6 @@ import (
|
|||
|
||||
const INDEX = "index.html"
|
||||
|
||||
type ServeFileSystem interface {
|
||||
http.FileSystem
|
||||
Exists(prefix string, path string) bool
|
||||
}
|
||||
|
||||
type localFileSystem struct {
|
||||
http.FileSystem
|
||||
root string
|
||||
|
@ -50,21 +45,3 @@ func (l *localFileSystem) Exists(prefix string, filepath string) bool {
|
|||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
|
||||
return Serve(urlPrefix, LocalFile(root, false))
|
||||
}
|
||||
|
||||
// Static returns a middleware handler that serves static files in the given directory.
|
||||
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
|
||||
fileserver := http.FileServer(fs)
|
||||
if urlPrefix != "" {
|
||||
fileserver = http.StripPrefix(urlPrefix, fileserver)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
if fs.Exists(urlPrefix, c.Request.URL.Path) {
|
||||
fileserver.ServeHTTP(c.Writer, c.Request)
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package static
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLocalFile(t *testing.T) {
|
||||
// SETUP file
|
||||
testRoot, _ := os.Getwd()
|
||||
f, err := ioutil.TempFile(testRoot, "")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
f.WriteString("Gin Web Framework")
|
||||
f.Close()
|
||||
|
||||
dir, filename := filepath.Split(f.Name())
|
||||
router := gin.New()
|
||||
router.Use(Serve("/", LocalFile(dir, true)))
|
||||
|
||||
w := PerformRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
|
||||
w = PerformRequest(router, "GET", "/")
|
||||
assert.Contains(t, w.Body.String(), `<a href="`+filename)
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package static
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ServeFileSystem interface {
|
||||
http.FileSystem
|
||||
Exists(prefix string, path string) bool
|
||||
}
|
||||
|
||||
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
|
||||
return Serve(urlPrefix, LocalFile(root, false))
|
||||
}
|
||||
|
||||
// Serve returns a middleware handler that serves static files in the given directory.
|
||||
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
|
||||
fileserver := http.FileServer(fs)
|
||||
if urlPrefix != "" {
|
||||
fileserver = http.StripPrefix(urlPrefix, fileserver)
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
if fs.Exists(urlPrefix, c.Request.URL.Path) {
|
||||
fileserver.ServeHTTP(c.Writer, c.Request)
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -15,7 +15,7 @@ import (
|
|||
)
|
||||
|
||||
//nolint:unparam
|
||||
func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
req, _ := http.NewRequestWithContext(context.Background(), method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
@ -46,19 +46,19 @@ func TestEmptyDirectory(t *testing.T) {
|
|||
router.GET("/"+filename, func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "this is not printed")
|
||||
})
|
||||
w := performRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w := PerformRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "index")
|
||||
|
||||
w = performRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
|
||||
w = performRequest(router, "GET", "/"+filename+"a")
|
||||
w = PerformRequest(router, "GET", "/"+filename+"a")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
|
||||
w = performRequest(router, "GET", "/a")
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router, "GET", "/a")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "a")
|
||||
|
||||
router2 := gin.New()
|
||||
|
@ -67,24 +67,24 @@ func TestEmptyDirectory(t *testing.T) {
|
|||
c.String(http.StatusOK, "this is printed")
|
||||
})
|
||||
|
||||
w = performRequest(router2, "GET", "/")
|
||||
w = PerformRequest(router2, "GET", "/")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
|
||||
w = performRequest(router2, "GET", "/static")
|
||||
w = PerformRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, 404)
|
||||
router2.GET("/static", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "index")
|
||||
})
|
||||
|
||||
w = performRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
|
||||
w = performRequest(router2, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router2, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "this is printed")
|
||||
|
||||
w = performRequest(router2, "GET", "/static/"+filename)
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router2, "GET", "/static/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
}
|
||||
|
||||
|
@ -104,33 +104,10 @@ func TestIndex(t *testing.T) {
|
|||
router := gin.New()
|
||||
router.Use(ServeRoot("/", dir))
|
||||
|
||||
w := performRequest(router, "GET", "/"+filename)
|
||||
w := PerformRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, 301)
|
||||
|
||||
w = performRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
w = PerformRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "index")
|
||||
}
|
||||
|
||||
func TestListIndex(t *testing.T) {
|
||||
// SETUP file
|
||||
testRoot, _ := os.Getwd()
|
||||
f, err := ioutil.TempFile(testRoot, "")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
_, _ = f.WriteString("Gin Web Framework")
|
||||
f.Close()
|
||||
|
||||
dir, filename := filepath.Split(f.Name())
|
||||
router := gin.New()
|
||||
router.Use(Serve("/", LocalFile(dir, true)))
|
||||
|
||||
w := performRequest(router, "GET", "/"+filename)
|
||||
assert.Equal(t, w.Code, http.StatusOK)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
|
||||
w = performRequest(router, "GET", "/")
|
||||
assert.Contains(t, w.Body.String(), `<a href="`+filename)
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
<h1>Hello Embed</h1>
|
|
@ -0,0 +1 @@
|
|||
<h1>Hello Gin Static</h1>
|
Loading…
Reference in New Issue