handler.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. func (t *RuleTable) HandleRedirect(w http.ResponseWriter, r *http.Request) {
  21. requestPath := r.Host + r.URL.Path
  22. rr := t.MatchRedirectRule(requestPath)
  23. if rr != nil {
  24. redirectTarget := rr.TargetURL
  25. //Always pad a / at the back of the target URL
  26. if redirectTarget[len(redirectTarget)-1:] != "/" {
  27. redirectTarget += "/"
  28. }
  29. if rr.ForwardChildpath {
  30. //Remove the first / in the path
  31. redirectTarget += r.URL.Path[1:] + "?" + r.URL.RawQuery
  32. }
  33. if !strings.HasPrefix(redirectTarget, "http://") && !strings.HasPrefix(redirectTarget, "https://") {
  34. redirectTarget = "http://" + redirectTarget
  35. }
  36. http.Redirect(w, r, redirectTarget, rr.StatusCode)
  37. } else {
  38. //Invalid usage
  39. w.WriteHeader(http.StatusInternalServerError)
  40. w.Write([]byte("500 - Internal Server Error"))
  41. log.Println("Target request URL do not have matching redirect rule. Check with IsRedirectable before calling HandleRedirect!")
  42. }
  43. }