router.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package auth
  2. import (
  3. "errors"
  4. "fmt"
  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. TargetMux *http.ServeMux
  12. }
  13. type RouterDef struct {
  14. option RouterOption
  15. endpoints map[string]func(http.ResponseWriter, *http.Request)
  16. }
  17. func NewManagedHTTPRouter(option RouterOption) *RouterDef {
  18. return &RouterDef{
  19. option: option,
  20. endpoints: map[string]func(http.ResponseWriter, *http.Request){},
  21. }
  22. }
  23. func (router *RouterDef) HandleFunc(endpoint string, handler func(http.ResponseWriter, *http.Request)) error {
  24. //Check if the endpoint already registered
  25. if _, exist := router.endpoints[endpoint]; exist {
  26. fmt.Println("WARNING! Duplicated registering of web endpoint: " + endpoint)
  27. return errors.New("endpoint register duplicated")
  28. }
  29. authAgent := router.option.AuthAgent
  30. //OK. Register handler
  31. if router.option.TargetMux == nil {
  32. http.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
  33. //Check authentication of the user
  34. if router.option.RequireAuth {
  35. authAgent.HandleCheckAuth(w, r, func(w http.ResponseWriter, r *http.Request) {
  36. handler(w, r)
  37. })
  38. } else {
  39. handler(w, r)
  40. }
  41. })
  42. } else {
  43. router.option.TargetMux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
  44. //Check authentication of the user
  45. if router.option.RequireAuth {
  46. authAgent.HandleCheckAuth(w, r, func(w http.ResponseWriter, r *http.Request) {
  47. handler(w, r)
  48. })
  49. } else {
  50. handler(w, r)
  51. }
  52. })
  53. }
  54. router.endpoints[endpoint] = handler
  55. return nil
  56. }