servauth.go 1013 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 realm == "" {
  9. realm = "Please enter username and password"
  10. }
  11. u, p, ok := r.BasicAuth()
  12. if !ok {
  13. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  14. w.WriteHeader(401)
  15. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  16. log.Printf("%s\n", err.Error())
  17. }
  18. return
  19. }
  20. if u != username {
  21. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  22. w.WriteHeader(401)
  23. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  24. log.Printf("%s\n", err.Error())
  25. }
  26. return
  27. }
  28. if p != password {
  29. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  30. w.WriteHeader(401)
  31. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  32. log.Printf("%s\n", err.Error())
  33. }
  34. return
  35. }
  36. handler.ServeHTTP(w, r)
  37. })
  38. }