Created
August 23, 2014 05:48
-
-
Save hirochachacha/fdab3f0e6b925a5ba746 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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