server.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Package server is an adaptation of the basic Auth demo by Alex Edwards
  2. // on https://www.alexedwards.net/blog/basic-authentication-in-go
  3. // where it is published under an MIT license.
  4. package server
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "os"
  10. )
  11. type Auth struct {
  12. Username, Password string
  13. }
  14. type TLS struct {
  15. Cert, Key string
  16. }
  17. type Application struct {
  18. Auth
  19. TLS
  20. }
  21. func (app *Application) UnprotectedHandler(w http.ResponseWriter, r *http.Request) {
  22. fmt.Fprintln(w, "this is the unprotected handler")
  23. }
  24. func (app *Application) ProtectedHandler(w http.ResponseWriter, r *http.Request) {
  25. fmt.Fprintln(w, "this is the protected handler")
  26. }
  27. func New(user, pass, cert, ckey string) (*Application, error) {
  28. if user == "" {
  29. return nil, errors.New("invalid username: may not be empty")
  30. }
  31. if pass == "" {
  32. return nil, errors.New("invalid password: may not be empty")
  33. }
  34. if cert == "" {
  35. return nil, errors.New("invalid certificate path: may not be empty")
  36. }
  37. if _, err := os.ReadFile(cert); err != nil {
  38. return nil, fmt.Errorf("cannot read certificate file %s: %w", cert, err)
  39. }
  40. if ckey == "" {
  41. return nil, errors.New("invalid certificate key path: may not be empty")
  42. }
  43. if _, err := os.ReadFile(ckey); err != nil {
  44. return nil, fmt.Errorf("cannot read certificate key file %s: %w", cert, err)
  45. }
  46. app := &Application{
  47. Auth{Username: user, Password: pass},
  48. TLS{Cert: cert, Key: ckey},
  49. }
  50. return app, nil
  51. }