http - Golang 在服务器运行时获得 404

标签 http go gorilla mux

我正在尝试按照教程使用 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/

相关文章:

ios - HTTP 请求的 ZIP 文件内容类型

go - 在结构定义之外使用方法的原因是什么?

go - 如何管理 Web 应用程序中的长进程

go - Sec-Websocket-Protocol 问题

go - 是否可以从 websocket 连接访问 HTTP 请求?

angularjs - 设备中的 ionic http get 请求返回状态 0

android - 使用 Volley Android 库发送 XML 数据

multithreading - 从 Go 应用程序中的线程低级 C/C++ 代码层调用 Go 回调

go - Aurora 与 DynamoDB 延迟不符合预期

python - Python标准包将HTTP响应码转为文本消息