使用第三方中間件
很多第三方庫提供了不同類型的可重用的中間件組件,可以用在很多共同的功能:比如授權(quán),登錄,壓縮響應(yīng)頭等.當(dāng)使用Go開發(fā)一個(gè)web應(yīng)用,可以使用這些第三方庫應(yīng)用到自己的項(xiàng)目中.
- 使用Gorilla Handlers
這個(gè)開發(fā)組件提供了很多net/http包下的handlers.
一個(gè)使用Gorilla的LoggingHandler和CompressHandler的例子
// Gorilla Handlers
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
)
func index(w http.ResponseWriter, r *http.Request) {
log.Println("Execute index Handler")
fmt.Fprintf(w, "Welcome!")
}
func about(w http.ResponseWriter, r *http.Request) {
log.Println("Execute message Handler")
fmt.Fprintf(w, "Message Go!")
}
func main() {
indexHandler := http.HandlerFunc(index)
aboutHandler := http.HandlerFunc(about)
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler)))
http.Handle("about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler)))
server := &http.Server{
Addr: ":9090",
}
log.Println("Listening...")
server.ListenAndServe()
}
//運(yùn)行時(shí)訪問日志信息server.log
::1 - - [29/Jul/2016:18:48:22 +0800] "GET / HTTP/1.1" 200 32
::1 - - [29/Jul/2016:18:48:25 +0800] "GET / HTTP/1.1" 200 32
::1 - - [29/Jul/2016:18:48:38 +0800] "GET /about HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:24:51 +0800] "GET / HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:24:51 +0800] "GET /favicon.ico HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:24:54 +0800] "GET / HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:24:54 +0800] "GET /favicon.ico HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:25:35 +0800] "GET /about HTTP/1.1" 200 32
::1 - - [02/Aug/2016:08:25:35 +0800] "GET /favicon.ico HTTP/1.1" 200 32
此外,還有很多的第三方庫,可以到Github查找對應(yīng)的文檔,查閱. Alice;Negroni.
- 在中間件分享值
有時(shí)候,我們需要提供值給下一個(gè)handler或者在應(yīng)用的handler和中間件的handler共享值.比如,當(dāng)通過一個(gè)中間件的handler授權(quán)應(yīng)用的權(quán)限,就需要在請求的handler環(huán)中提供用戶的信息給下一個(gè)handler.
使用Gorilla上下文.
很多第三庫允許在請求的生命周期里保存值,用來共享,Gorilla的context包是一個(gè)非常好的選擇,用來在請求的生命周期里共享數(shù)據(jù).
使用context的例子
package main
import (
"fmt"
"log"
"net/http"
"github.com/codegangsta/negroni"
"github.com/gorilla/context"
)
func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
token := r.Header.Get("X-AppToken")
if token == "1l9o9v0e" {
log.Printf("Authorized to the system!")
context.Set(r, "user", "xiaoming")
next(w, r)
} else {
http.Error(w, "Not Authorized", 401)
}
}
func index(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user")
fmt.Fprintf(w, "Welcome %s!", user)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", index)
n := negroni.Classic()
n.Use(negroni.HandlerFunc(Authorize))
n.UseHandler(mux)
n.Run(":9090")
}
一個(gè)中間件的handler被創(chuàng)建,用來驗(yàn)證HTTP請求,HTTP頭 的 "X-AppToken"從請求對象讀取的驗(yàn)證token.這也是RESTful APIs驗(yàn)證的方式之一:客戶端必須在請求頭發(fā)送一個(gè)驗(yàn)證的token.還有的方式是通過session驗(yàn)證.
在這個(gè)程序,我們想傳遞用戶名給下一個(gè)handler:應(yīng)用的handler.因此在context對象設(shè)置了user的值,這個(gè)值在請求的生命周期里面都可以訪問到.比如這里的index handler就訪問這個(gè)user的值.