handler.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 += r.URL.Path[1:] + "?" + r.URL.RawQuery
  33. }
  34. if !strings.HasPrefix(redirectTarget, "http://") && !strings.HasPrefix(redirectTarget, "https://") {
  35. redirectTarget = "http://" + redirectTarget
  36. }
  37. http.Redirect(w, r, redirectTarget, rr.StatusCode)
  38. return rr.StatusCode
  39. } else {
  40. //Invalid usage
  41. w.WriteHeader(http.StatusInternalServerError)
  42. w.Write([]byte("500 - Internal Server Error"))
  43. log.Println("Target request URL do not have matching redirect rule. Check with IsRedirectable before calling HandleRedirect!")
  44. return 500
  45. }
  46. }