router.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package auth
  2. import (
  3. "errors"
  4. "log"
  5. "net/http"
  6. )
  7. type RouterOption struct {
  8. AuthAgent *AuthAgent
  9. RequireAuth bool //This router require authentication
  10. DeniedHandler func(http.ResponseWriter, *http.Request) //Things to do when request is rejected
  11. }
  12. type RouterDef struct {
  13. option RouterOption
  14. endpoints map[string]func(http.ResponseWriter, *http.Request)
  15. }
  16. func NewManagedHTTPRouter(option RouterOption) *RouterDef {
  17. return &RouterDef{
  18. option: option,
  19. endpoints: map[string]func(http.ResponseWriter, *http.Request){},
  20. }
  21. }
  22. func (router *RouterDef) HandleFunc(endpoint string, handler func(http.ResponseWriter, *http.Request)) error {
  23. //Check if the endpoint already registered
  24. if _, exist := router.endpoints[endpoint]; exist {
  25. log.Println("WARNING! Duplicated registering of web endpoint: " + endpoint)
  26. return errors.New("endpoint register duplicated")
  27. }
  28. authAgent := router.option.AuthAgent
  29. //OK. Register handler
  30. http.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
  31. //Check authentication of the user
  32. if router.option.RequireAuth {
  33. authAgent.HandleCheckAuth(w, r, func(w http.ResponseWriter, r *http.Request) {
  34. handler(w, r)
  35. })
  36. } else {
  37. handler(w, r)
  38. }
  39. })
  40. router.endpoints[endpoint] = handler
  41. return nil
  42. }