Tôi mới dùng Go và cố gắng viết một máy chủ http tùy chỉnh.Đặt lỗi biên dịch. Làm thế nào tôi có thể thực hiện các phương pháp ServeHTTP trong mã của tôi?Làm thế nào để viết một máy chủ http tùy chỉnh đơn giản trong Go?
Mã của tôi:
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())
}
}
Lỗi khi biên dịch:
.\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)
Ý của bạn là viết 'và' thay vì 'an' trong 'Bạn có sử dụng cấu trúc định nghĩa' không? – kometen
@kometen yep! wow 3 năm lỗi đánh máy cũ, sửa chữa. – OneOfOne
Tôi có thể thêm nhiều chức năng xử lý bằng cách nào? – AMB