В веб-приложении Go у меня есть встроенная файловая система, содержащая статические файлы и файлы шаблонов.
Индексная функция func index(w http.ResponseWriter, r *http.Request)
работает с анализом и выполнением шаблона.
Как я мог служить обоим на пути /
?
GET /
послужит index
GET/{anythingelse}
будет подаваться из FS
//go:embed assets
var staticFiles embed.FS
var staticFS = fs.FS(staticFiles)
htmlContent, _ := fs.Sub(staticFS, "assets")
fs := http.FileServer(http.FS(htmlContent))
mux := http.NewServeMux()
mux.Handle("GET /", fs)
mux.HandleFunc("GET /", index)
У julienschmidt/httprouter
есть роутер .NotFound . Как я могу сделать то же самое?
В Go 1.22 используйте шаблон /{$}
для соответствия точному пути /
и шаблон /
для соответствия любому пути.
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", index)
mux.Handle("GET /", fs)
До Go 1.22 используйте оператор if
в функции index
:
//go:embed assets
var staticFiles embed.FS
var fs http.Handler
func index(w http.ReponseWriter, r *http.Request) {
if r.URL.Path != "/" {
fs.ServeHTTP(w, r)
return
}
// insert original index code here
}
func main() {
staticFS := fs.FS(staticFiles)
htmlContent, _ := fs.Sub(staticFS, "assets")
fs = http.FileServer(http.FS(htmlContent))
mux := http.NewServeMux()
mux.HandleFunc("GET /", index)
...