Skip to content

Instantly share code, notes, and snippets.

@hirochachacha
Created August 23, 2014 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirochachacha/fdab3f0e6b925a5ba746 to your computer and use it in GitHub Desktop.
Save hirochachacha/fdab3f0e6b925a5ba746 to your computer and use it in GitHub Desktop.
package app
import (
"encoding/base64"
"net/http"
)
func Basic(username, password string) http.Handler {
credential := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return &basicHandler{credential}
}
type basicHandler struct {
credential string
}
func (bh *basicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
credential := r.Header.Get("Authorization")
if len(credential) <= 6 || credential[6:] != bh.credential {
w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
}
}
package app
import (
"net/http"
)
func Chain(handlers ...http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rw := newResponseWriter(w)
for _, h := range handlers {
h.ServeHTTP(rw, r)
if rw.written {
return
}
}
}
}
func ChainFunc(handlers ...http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rw := newResponseWriter(w)
for _, h := range handlers {
h(rw, r)
if rw.written {
return
}
}
}
}
type responseWriter struct {
http.ResponseWriter
written bool
}
func newResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{w, false}
}
func (rw *responseWriter) Write(bs []byte) (int, error) {
rw.written = true
return rw.ResponseWriter.Write(bs)
}
func (rw *responseWriter) WriteHeader(i int) {
rw.written = true
rw.ResponseWriter.WriteHeader(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment