我是 Go 新手,正在尝试编写一个自定义 HTTP 服务器。我收到编译错误。我该如何实施ServeHTTP
我的代码中的方法?
My Code:
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)
您可以使用结构并定义ServeHTTP
在它上面或者简单地将你的函数包装在HandlerFunc http://golang.org/pkg/net/http/#HandlerFunc
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(myHandler),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)