handler.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package redirection
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "strings"
  7. )
  8. /*
  9. handler.go
  10. This script store the handlers use for handling
  11. redirection request
  12. */
  13. //Check if a request URL is a redirectable URI
  14. func (t *RuleTable) IsRedirectable(r *http.Request) bool {
  15. requestPath := r.Host + r.URL.Path
  16. rr := t.MatchRedirectRule(requestPath)
  17. return rr != nil
  18. }
  19. //Handle the redirect request, return after calling this function to prevent
  20. //multiple write to the response writer
  21. func (t *RuleTable) HandleRedirect(w http.ResponseWriter, r *http.Request) {
  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:]
  33. }
  34. if !strings.HasPrefix(redirectTarget, "http://") && !strings.HasPrefix(redirectTarget, "https://") {
  35. redirectTarget = "http://" + redirectTarget
  36. }
  37. fmt.Println(redirectTarget)
  38. http.Redirect(w, r, redirectTarget, 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. }
  45. }