Go HTTP Middleware學習2

使用第三方中間件

很多第三方庫提供了不同類型的可重用的中間件組件,可以用在很多共同的功能:比如授權(quán),登錄,壓縮響應頭等.當使用Go開發(fā)一個web應用,可以使用這些第三方庫應用到自己的項目中.

  • 使用Gorilla Handlers

這個開發(fā)組件提供了很多net/http包下的handlers.
一個使用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()

}

//運行時訪問日志信息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查找對應的文檔,查閱. Alice;Negroni.

  • 在中間件分享值

有時候,我們需要提供值給下一個handler或者在應用的handler和中間件的handler共享值.比如,當通過一個中間件的handler授權(quán)應用的權(quán)限,就需要在請求的handler環(huán)中提供用戶的信息給下一個handler.

使用Gorilla上下文.

很多第三庫允許在請求的生命周期里保存值,用來共享,Gorilla的context包是一個非常好的選擇,用來在請求的生命周期里共享數(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")
}

一個中間件的handler被創(chuàng)建,用來驗證HTTP請求,HTTP頭 的 "X-AppToken"從請求對象讀取的驗證token.這也是RESTful APIs驗證的方式之一:客戶端必須在請求頭發(fā)送一個驗證的token.還有的方式是通過session驗證.
在這個程序,我們想傳遞用戶名給下一個handler:應用的handler.因此在context對象設(shè)置了user的值,這個值在請求的生命周期里面都可以訪問到.比如這里的index handler就訪問這個user的值.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,839評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,527評論 19 139
  • HTTP 中間件 HTTP中間件,在現(xiàn)實項目開發(fā)中簡化了很多工作,Go開發(fā)社區(qū)還沒有很大的興趣吸收成熟的web開發(fā)...
    小Q逛逛閱讀 3,925評論 0 5
  • 這篇文章是 Golang 開源庫 Negroni 的 README.md 中推薦一篇的文章,講的是 Golang ...
    王諳然閱讀 7,555評論 0 6
  • 紅綠燈火,閃爍 引著漁船,回航 橙紅彎月,倒映 在墨一般的海上 伴著你的影 波光瀲滟,浮動 撩撥了誰的心海 風輕拂...
    布小夭閱讀 270評論 0 0

友情鏈接更多精彩內(nèi)容