123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- 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([]byte(s))
- 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
- }
- wrapper := struct{ Target string }{}
- err = json.Unmarshal(payload, &wrapper)
- if err != nil {
- w.WriteHeader(http.StatusBadRequest)
- w.Write(jsonFromString(`{ error: "Invalid JSON request"}`))
- return
- }
- su, isNew, err := domain.GetShortURL(wrapper.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
- }
- payload, err = json.Marshal(su)
- 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
- }
|