gorilla 多路复用器 404

标签 go mux

我要利用这个假期来更新 Go 语言。不幸的是,我下面的代码在两条路线上都抛出 404。这是最新的迭代。我最初将路由器放在 handleRouter 函数中,并认为将其移除会修复 404ing。剧透警报:它没有。我怎样才能解决这个问题?谢谢!

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type Article struct {
    Title   string `json:"Title"`
    Desc    string `json:"desc"`
    Content string `json:"content"`
}

type Articles []Article

func main() {
    fmt.Println("Router v2 - Muxx")

    myRouter := mux.NewRouter()
    myRouter.HandleFunc("/all", returnAllArticles).Methods("GET")
    myRouter.HandleFunc("/", homePage).Methods("GET")
    log.Fatal(http.ListenAndServe(":8000", nil))
}

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello:")
    fmt.Println("Endpoint Hit: homepage")
}

func returnAllArticles(w http.ResponseWriter, r *http.Request) {
    articles := Articles{
        Article{Title: "Hello", Desc: "Article Description", Content: "Article Content"},
        Article{Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
    }

    fmt.Println("Endpoint Hit: returnAllArticles")
    json.NewEncoder(w).Encode(articles)

}

最佳答案

要使用路由器,您必须将其传递给 HTTP 服务器。

log.Fatal(http.ListenAndServe(":8000", myRouter))

或使用默认服务 mux 注册它:

http.Handle("/", myRouter)
log.Fatal(http.ListenAndServe(":8000", nil))

关于 gorilla 多路复用器 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47995240/

相关文章:

go - 如果 env var 为空,如何分配默认值?

javascript - 我无法让 golang 识别我带参数的 get 请求

go - 键入断言嵌套接口(interface)

go - 如何从客户端停止goroutine?

go - r.Handle : missing method ServeHTTP error 参数中的 http.Handler 值

rest - 使用 Gorilla Mux 端点通过 HTTP 流式传输数据

api - h.264解码器的 "invalid NAL unit size"是什么意思?

linux - arm 上的 autocert 中缺少字段或方法签名方案

Golang gorilla mux 未找到处理程序无法正常工作