我是新手,试图编写自定义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