参考
- http - The Go Programming Language
- javascript - How to prevent browser to invoke basic auth popup and handle 401 error using Jquery? - Stack Overflow
実装
main.go
package main import ( "fmt" "net/http" "github.com/otiai10/marmoset" ) // BasicAuthFilter ... type BasicAuthFilter struct { next http.Handler } // ServeHTTP ... func (f BasicAuthFilter) ServeHTTP(w http.ResponseWriter, r *http.Request) { // r.SetBasicAuth("foo", "bar") if user, pass, ok := r.BasicAuth(); ok && user == "oppai" && pass == "prunprun" { f.next.ServeHTTP(w, r) } else { w.Header().Set("WWW-Authenticate", "Basic") w.WriteHeader(http.StatusUnauthorized) fmt.Fprint(w, "ノーおっぱい!") } } func main() { router := marmoset.NewRouter() router.GET("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "おっぱいぷるんぷるん") }) http.ListenAndServe(":9090", BasicAuthFilter{router}) }
メモ: BasicAuth失敗したときのレスポンスコード
http.StatusUnauthorized
== 400
メモ: ブラウザがベーシック認証のダイアログ出してくれない
レスポンスにWWW-Authenticate
ヘッダーが必要
If the WWW-Authenticate header is missing, then the browser won't prompt for credentials.
雑感
- AppEngineもGoでつくってるので、これでアプリケーションのレイヤーでBasic認証つけれるはず
DRY