mirror of
https://github.com/NotAShelf/httpserve.git
synced 2024-11-01 11:01:19 +00:00
feat: basic authentication
This commit is contained in:
parent
14a55bd77d
commit
11585b3662
2 changed files with 21 additions and 3 deletions
|
@ -15,8 +15,8 @@ httpserve -p <PORT> -a <ADDRESS> -f <FILENAME> -c <CONTENT_TYPE>
|
|||
- `-a <ADDRESS>`: Set the address for the server (default: 0.0.0.0)
|
||||
- `-f <FILENAME>`: Set the filename header for downloaded content
|
||||
- `-c <CONTENT_TYPE>`: Set the content-type header (default: application/octet-stream)
|
||||
|
||||
> Replace `<PORT>`, `<ADDRESS>`, `<FILENAME>`, and `<CONTENT_TYPE>` with your preferred values.
|
||||
- `-user <USERNAME>`: The user that will be used in authentication prompts
|
||||
- `-password <PASSWORD>`: The password required to access served data
|
||||
|
||||
### Examples
|
||||
|
||||
|
|
20
main.go
20
main.go
|
@ -42,12 +42,30 @@ var (
|
|||
address = flag.String("a", "0.0.0.0", "Address (default: 0.0.0.0)")
|
||||
fileName = flag.String("f", "", "Set filename header")
|
||||
contentType = flag.String("c", "application/octet-stream", "Set content-type header (default: application/octet-stream)")
|
||||
username = flag.String("user", "", "Username for basic authentication")
|
||||
password = flag.String("password", "", "Password for basic authentication")
|
||||
)
|
||||
|
||||
func basicAuth(handler http.Handler, username, password string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if username != "" || password != "" {
|
||||
user, pass, ok := r.BasicAuth()
|
||||
if !ok || user != username || pass != password {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="Please enter your credentials"`)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte("Unauthorized access"))
|
||||
return
|
||||
}
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
http.Handle("/", &requestHandler{})
|
||||
authHandler := basicAuth(&requestHandler{}, *username, *password)
|
||||
http.Handle("/", authHandler)
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", *address, *port)
|
||||
log.Printf("Server starting on %s\n", addr)
|
||||
|
|
Loading…
Reference in a new issue