Go语言Web框架
一、http.Handler
package main
import (
"fmt"
"log"
"net/http"
)
type HandlerFunc func(http.ResponseWriter, *http.Request)
type Engine struct {
router map[string]HandlerFunc
}
func New() *Engine {
return &Engine{router: make(map[string]HandlerFunc)}
}
func (engine *Engine) Run(addr string) (err error) {
return http.ListenAndServe(addr, engine)
}
func (engine *Engine) addRoute(method, pattern string, handler HandlerFunc) {
key := method + "-" + pattern
log.Printf("Route %s - %s", method, pattern)
engine.router[key] = handler
}
func (engine *Engine) GET(pattern string, handler HandlerFunc) {
engine.addRoute("GET", pattern, handler)
}
func (engine *Engine) POST(pattern string, handler HandlerFunc) {
engine.addRoute("POST", pattern, handler)
}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
key := req.Method + "-" + req.URL.Path
if handler, ok := engine.router[key]; ok {
handler(w, req)
} else {
fmt.Fprintf(w, "404 NOT FOUND: %s\n", req.URL)
}
}
func main() {
r := New()
r.GET("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w,"url parth %q\n",req.URL.Path)
})
r.GET("/hello", func(w http.ResponseWriter, req *http.Request) {
for k, v := range req.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
})
r.Run(":8090")
}
执行go run main.go 使用curl访问
$ curl http://localhost:8090/
URL.Path = “/”
$ curl http://localhost:8090/hello
Header[“Accept”] = ["/"]
Header[“User-Agent”] = [“curl/7.54.0”]
curl http://localhost:8090/world
404 NOT FOUND: /world