大猩猩Mux 404
我正在休假放松一下,不幸的是,我下面的代码在这两条路线上都抛出了404。这是最新的迭代。我原来在路由器的路由器功能,并认为把它拿出来将修复404。扰流警报:它没有。我怎样才能解决这个问题?谢谢!大猩猩Mux 404
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))
以上是 大猩猩Mux 404 的全部内容, 来源链接: utcz.com/qa/266235.html