【发布时间】:2018-11-12 01:46:15
【问题描述】:
我正在尝试根据路线提供不同的 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)
}
【问题讨论】:
-
我在代码中没有主动看到错误,您确定您在进行更改后重新启动了 GO 进程吗?
-
删除所有对 path.Dir() 的调用。此调用返回路径的目录部分。该代码提供 index.html,因为 ServeFile 在给定目录时会查找 index.html。
-
有效!非常感谢 ThunderCat。
-
你应该直接使用
http.ServeFile(w, r, /* file or directory name */)来解决歧义