我正在尝试根据路由提供不同的HTML文件。路由器可以很好地处理"/“,并为index.html提供服务。然而,当转到像"/download“这样的任何其他路由时,它也会呈现index.html,即使要提供的文件名为share.html。
我在这里做错了什么?
package main
import (
"net/http"
"github.com/gorilla/mux"
"log"
"path"
"fmt"
)
// main func
func main() {
routes()
}
// routes
func routes() {
// init router
r := mux.NewRouter()
// index route
r.HandleFunc("/", home)
r.HandleFunc("/share", share)
r.HandleFunc("/download", download)
// start server on port 1337
log.Fatal(http.ListenAndServe(":1337", r))
}
// serves index file
func home(w http.ResponseWriter, r*http.Request) {
p := path.Dir("./public/views/index.html")
// set header
w.Header().Set("Content-type", "text/html")
http.ServeFile(w, r, p)
}
// get shared files
func share(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
if err := r.ParseForm(); err != nil {
fmt.Fprint(w, "ParseForm() err: %v", err)
return
}
log.Println(r.FormValue("name"))
http.Redirect(w, r, "/download", http.StatusMovedPermanently)
}
}
func download(w http.ResponseWriter, r *http.Request) {
p := path.Dir("./public/views/share.html")
// set header
w.Header().Set("Content-type", "text/html")
http.ServeFile(w, r, p)
}
发布于 2019-05-31 15:46:38
我相信你可能在找"PathPrefix“
func routes() {
// init router
r := mux.NewRouter()
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}
发布于 2018-06-02 07:33:52
删除对path.Dir()的所有调用。此调用返回路径的目录部分。该代码服务于index.html,因为ServeFile会在给定目录时查找index.html。
https://stackoverflow.com/questions/50651523
复制相似问题