大猩猩Mux 404

时间:2017-12-27 16:09:37

标签: go mux

我正在休假,在Go上梳洗。不幸的是,我下面的代码在两条路线上都抛出了404。这是最新的迭代。我原来在handleRouter函数中有路由器,并认为把它拿出来会修复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)

}

1 个答案:

答案 0 :(得分:4)

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

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

或使用默认的服务器mux注册:

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