get.go 1.1 KB

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