第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang net/http 和 Gorilla:在處理程序之前運行代碼

Golang net/http 和 Gorilla:在處理程序之前運行代碼

Go
BIG陽 2021-09-13 10:10:09
是否可以使用 net/http 包和/或任何 gorilla 庫在進入處理程序之前在每個 URL 上執(zhí)行一些代碼?例如,檢查連接是否來自列入黑名單的 IP 地址?
查看完整描述

2 回答

?
烙印99

TA貢獻1829條經(jīng)驗 獲得超13個贊

創(chuàng)建一個處理程序,在檢查 IP 地址后調用另一個處理程序:


type checker struct {

   h http.Handler

}


func (c checker) ServeHTTP(w http.ResponseWriter, r *http.Request) {

   if blackListed(r.RemoteAddr) {

      http.Error(w, "not authorized", http.StatusForbidden)

      return

   }

   c.h.ServeHTTP(w, r)

}

將此處理程序傳遞給 ListenAndServe 而不是您的原始處理程序。例如,如果您有:


err := http.ListenAndServe(addr, mux)

將代碼更改為


err := http.ListenAndServe(addr, checker{mux})

這也適用于 ListenAndServe 的所有變體。它適用于 http.ServeMux、Gorilla mux 和其他路由器。


查看完整回答
反對 回復 2021-09-13
?
函數(shù)式編程

TA貢獻1807條經(jīng)驗 獲得超9個贊

如果您想使用我發(fā)現(xiàn)很常見的默認多路復用器,您可以像這樣創(chuàng)建中間件:


func mustBeLoggedIn(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {

    return func(w http.ResponseWriter, r *http.Request) {

        // Am i logged in?

        if ...not logged in... {

            http.Error(w, err.Error(), http.StatusUnauthorized)

            return

        }

        // Pass through to the original handler.

        handler(w, r)

    }

}

像這樣使用它:


http.HandleFunc("/some/priveliged/action", mustBeLoggedIn(myVanillaHandler))

http.ListenAndServe(":80", nil)


查看完整回答
反對 回復 2021-09-13
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號