package api import ( "code.osinet.fr/fgm/kurz/web/i18n" "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.Header().Set("Content-Type", JsonTypeHeader) w.Write(jsonFromString(`{ error: "Incomplete request body"}`)) return } var target Target err = json.Unmarshal(payload, &target) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Header().Set("Content-Type", JsonTypeHeader) w.Write(jsonFromString(`{ error: "Invalid JSON request"}`)) return } shortString, isNew, err := domain.GetShortURL(target.Target, i18n.Localizer(r)) w.Header().Set("Content-type", postContentType) if err != nil { domainErr, ok := err.(domain.Error) if ok { switch domainErr.Kind { case domain.TargetInvalid.ID: w.WriteHeader(http.StatusBadRequest) w.Header().Set("Content-Type", JsonTypeHeader) 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.Header().Set("Content-Type", JsonTypeHeader) w.Write(jsonFromString(`{ error: "Short URL serialization error"}`)) return } if isNew { w.WriteHeader(http.StatusCreated) } else { w.WriteHeader(http.StatusConflict) } w.Header().Set("Content-Type", JsonTypeHeader) w.Write(payload) return }