post.go 1.9 KB

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