post.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package api
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "code.osinet.fr/fgm/kurz/domain"
  7. )
  8. const postContentType = "application/json"
  9. func jsonFromString(s string) []byte {
  10. j, err := json.Marshal([]byte(s))
  11. if err != nil {
  12. panic(err)
  13. }
  14. return j
  15. }
  16. // HandlePostTarget() handles "POST /" with { "target": "some target" }.
  17. func HandlePostTarget(w http.ResponseWriter, r *http.Request) {
  18. payload, err := ioutil.ReadAll(r.Body)
  19. if err != nil {
  20. w.WriteHeader(http.StatusBadRequest)
  21. w.Write(jsonFromString(`{ error: "Incomplete request body"}`))
  22. return
  23. }
  24. wrapper := struct{ Target string }{}
  25. err = json.Unmarshal(payload, &wrapper)
  26. if err != nil {
  27. w.WriteHeader(http.StatusBadRequest)
  28. w.Write(jsonFromString(`{ error: "Invalid JSON request"}`))
  29. return
  30. }
  31. su, isNew, err := domain.GetShortURL(wrapper.Target)
  32. w.Header().Set("Content-type", postContentType)
  33. if err != nil {
  34. domainErr, ok := err.(domain.Error)
  35. if ok {
  36. switch domainErr.Kind {
  37. case domain.TargetInvalidError:
  38. w.WriteHeader(http.StatusBadRequest)
  39. w.Write(jsonFromString(`{ error: "Invalid target requested"}`))
  40. // Covers all the domain.Storage* error cases too.
  41. default:
  42. w.WriteHeader(http.StatusInternalServerError)
  43. }
  44. } else {
  45. w.WriteHeader(http.StatusInternalServerError)
  46. }
  47. return
  48. }
  49. payload, err = json.Marshal(su)
  50. if err != nil {
  51. w.WriteHeader(http.StatusInternalServerError)
  52. w.Write(jsonFromString(`{ error: "Short URL serialization error"}`))
  53. return
  54. }
  55. if isNew {
  56. w.WriteHeader(http.StatusCreated)
  57. } else {
  58. w.WriteHeader(http.StatusConflict)
  59. }
  60. w.Write(payload)
  61. return
  62. }