12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package api
- import (
- "encoding/json"
- "io/ioutil"
- "net/http"
- "code.osinet.fr/fgm/kurz/domain"
- )
- const postContentType = "application/json"
- func jsonFromString(s string) []byte {
- j, err := json.Marshal(Target{})
- if err != nil {
- panic(err)
- }
- return j
- }
- // handlePostTarget() handles "POST /" with { "target": "some target" }.
- func handlePostTarget(w http.ResponseWriter, r *http.Request) {
- payload, err := ioutil.ReadAll(r.Body)
- if err != nil {
- w.WriteHeader(http.StatusBadRequest)
- w.Write(jsonFromString(`{ error: "Incomplete request body"}`))
- return
- }
- var target Target
- err = json.Unmarshal(payload, &target)
- if err != nil {
- w.WriteHeader(http.StatusBadRequest)
- w.Write(jsonFromString(`{ error: "Invalid JSON request"}`))
- return
- }
- shortString, isNew, err := domain.GetShortURL(target.Target)
- w.Header().Set("Content-type", postContentType)
- if err != nil {
- domainErr, ok := err.(domain.Error)
- if ok {
- switch domainErr.Kind {
- case domain.TargetInvalidError:
- w.WriteHeader(http.StatusBadRequest)
- w.Write(jsonFromString(`{ error: "Invalid target requested"}`))
- // Covers all the domain.Storage* error cases too.
- default:
- w.WriteHeader(http.StatusInternalServerError)
- }
- } else {
- w.WriteHeader(http.StatusInternalServerError)
- }
- return
- }
- short := Short{Short: shortString}
- payload, err = json.Marshal(short)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- w.Write(jsonFromString(`{ error: "Short URL serialization error"}`))
- return
- }
- if isNew {
- w.WriteHeader(http.StatusCreated)
- } else {
- w.WriteHeader(http.StatusConflict)
- }
- w.Write(payload)
- return
- }
|