我是新手,試圖編寫自定義http server.Getting編譯錯誤。我如何在我的代碼中實現ServeHTTP方法?如何在Go中編寫簡單的自定義http服務器?
我的代碼:
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)
您是否在'您使用結構體和定義'中寫'and'而不是'an'? – kometen 2017-08-28 14:07:45
@kometen yep! 3歲的錯字,修復。 – OneOfOne 2017-08-28 20:37:26
我如何添加多個處理函數? – AMB 2017-12-12 05:46:26