mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-11 00:40:00 +08:00
feat: support embed file system to serve files in rest (#4253)
This commit is contained in:
@@ -2,8 +2,10 @@ package rest
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -21,6 +23,11 @@ import (
|
||||
"github.com/zeromicro/go-zero/rest/router"
|
||||
)
|
||||
|
||||
const (
|
||||
exampleContent = "example content"
|
||||
sampleContent = "sample content"
|
||||
)
|
||||
|
||||
func TestNewServer(t *testing.T) {
|
||||
logtest.Discard(t)
|
||||
|
||||
@@ -199,7 +206,7 @@ func TestWithFileServerMiddleware(t *testing.T) {
|
||||
dir: "./testdata",
|
||||
requestPath: "/assets/example.txt",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedContent: "example content",
|
||||
expectedContent: exampleContent,
|
||||
},
|
||||
{
|
||||
name: "Pass through non-matching path",
|
||||
@@ -214,13 +221,13 @@ func TestWithFileServerMiddleware(t *testing.T) {
|
||||
dir: "testdata",
|
||||
requestPath: "/static/sample.txt",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedContent: "sample content",
|
||||
expectedContent: sampleContent,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := MustNewServer(RestConf{}, WithFileServer(tt.path, tt.dir))
|
||||
server := MustNewServer(RestConf{}, WithFileServer(tt.path, http.Dir(tt.dir)))
|
||||
req := httptest.NewRequest(http.MethodGet, tt.requestPath, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
@@ -688,3 +695,18 @@ Port: 54321
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//go:embed testdata
|
||||
var content embed.FS
|
||||
|
||||
func TestServerEmbedFileSystem(t *testing.T) {
|
||||
filesys, err := fs.Sub(content, "testdata")
|
||||
assert.NoError(t, err)
|
||||
|
||||
server := MustNewServer(RestConf{}, WithFileServer("/assets", http.FS(filesys)))
|
||||
req, err := http.NewRequest(http.MethodGet, "/assets/sample.txt", http.NoBody)
|
||||
assert.Nil(t, err)
|
||||
rr := httptest.NewRecorder()
|
||||
server.ServeHTTP(rr, req)
|
||||
assert.Equal(t, sampleContent, rr.Body.String())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user