package main import ( "database/sql" "encoding/json" "net/http" "strconv" "github.com/gorilla/mux" ) func (a *App) getTagValue(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid tagValue ID") return } c := TagValue{ID: id} if err := c.getTagValue(a.DB); err != nil { switch err { case sql.ErrNoRows: respondWithError(w, http.StatusNotFound, "TagValue not found") default: respondWithError(w, http.StatusInternalServerError, err.Error()) } return } respondWithJSON(w, http.StatusOK, c) } func (a *App) getTagValues(w http.ResponseWriter, r *http.Request) { count, _ := strconv.Atoi(r.FormValue("count")) start, _ := strconv.Atoi(r.FormValue("start")) if count > 10 || count < 1 { count = 10 } if start < 0 { start = 0 } tagValues, err := getTagValues(a.DB, start, count) if err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, tagValues) } func (a *App) createTagValue(w http.ResponseWriter, r *http.Request) { var t TagValue decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&t); err != nil { respondWithError(w, http.StatusBadRequest, "Invalid request payload") return } defer r.Body.Close() if err := t.createTagValue(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusCreated, t) } func (a *App) updateTagValue(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid tagValue ID") return } var c TagValue decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&c); err != nil { respondWithError(w, http.StatusBadRequest, "Invalid request payload") return } defer r.Body.Close() c.ID = id if err := c.updateTagValue(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, c) } func (a *App) deleteTagValue(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid TagValue ID") return } c := TagValue{ID: id} if err := c.deleteTagValue(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"}) } func (a *App) getLatestTagValues(w http.ResponseWriter, r *http.Request) { latesTagValues, err := getLatestTagValues(a.DB) if err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, latesTagValues) }