feat: Implement embed folder and a better organisation
This commit is contained in:
parent
9ae1c0d541
commit
7e4680a8ef
|
@ -10,6 +10,7 @@ jobs:
|
|||
- go: 1.13.x
|
||||
- go: 1.14.x
|
||||
- go: 1.15.x
|
||||
- go: 1.16.x
|
||||
- go: master
|
||||
|
||||
install:
|
||||
|
|
33
README.md
33
README.md
|
@ -28,6 +28,8 @@ import "github.com/gin-contrib/static"
|
|||
See the [example](example)
|
||||
|
||||
[embedmd]:# (example/simple/example.go go)
|
||||
|
||||
#### Serve local file
|
||||
```go
|
||||
package main
|
||||
|
||||
|
@ -52,3 +54,34 @@ func main() {
|
|||
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 tmp/server
|
||||
var server embed.FS
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.Use(static.Serve("/", static.EmbedFolder(server, "tmp/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")
|
||||
}
|
||||
```
|
|
@ -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,47 @@
|
|||
package static
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const INDEX = "index.html"
|
||||
|
||||
type localFileSystem struct {
|
||||
http.FileSystem
|
||||
root string
|
||||
indexes bool
|
||||
}
|
||||
|
||||
func LocalFile(root string, indexes bool) *localFileSystem {
|
||||
return &localFileSystem{
|
||||
FileSystem: gin.Dir(root, indexes),
|
||||
root: root,
|
||||
indexes: indexes,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *localFileSystem) Exists(prefix string, filepath string) bool {
|
||||
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
|
||||
name := path.Join(l.root, p)
|
||||
stats, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if stats.IsDir() {
|
||||
if !l.indexes {
|
||||
index := path.Join(name, INDEX)
|
||||
_, err := os.Stat(index)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
|
@ -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)
|
||||
}
|
42
serve.go
42
serve.go
|
@ -2,60 +2,20 @@ package static
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const INDEX = "index.html"
|
||||
|
||||
type ServeFileSystem interface {
|
||||
http.FileSystem
|
||||
Exists(prefix string, path string) bool
|
||||
}
|
||||
|
||||
type localFileSystem struct {
|
||||
http.FileSystem
|
||||
root string
|
||||
indexes bool
|
||||
}
|
||||
|
||||
func LocalFile(root string, indexes bool) *localFileSystem {
|
||||
return &localFileSystem{
|
||||
FileSystem: gin.Dir(root, indexes),
|
||||
root: root,
|
||||
indexes: indexes,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *localFileSystem) Exists(prefix string, filepath string) bool {
|
||||
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
|
||||
name := path.Join(l.root, p)
|
||||
stats, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if stats.IsDir() {
|
||||
if !l.indexes {
|
||||
index := path.Join(name, INDEX)
|
||||
_, err := os.Stat(index)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
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.
|
||||
// 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 != "" {
|
||||
|
|
|
@ -13,7 +13,7 @@ import (
|
|||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
req, _ := http.NewRequest(method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
@ -44,18 +44,18 @@ func TestEmptyDirectory(t *testing.T) {
|
|||
router.GET("/"+filename, func(c *gin.Context) {
|
||||
c.String(200, "this is not printed")
|
||||
})
|
||||
w := performRequest(router, "GET", "/")
|
||||
w := PerformRequest(router, "GET", "/")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "index")
|
||||
|
||||
w = performRequest(router, "GET", "/"+filename)
|
||||
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")
|
||||
w = PerformRequest(router, "GET", "/a")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "a")
|
||||
|
||||
|
@ -65,23 +65,23 @@ func TestEmptyDirectory(t *testing.T) {
|
|||
c.String(200, "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(200, "index")
|
||||
})
|
||||
|
||||
w = performRequest(router2, "GET", "/static")
|
||||
w = PerformRequest(router2, "GET", "/static")
|
||||
assert.Equal(t, w.Code, 200)
|
||||
|
||||
w = performRequest(router2, "GET", "/"+filename)
|
||||
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)
|
||||
w = PerformRequest(router2, "GET", "/static/"+filename)
|
||||
assert.Equal(t, w.Code, 200)
|
||||
assert.Equal(t, w.Body.String(), "Gin Web Framework")
|
||||
}
|
||||
|
@ -102,33 +102,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", "/")
|
||||
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, 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 @@
|
|||
<h1>Hello Embed</h1>
|
|
@ -0,0 +1 @@
|
|||
<h1>Hello Gin Static</h1>
|
Loading…
Reference in New Issue