我正在尝试按照教程使用 Golang 和路由包 Gorilla/mux 运行一个基本的网络应用程序。服务器运行正常,但无论我在浏览器中输入什么,它都拒绝找到 index.html 文件,总是返回 404。
代码如下:
主.go
package main
import (
"database/sql"
"fmt"
"net/http"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "0102"
dbname = "bird_encyclopaedia"
)
func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/hello", handler).Methods("GET")
staticFileDirectory := http.Dir("./assets/")
staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))
r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
r.HandleFunc("/bird", getBirdHandler).Methods("GET")
r.HandleFunc("/bird", createBirdHandler).Methods("POST")
return r
}
func main() {
fmt.Println("Starting server dickface...")
connString := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", connString)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
InitStore(&dbStore{db: db})
r := newRouter()
fmt.Println("Serving on port 8080")
http.ListenAndServe(":8080", r)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
html 文件就在 assets/index.html 目录中,如果需要我可以提供,但我看不到实际 html 中的问题?
我多次浏览代码,不明白为什么服务器找不到目录。我已经尝试过 localhost/8080/assets、localhost/8080/assets/index.html、localhost/8080 和所有其他变体。
如果我用/hello mind 附加它,它会返回在 main.go 中看到的 Hello world 如果我用/bird 附加它,它会返回“null”而不是 404。
最佳答案
你不需要 http.StripPrefix()因为您没有在 URL 中使用 assets
。
只需更改这两行:
staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))
r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
到
staticFileHandler := http.FileServer(staticFileDirectory)
r.PathPrefix("/").Handler(staticFileHandler).Methods("GET")
关于http - Golang 在服务器运行时获得 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54690875/