package api import ( "code.osinet.fr/fgm/kurz/web/i18n" "net/http" "code.osinet.fr/fgm/kurz/domain" "github.com/gorilla/mux" ) // handleGetShort() handles GET /. func handleGetShort(w http.ResponseWriter, r *http.Request) { short, ok := mux.Vars(r)["short"] if !ok { w.WriteHeader(http.StatusBadRequest) return } target, err := domain.GetTargetURL(short, i18n.Localizer(r)) // Happy path. if err == nil { w.Header().Set("Location", target) w.WriteHeader(http.StatusTemporaryRedirect) return } // Very sad path. domainErr, ok := err.(domain.Error) if !ok { // All errors return by the API should be domain-specific errors. w.WriteHeader(http.StatusInternalServerError) return } // Normal sad paths. var status int switch domainErr.Kind { case domain.ShortNotFound.ID: status = http.StatusNotFound case domain.TargetBlocked.ID: status = http.StatusForbidden case domain.TargetCensored.ID: status = http.StatusUnavailableForLegalReasons default: // TargetInvalid is not supposed to happen in this case, so it is an internal error too. status = http.StatusInternalServerError } w.WriteHeader(status) }