Skip to content

Commit

Permalink
中间件示例
Browse files Browse the repository at this point in the history
  • Loading branch information
alonelucky committed Aug 1, 2017
1 parent 5226fac commit de134b7
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions test/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"net/http"
"fmt"
)

// 中间件
func logMiddle(next http.Handler) http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){
fmt.Println("middle log")
next.ServeHTTP(w,r)
})
}
// 中间件2
func hook(next http.Handler) http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
fmt.Println("hook log",r.URL.Path)
next.ServeHTTP(w,r)
})
}

// 首页
func index(w http.ResponseWriter,r *http.Request){
if r.URL.Path != "/"{
return
}
w.Write([]byte("hello"))
fmt.Println("index log")
}

func main() {

http.Handle("/api",logMiddle(hook(http.HandlerFunc(index))))
http.Handle("/",hook(http.HandlerFunc(index)))

http.ListenAndServe(":8000",nil)
}

0 comments on commit de134b7

Please sign in to comment.