2017-12-27 325 views
0

我正在休假放松一下,不幸的是,我下面的代码在这两条路线上都抛出了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) 

} 
+0

你调用'http.ListenAndServe'没有实际传递你的路由器。请参阅['gorilla/mux'自述文件](https://github.com/gorilla/mux)中第一个示例中的http.Handle(“/”,r)'。 – Adrian

+1

为什么downvote?这似乎是一个很好的问题... – maerics

回答

2

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

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

或默认其注册服务MUX:

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