get.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package api
  2. import (
  3. "code.osinet.fr/fgm/kurz/web/i18n"
  4. "net/http"
  5. "code.osinet.fr/fgm/kurz/domain"
  6. "github.com/gorilla/mux"
  7. )
  8. // handleGetShort() handles GET /<short>.
  9. func handleGetShort(w http.ResponseWriter, r *http.Request) {
  10. short, ok := mux.Vars(r)["short"]
  11. if !ok {
  12. w.WriteHeader(http.StatusBadRequest)
  13. return
  14. }
  15. target, err := domain.GetTargetURL(short, i18n.Localizer(r))
  16. // Happy path.
  17. if err == nil {
  18. w.Header().Set("Location", target)
  19. w.WriteHeader(http.StatusTemporaryRedirect)
  20. return
  21. }
  22. // Very sad path.
  23. domainErr, ok := err.(domain.Error)
  24. if !ok {
  25. // All errors return by the API should be domain-specific errors.
  26. w.WriteHeader(http.StatusInternalServerError)
  27. return
  28. }
  29. // Normal sad paths.
  30. var status int
  31. switch domainErr.Kind {
  32. case domain.ShortNotFound.ID:
  33. status = http.StatusNotFound
  34. case domain.TargetBlocked.ID:
  35. status = http.StatusForbidden
  36. case domain.TargetCensored.ID:
  37. status = http.StatusUnavailableForLegalReasons
  38. default:
  39. // TargetInvalid is not supposed to happen in this case, so it is an internal error too.
  40. status = http.StatusInternalServerError
  41. }
  42. w.WriteHeader(status)
  43. }