亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中編寫一個簡單的自定義 HTTP 服務器?

如何在 Go 中編寫一個簡單的自定義 HTTP 服務器?

Go
慕村9548890 2021-08-16 15:15:22
我是 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,

}


查看完整回答
反對 回復 2021-08-16
  • 2 回答
  • 0 關注
  • 260 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號