LoginSignup
20
19

More than 5 years have passed since last update.

golang の net/http で basic auth

Posted at

golang の net/http で、外部モジュールをつかわずに basic 認証実装。


func checkAuth(r *http.Request) bool {
    username, password, ok := r.BasicAuth()
    if ok == false {
        return false
    }
    return username == "user" && password == "pass"
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
    if checkAuth(r) == false {
        w.Header().Set("WWW-Authenticate", `Basic realm="MY REALM"`)
        w.WriteHeader(401)
        w.Write([]byte("401 Unauthorized\n"))
        return
    }
  ...
}

func main() {
    http.HandleFunc("/", rootHandler)
  ...
}

昔は net/http に BasicAuth ってメソッドがなかったのかな? って感じ。

r.BasicAuth がかえす第3返り値の ok bool はヘッダの解析失敗時に false がくる。

✧\\ g( 'ω' )o //✧

20
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19