handler.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package redirection
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. )
  7. /*
  8. handler.go
  9. This script store the handlers use for handling
  10. redirection request
  11. */
  12. // Check if a request URL is a redirectable URI
  13. func (t *RuleTable) IsRedirectable(r *http.Request) bool {
  14. requestPath := r.Host + r.URL.Path
  15. rr := t.MatchRedirectRule(requestPath)
  16. return rr != nil
  17. }
  18. // Handle the redirect request, return after calling this function to prevent
  19. // multiple write to the response writer
  20. // Return the status code of the redirection handling
  21. func (t *RuleTable) HandleRedirect(w http.ResponseWriter, r *http.Request) int {
  22. requestPath := r.Host + r.URL.Path
  23. rr := t.MatchRedirectRule(requestPath)
  24. if rr != nil {
  25. redirectTarget := rr.TargetURL
  26. //Always pad a / at the back of the target URL
  27. if redirectTarget[len(redirectTarget)-1:] != "/" {
  28. redirectTarget += "/"
  29. }
  30. if rr.ForwardChildpath {
  31. //Remove the first / in the path
  32. redirectTarget += strings.TrimPrefix(r.URL.Path, "/")
  33. if r.URL.RawQuery != "" {
  34. redirectTarget += "?" + r.URL.RawQuery
  35. }
  36. }
  37. if !strings.HasPrefix(redirectTarget, "http://") && !strings.HasPrefix(redirectTarget, "https://") {
  38. redirectTarget = "http://" + redirectTarget
  39. }
  40. http.Redirect(w, r, redirectTarget, rr.StatusCode)
  41. return rr.StatusCode
  42. } else {
  43. //Invalid usage
  44. w.WriteHeader(http.StatusInternalServerError)
  45. w.Write([]byte("500 - Internal Server Error"))
  46. log.Println("Target request URL do not have matching redirect rule. Check with IsRedirectable before calling HandleRedirect!")
  47. return 500
  48. }
  49. }