大猩猩多路复用器 404
Gorilla Mux 404
我要利用这个假期来更新 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))
我要利用这个假期来更新 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))