我正在跟随之旅,其中一个练习要求我建立一对http的处理程序。 这是代码:
package main
import (
"fmt"
"net/http"
)
type String string
type 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错误。
我在这里错过了一步还是?
答案 0 :(得分:3)
您的代码停在ListenAndServe
,即阻止。 (顺便说一句,如果ListenAndServe
没有阻止,main
将返回并且该过程将退出)
在此之前注册处理程序。
答案 1 :(得分:1)
从
更改main
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!"})
}
到
func main() {
http.Handle("/string", String("I'm a frayed knot"))
http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
// your http.Handle calls here
http.ListenAndServe("localhost:4000", nil)
}
http.ListenAndServe
阻止,直到您终止该程序。
通常会添加退出值的日志:
log.Fatal(http.ListenAndServe(...))