Skip to content

Instantly share code, notes, and snippets.

@cyx
Created November 21, 2020 01:22
Show Gist options
  • Save cyx/0983d58983441d1932340690176cade3 to your computer and use it in GitHub Desktop.
Save cyx/0983d58983441d1932340690176cade3 to your computer and use it in GitHub Desktop.
package main
import "net/http"
func main() {
http.HandleFunc("/", publicHandler)
http.HandleFunc("/admin", authenticate(adminHandler))
http.ListenAndServe(":8080", nil)
}
func authenticate(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if ok && user == "john" && pass == "secret" {
h.ServeHTTP(w, r)
return
}
w.WriteHeader(http.StatusUnauthorized)
}
}
func publicHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("public"))
}
func adminHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("admin"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment