|
@@ -17,12 +17,14 @@ var (
|
|
)
|
|
)
|
|
|
|
|
|
type Server struct {
|
|
type Server struct {
|
|
- ctx context.Context
|
|
|
|
- serve *http.Server
|
|
|
|
- router *router.Router
|
|
|
|
- middleware []Middleware
|
|
|
|
- uptime time.Time
|
|
|
|
- anyRequests map[string]http.Handler
|
|
|
|
|
|
+ ctx context.Context
|
|
|
|
+ serve *http.Server
|
|
|
|
+ router *router.Router
|
|
|
|
+ middleware []Middleware
|
|
|
|
+ uptime time.Time
|
|
|
|
+ enableDocumentRoot bool
|
|
|
|
+ fileSystem http.FileSystem
|
|
|
|
+ anyRequests map[string]http.Handler
|
|
}
|
|
}
|
|
|
|
|
|
func (svr *Server) applyContext() *Context {
|
|
func (svr *Server) applyContext() *Context {
|
|
@@ -91,6 +93,15 @@ func (svr *Server) Group(prefix string, routes []Route, middleware ...Middleware
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
+func (svr *Server) Root(prefix string, fs http.FileSystem) {
|
|
|
|
+ svr.enableDocumentRoot = true
|
|
|
|
+ s := newFS(svr.uptime, fs)
|
|
|
|
+ s.SetPrefix(prefix)
|
|
|
|
+ s.DenyAccessDirectory()
|
|
|
|
+ s.SetIndexFile("/index.html")
|
|
|
|
+ svr.fileSystem = s
|
|
|
|
+}
|
|
|
|
+
|
|
func (svr *Server) Embed(prefix string, root string, embedFs embed.FS) {
|
|
func (svr *Server) Embed(prefix string, root string, embedFs embed.FS) {
|
|
routePath := prefix
|
|
routePath := prefix
|
|
if !strings.HasSuffix(routePath, "/*filepath") {
|
|
if !strings.HasSuffix(routePath, "/*filepath") {
|
|
@@ -159,12 +170,24 @@ func (svr *Server) handleRequest(res http.ResponseWriter, req *http.Request) {
|
|
}
|
|
}
|
|
|
|
|
|
func (svr *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
|
func (svr *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
|
|
|
+ var (
|
|
|
|
+ err error
|
|
|
|
+ file http.File
|
|
|
|
+ )
|
|
for prefix, handle := range svr.anyRequests {
|
|
for prefix, handle := range svr.anyRequests {
|
|
if strings.HasPrefix(request.URL.Path, prefix) {
|
|
if strings.HasPrefix(request.URL.Path, prefix) {
|
|
handle.ServeHTTP(writer, request)
|
|
handle.ServeHTTP(writer, request)
|
|
return
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
+ if svr.enableDocumentRoot && request.Method == http.MethodGet {
|
|
|
|
+ uri := path.Clean(request.URL.Path)
|
|
|
|
+ if file, err = svr.fileSystem.Open(uri); err == nil {
|
|
|
|
+ http.ServeContent(writer, request, path.Base(uri), svr.uptime, file)
|
|
|
|
+ err = file.Close()
|
|
|
|
+ return
|
|
|
|
+ }
|
|
|
|
+ }
|
|
switch request.Method {
|
|
switch request.Method {
|
|
case http.MethodOptions:
|
|
case http.MethodOptions:
|
|
svr.handleOption(writer, request)
|
|
svr.handleOption(writer, request)
|