servauth.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package servauth
  2. import (
  3. "log"
  4. "net/http"
  5. )
  6. func BasicAuth(handler http.Handler, username, password, realm string) http.Handler {
  7. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  8. if username != "" {
  9. if realm == "" {
  10. realm = "Please enter username and password"
  11. }
  12. u, p, ok := r.BasicAuth()
  13. if !ok {
  14. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  15. w.WriteHeader(401)
  16. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  17. log.Printf("%s\n", err.Error())
  18. }
  19. return
  20. }
  21. if u != username {
  22. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  23. w.WriteHeader(401)
  24. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  25. log.Printf("%s\n", err.Error())
  26. }
  27. return
  28. }
  29. if p != password {
  30. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  31. w.WriteHeader(401)
  32. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  33. log.Printf("%s\n", err.Error())
  34. }
  35. return
  36. }
  37. }
  38. handler.ServeHTTP(w, r)
  39. })
  40. }