我是 Go 新手,正在尝试编写自定义 HTTP 服务器。我收到编译错误。如何ServeHTTP在我的代码中实现该方法?
我的代码:
package main
import (
"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)
人到中年有点甜
相关分类