Skip to content

Instantly share code, notes, and snippets.

@kitallis
Last active April 16, 2023 03:18
Show Gist options
  • Save kitallis/0b8845f647e74ab86f93992be708a33c to your computer and use it in GitHub Desktop.
Save kitallis/0b8845f647e74ab86f93992be708a33c to your computer and use it in GitHub Desktop.
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