Skip to content

Instantly share code, notes, and snippets.

@kumakichi
Last active April 29, 2016 06:50
Show Gist options
  • Save kumakichi/e39bf8f1a463fa57eb496e8f013247a3 to your computer and use it in GitHub Desktop.
Save kumakichi/e39bf8f1a463fa57eb496e8f013247a3 to your computer and use it in GitHub Desktop.
A SimpleHTTPServer with authentication written in golang
package main
import (
"encoding/base64"
"fmt"
"net/http"
"os"
)
var (
authStr string
realHandler http.Handler
)
func askForAuth(w http.ResponseWriter) {
w.Header().Set("WWW-Authenticate", `Basic realm="Please Login"`)
w.Header().Set("Content-type", "text/html")
w.WriteHeader(http.StatusUnauthorized)
}
func checkAuth(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
switch auth {
case "": // no such header
askForAuth(w)
w.Write([]byte("no auth header received"))
case authStr: // passed
realHandler.ServeHTTP(w, r)
default: // header existed but invalid
askForAuth(w)
w.Write([]byte("not authenticated"))
}
}
func main() {
if len(os.Args) != 4 {
fmt.Printf("Usage: %s port user password", os.Args[0])
os.Exit(0)
}
authStr = calcAuthStr(os.Args[2], os.Args[3])
realHandler = http.FileServer(http.Dir("."))
host := fmt.Sprintf(":%s", os.Args[1])
http.HandleFunc("/", checkAuth)
http.ListenAndServe(host, nil)
}
func calcAuthStr(usr, pwd string) string {
msg := []byte(usr + ":" + pwd)
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
base64.StdEncoding.Encode(encoded, msg)
return "Basic " + string(encoded)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment