2017-12-27 114 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))