diff options
Diffstat (limited to 'view/json.go')
| -rw-r--r-- | view/json.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/view/json.go b/view/json.go new file mode 100644 index 0000000..5f3a30c --- /dev/null +++ b/view/json.go @@ -0,0 +1,65 @@ +package view + +import ( + "encoding/json" + "io" + "log" + "net/http" + "strconv" + + "xengineering.eu/ceres/model" +) + +func CreateJSON[O model.Object](db *model.DB, constructor func() model.Object) http.Handler { + return http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + buf, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + object := constructor() + err = json.Unmarshal(buf, &object) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + err = db.Transaction(object.Create) + if err != nil { + log.Println("Could not create object.") + http.Error(w, "Could not create object.", http.StatusBadRequest) + return + } + }, + ) +} + +func ReadJSON[O model.Object](db *model.DB, constructor func() model.Object) http.Handler { + return http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + object := constructor() + + id, err := strconv.Atoi(r.PathValue("id")) + if err != nil { + // TODO + return + } + object.SetID(id) + + err = db.Transaction(object.Read) + if err != nil { + // TODO + return + } + + w.Header().Set("Content-Type", "application/json") + err = json.NewEncoder(w).Encode(object) + if err != nil { + // TODO + return + } + }, + ) +} |
