golang http 服務器的接口梳理
Hanlde和HandleFunc以及Handler, HandlerFunc
func Handle(pattern string, handler Handler)
// Handle 函數將pattern和對應的handler注冊進DefaultServeMux
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
// HandleFunc registers the handler function for the given pattern in the DefaultServeMux
// Handler
//
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
// HandlerFunc能夠將一個普通的處理函數轉化為Handler
type HandlerFunc func(ResponseWriter, *Request)
HandleFunc僅接受一個func為參數,相對於簡潔些。Handle則需要傳入一個帶有ServeHTTP的結構體,因此控制邏輯可以靈活些。
Handle的例子
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
type countHandler struct {
mu sync.Mutex // guards n
n int
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
h.n++
fmt.Fprintf(w, "count is %d\n", h.n)
}
func main() {
http.Handle("/count", new(countHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
HandleFunc的例子
h1 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #1!\n")
}
h2 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #2!\n")
}
http.HandleFunc("/", h1)
http.HandleFunc("/endpoint", h2)
log.Fatal(http.ListenAndServe(":8080", nil))
server := &http.Server{
Addr: ":8000",
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
server.ListenAndServe()
}
// 自定義的serverMux對象也可以傳到server對象中。
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", index)
server := &http.Server{
Addr: ":8000",
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
Handler: mux,
}
server.ListenAndServe()
}