post.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.Write(jsonFromString(`{ error: "Incomplete request body"}`))
  22. return
  23. }
  24. var target Target
  25. err = json.Unmarshal(payload, &target)
  26. if err != nil {
  27. w.WriteHeader(http.StatusBadRequest)
  28. w.Write(jsonFromString(`{ error: "Invalid JSON request"}`))
  29. return
  30. }
  31. shortString, isNew, err := domain.GetShortURL(target.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. short := Short{Short: shortString}
  50. payload, err = json.Marshal(short)
  51. if err != nil {
  52. w.WriteHeader(http.StatusInternalServerError)
  53. w.Write(jsonFromString(`{ error: "Short URL serialization error"}`))
  54. return
  55. }
  56. if isNew {
  57. w.WriteHeader(http.StatusCreated)
  58. } else {
  59. w.WriteHeader(http.StatusConflict)
  60. }
  61. w.Write(payload)
  62. return
  63. }