猿问

如何在 Go 中编写一个简单的自定义 HTTP 服务器?

我是 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)


慕村9548890
浏览 237回答 2
2回答

人到中年有点甜

您要么使用结构并ServeHTTP在其上定义,要么简单地将您的函数包装在一个HandlerFuncs := &http.Server{&nbsp; &nbsp; Addr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;":8080",&nbsp; &nbsp; Handler:&nbsp; &nbsp; &nbsp; &nbsp; http.HandlerFunc(myHandler),&nbsp; &nbsp; ReadTimeout:&nbsp; &nbsp; 10 * time.Second,&nbsp; &nbsp; WriteTimeout:&nbsp; &nbsp;10 * time.Second,&nbsp; &nbsp; MaxHeaderBytes: 1 << 20,}
随时随地看视频慕课网APP

相关分类

Go
我要回答