Last active
April 16, 2023 03:18
-
-
Save kitallis/0b8845f647e74ab86f93992be708a33c to your computer and use it in GitHub Desktop.
serve static files / directory with http basic auth in Go
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
/* | |
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