通过定义接口,使用 net/http 库封装基础的功能,通过自定义函数的方式可以自定义
StandardStart.go
下面创建了两个处理接口进行实现
main.go
type Handler struct {
Path string
Process func(w http.ResponseWriter, r *http.Request)
}
func (p Handler) GetProcess() func(w http.ResponseWriter, r *http.Request) {
return p.Process
}
func (p Handler) GetPath() string {
return p.Path
}
func main() {
web := standard.TestWeb{}
printPath := Handler {
Path: "/",
Process: func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Url.Path = %q\n", r.URL.Path)
},
}
hello := Handler {
Path: "/hello",
Process: func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world")
},
}
handlers := make([]standard.Handler, 0, 2)
handlers = append(handlers, printPath, hello)
web.Start(8080, handlers)
}
1.2 基础框架(Gee)上面是通过创建函数对象进行实现,下面就通过 net/http 提供的 http.Handler 接口进行实现
package http
type Handler interface {
ServeHTTP(w ResponseWriter, r *Request)
}
func ListenAndServe(address string, h Handler) error