123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 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.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, nil)
- 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
- }
|