我正在跟蹤 go tour,其中一個練習要求我構建幾個 http 處理程序。這是代碼: package mainimport ( "fmt" "net/http")type String stringtype Struct struct { Greeting string Punct string Who string}func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request){ fmt.Fprint(w, s)}func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request){ fmt.Fprint(w, "This is a struct. Yey!")}func main() { // your http.Handle calls here http.ListenAndServe("localhost:4000", nil) http.Handle("/string", String("I'm a frayed knot")) http.Handle("/struct", &Struct{"Hello",":","Gophers!"})}代碼編譯并運行得很好但是我不確定為什么當我導航到localhost:4000/string或localhost:4000/struct我得到的只是來自默認 http 處理程序的 404 錯誤。我在這里遺漏了一步還是?
2 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
您的代碼停在ListenAndServe
,這是阻塞的。(順便說一句,如果ListenAndServe
沒有阻塞,main
將返回并且進程將退出)
在此之前注冊處理程序。
- 2 回答
- 0 關注
- 169 瀏覽
添加回答
舉報
0/150
提交
取消