通过map来保存你注册的 handler , 底层通过ServeHTTP来进行转发。
每个handler只有一个方法ServeHTTP,所以可以在ServeHTTP中进行路由的转发
server3.go
package main
import (
"io"
"net/http"
"log"
"time"
)
var muxmap[string] func(http.ResponseWriter, *http.Request)
func main () {
server := &http.Server{
Addr:":6077",
Handler:&NewHandler{},
ReadTimeout:5 * time.Second,
}
// 路由注册
mux = make(map[string]func(http.ResponseWriter, *http.Request))
mux["/hello"] = sayThree
mux["/say"] = sayFive
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
type NewHandlerstruct {}
func (*NewHandler)ServeHTTP(w http.ResponseWriter, r *http.Request) {
if fun, ok := mux[r.URL.String()]; ok {
fun(w, r)
return
}
io.WriteString(w, "URL:" + r.URL.String())
}
func sayThree (w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "this is version 3")
}
func sayFive (w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "this is version 4")
}
go run server3.go
网友评论