我是 Go 新手,正在尝试编写自定义 HTTP 服务器。我收到编译错误。如何ServeHTTP在我的代码中实现该方法?我的代码:package mainimport ( "net/http" "fmt" "io" "time")func myHandler(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n")}func main() { // Custom http server s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } err := s.ListenAndServe() if err != nil { fmt.Printf("Server failed: ", err.Error()) }}编译时出错:.\hello.go:21: cannot use myHandler (type func(http.ResponseWriter, *http.Request)) as type http.Handler in field value: func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)
2 回答
人到中年有点甜
TA贡献1895条经验 获得超7个赞
您要么使用结构并ServeHTTP在其上定义,要么简单地将您的函数包装在一个HandlerFunc
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(myHandler),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
- 2 回答
- 0 关注
- 236 浏览
添加回答
举报
0/150
提交
取消