50 lines
1.0 KiB
Go
50 lines
1.0 KiB
Go
|
|
package webui
|
||
|
|
|
||
|
|
import (
|
||
|
|
"embed"
|
||
|
|
"io/fs"
|
||
|
|
"net/http"
|
||
|
|
"path"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
//go:embed dist
|
||
|
|
var content embed.FS
|
||
|
|
|
||
|
|
// Handler 返回嵌入后的前端静态资源处理器。
|
||
|
|
func Handler() http.Handler {
|
||
|
|
dist, err := fs.Sub(content, "dist")
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
files := http.FileServer(http.FS(dist))
|
||
|
|
|
||
|
|
return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||
|
|
requestPath := request.URL.Path
|
||
|
|
if requestPath == "/api" || strings.HasPrefix(requestPath, "/api/") {
|
||
|
|
http.NotFound(response, request)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
fileName := strings.TrimPrefix(path.Clean(requestPath), "/")
|
||
|
|
if fileName == "." {
|
||
|
|
fileName = ""
|
||
|
|
}
|
||
|
|
if fileName != "" {
|
||
|
|
if _, statErr := fs.Stat(dist, fileName); statErr == nil {
|
||
|
|
files.ServeHTTP(response, request)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if request.Method == http.MethodGet && path.Ext(requestPath) == "" {
|
||
|
|
indexRequest := request.Clone(request.Context())
|
||
|
|
indexRequest.URL.Path = "/"
|
||
|
|
files.ServeHTTP(response, indexRequest)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
http.NotFound(response, request)
|
||
|
|
})
|
||
|
|
}
|