Skip to content

Commit

Permalink
feat: Implement embed folder and a better organisation
Browse files Browse the repository at this point in the history
  • Loading branch information
vomnes committed Mar 15, 2021
1 parent 9ae1c0d commit 7e4680a
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 77 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ jobs:
- go: 1.13.x
- go: 1.14.x
- go: 1.15.x
- go: 1.16.x
- go: master

install:
Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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")
}
```
27 changes: 27 additions & 0 deletions embed_folder.go
Original file line number Diff line number Diff line change
@@ -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),
}
}
40 changes: 40 additions & 0 deletions embed_folder_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ require (
github.com/stretchr/testify v1.4.0
)

go 1.13
go 1.16
47 changes: 47 additions & 0 deletions local_file.go
Original file line number Diff line number Diff line change
@@ -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
}
34 changes: 34 additions & 0 deletions local_file_test.go
Original file line number Diff line number Diff line change
@@ -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 changes: 1 addition & 41 deletions serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand Down
47 changes: 12 additions & 35 deletions serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")

Expand All @@ -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")
}
Expand All @@ -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)
}
1 change: 1 addition & 0 deletions test/data/server/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Hello Embed</h1>
1 change: 1 addition & 0 deletions test/data/server/static.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Hello Gin Static</h1>

0 comments on commit 7e4680a

Please sign in to comment.