Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
serve static files / directory with http basic auth in Go
/*
Simple static file server with http basic auth in go
Usage:
-p="8100": port to serve on
-d=".": the directory of static files to host
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"flag"
"log"
"net/http"
auth "github.com/abbot/go-http-auth"
)
//Secret ...
//Use https://unix4lyfe.org/crypt to generate an md5 hash + salt
func Secret(user, realm string) string {
switch user {
case "kitallis":
return "$1$eq9ct8Co$gR4Oluc5k4xVQFJPEnr9Y." // password is "hello"
case "guest":
return "$1$wZRWVGXc$wTmEmVCZFpNt2Xt3Fwdxl0" // password is "R#A?hx<MzU6F:pj5"
default:
return ""
}
}
func main() {
port := flag.String("p", "8100", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
flag.Parse()
authenticator := auth.NewBasicAuthenticator("baitai", Secret)
http.HandleFunc("/", authenticator.Wrap(func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
http.FileServer(http.Dir(*directory)).ServeHTTP(w, &r.Request)
}))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment