post.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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(Target{})
  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.Header().Set("Content-Type", JsonTypeHeader)
  22. w.Write(jsonFromString(`{ error: "Incomplete request body"}`))
  23. return
  24. }
  25. var target Target
  26. err = json.Unmarshal(payload, &target)
  27. if err != nil {
  28. w.WriteHeader(http.StatusBadRequest)
  29. w.Header().Set("Content-Type", JsonTypeHeader)
  30. w.Write(jsonFromString(`{ error: "Invalid JSON request"}`))
  31. return
  32. }
  33. shortString, isNew, err := domain.GetShortURL(target.Target, nil)
  34. w.Header().Set("Content-type", postContentType)
  35. if err != nil {
  36. domainErr, ok := err.(domain.Error)
  37. if ok {
  38. switch domainErr.Kind {
  39. case domain.TargetInvalid.ID:
  40. w.WriteHeader(http.StatusBadRequest)
  41. w.Header().Set("Content-Type", JsonTypeHeader)
  42. w.Write(jsonFromString(`{ error: "Invalid target requested"}`))
  43. // Covers all the domain.Storage* error cases too.
  44. default:
  45. w.WriteHeader(http.StatusInternalServerError)
  46. }
  47. } else {
  48. w.WriteHeader(http.StatusInternalServerError)
  49. }
  50. return
  51. }
  52. short := Short{Short: shortString}
  53. payload, err = json.Marshal(short)
  54. if err != nil {
  55. w.WriteHeader(http.StatusInternalServerError)
  56. w.Header().Set("Content-Type", JsonTypeHeader)
  57. w.Write(jsonFromString(`{ error: "Short URL serialization error"}`))
  58. return
  59. }
  60. if isNew {
  61. w.WriteHeader(http.StatusCreated)
  62. } else {
  63. w.WriteHeader(http.StatusConflict)
  64. }
  65. w.Header().Set("Content-Type", JsonTypeHeader)
  66. w.Write(payload)
  67. return
  68. }