package main import ( "database/sql" "encoding/json" "net/http" "strconv" "github.com/gorilla/mux" ) func (a *App) getTag(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid tag ID") return } c := Tag{ID: id} if err := c.getTag(a.DB); err != nil { switch err { case sql.ErrNoRows: respondWithError(w, http.StatusNotFound, "Tag not found") default: respondWithError(w, http.StatusInternalServerError, err.Error()) } return } respondWithJSON(w, http.StatusOK, c) } func (a *App) getTags(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 } tags, err := getTags(a.DB, start, count) if err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, tags) } func (a *App) createTag(w http.ResponseWriter, r *http.Request) { var c Tag decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&c); err != nil { respondWithError(w, http.StatusBadRequest, "Invalid request payload") return } defer r.Body.Close() if err := c.createTag(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusCreated, c) } func (a *App) updateTag(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid tag ID") return } var c Tag 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.updateTag(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, c) } func (a *App) deleteTag(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid Tag ID") return } c := Tag{ID: id} if err := c.deleteTag(a.DB); err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"}) }