special.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "net/http"
  5. )
  6. /*
  7. Special.go
  8. This script handle special routing rules
  9. by external modules
  10. */
  11. type RoutingRule struct {
  12. ID string //ID of the routing rule
  13. Enabled bool //If the routing rule enabled
  14. UseSystemAccessControl bool //Pass access control check to system white/black list, set this to false to bypass white/black list
  15. MatchRule func(r *http.Request) bool
  16. RoutingHandler func(http.ResponseWriter, *http.Request)
  17. }
  18. // Router functions
  19. // Check if a routing rule exists given its id
  20. func (router *Router) GetRoutingRuleById(rrid string) (*RoutingRule, error) {
  21. for _, rr := range router.routingRules {
  22. if rr.ID == rrid {
  23. return rr, nil
  24. }
  25. }
  26. return nil, errors.New("routing rule with given id not found")
  27. }
  28. // Add a routing rule to the router
  29. func (router *Router) AddRoutingRules(rr *RoutingRule) error {
  30. _, err := router.GetRoutingRuleById(rr.ID)
  31. if err == nil {
  32. //routing rule with given id already exists
  33. return errors.New("routing rule with same id already exists")
  34. }
  35. router.routingRules = append(router.routingRules, rr)
  36. return nil
  37. }
  38. // Remove a routing rule from the router
  39. func (router *Router) RemoveRoutingRule(rrid string) {
  40. newRoutingRules := []*RoutingRule{}
  41. for _, rr := range router.routingRules {
  42. if rr.ID != rrid {
  43. newRoutingRules = append(newRoutingRules, rr)
  44. }
  45. }
  46. router.routingRules = newRoutingRules
  47. }
  48. // Get all routing rules
  49. func (router *Router) GetAllRoutingRules() []*RoutingRule {
  50. return router.routingRules
  51. }
  52. // Get the matching routing rule that describe this request.
  53. // Return nil if no routing rule is match
  54. func (router *Router) GetMatchingRoutingRule(r *http.Request) *RoutingRule {
  55. for _, thisRr := range router.routingRules {
  56. if thisRr.IsMatch(r) {
  57. return thisRr
  58. }
  59. }
  60. return nil
  61. }
  62. // Routing Rule functions
  63. // Check if a request object match the
  64. func (e *RoutingRule) IsMatch(r *http.Request) bool {
  65. if !e.Enabled {
  66. return false
  67. }
  68. return e.MatchRule(r)
  69. }
  70. func (e *RoutingRule) Route(w http.ResponseWriter, r *http.Request) {
  71. e.RoutingHandler(w, r)
  72. }