我正在跟随巡回演出,其中一个练习要求我建立几个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错误。我在这里错过了一步吗?
最佳答案
您的代码在ListenAndServe
处停止,该代码正在阻止。 (顺便说一句,如果ListenAndServe
没有被阻止,则main
将返回并且该过程将退出)
在此之前注册处理程序。