handler.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package redirection
  2. import (
  3. "errors"
  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. if rr.ForwardChildpath {
  27. //Remove the first / in the path if the redirect target already have tailing slash
  28. if strings.HasSuffix(redirectTarget, "/") {
  29. redirectTarget += strings.TrimPrefix(r.URL.Path, "/")
  30. } else {
  31. redirectTarget += r.URL.Path
  32. }
  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. t.log("Target request URL do not have matching redirect rule. Check with IsRedirectable before calling HandleRedirect!", errors.New("invalid usage"))
  47. return 500
  48. }
  49. }