package redirection import ( "fmt" "log" "net/http" "strings" ) /* handler.go This script store the handlers use for handling redirection request */ //Check if a request URL is a redirectable URI func (t *RuleTable) IsRedirectable(r *http.Request) bool { requestPath := r.Host + r.URL.Path rr := t.MatchRedirectRule(requestPath) return rr != nil } //Handle the redirect request, return after calling this function to prevent //multiple write to the response writer func (t *RuleTable) HandleRedirect(w http.ResponseWriter, r *http.Request) { requestPath := r.Host + r.URL.Path rr := t.MatchRedirectRule(requestPath) if rr != nil { redirectTarget := rr.TargetURL //Always pad a / at the back of the target URL if redirectTarget[len(redirectTarget)-1:] != "/" { redirectTarget += "/" } if rr.ForwardChildpath { //Remove the first / in the path redirectTarget += r.URL.Path[1:] } if !strings.HasPrefix(redirectTarget, "http://") && !strings.HasPrefix(redirectTarget, "https://") { redirectTarget = "http://" + redirectTarget } fmt.Println(redirectTarget) http.Redirect(w, r, redirectTarget, rr.StatusCode) } else { //Invalid usage w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("500 - Internal Server Error")) log.Println("Target request URL do not have matching redirect rule. Check with IsRedirectable before calling HandleRedirect!") } }