golang 中介軟體、json返回、302跳轉
阿新 • • 發佈:2018-12-01
package main import ( "fmt" "net/http" ) func middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("前置操作") next.ServeHTTP(w, r) fmt.Println("後置操作") }) } func root(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"name":"SuperWang","hobbies":["football","programming"]}`)) } func main() { http.Handle("/jump", http.RedirectHandler("http://www.baidu.com", 302)) http.Handle("/", middleware(http.HandlerFunc(root))) err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Println(err) } }