我是 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 關注
- 260 瀏覽
添加回答
舉報
0/150
提交
取消