111 lines
2.5 KiB
Go
111 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
func (a *App) getFile(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
id, err := strconv.Atoi(vars["id"])
|
|
if err != nil {
|
|
respondWithError(w, http.StatusBadRequest, "Invalid file ID")
|
|
return
|
|
}
|
|
|
|
c := File{ID: id}
|
|
if err := c.getFile(a.DB); err != nil {
|
|
switch err {
|
|
case sql.ErrNoRows:
|
|
respondWithError(w, http.StatusNotFound, "File not found")
|
|
default:
|
|
respondWithError(w, http.StatusInternalServerError, err.Error())
|
|
}
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusOK, c)
|
|
}
|
|
|
|
func (a *App) getFiles(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
|
|
}
|
|
|
|
files, err := getFiles(a.DB, start, count)
|
|
if err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusOK, files)
|
|
}
|
|
|
|
func (a *App) createFile(w http.ResponseWriter, r *http.Request) {
|
|
var c File
|
|
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.createFile(a.DB); err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusCreated, c)
|
|
}
|
|
|
|
func (a *App) updateFile(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
id, err := strconv.Atoi(vars["id"])
|
|
if err != nil {
|
|
respondWithError(w, http.StatusBadRequest, "Invalid file ID")
|
|
return
|
|
}
|
|
|
|
var c File
|
|
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.updateFile(a.DB); err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusOK, c)
|
|
}
|
|
|
|
func (a *App) deleteFile(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
id, err := strconv.Atoi(vars["id"])
|
|
if err != nil {
|
|
respondWithError(w, http.StatusBadRequest, "Invalid File ID")
|
|
return
|
|
}
|
|
|
|
c := File{ID: id}
|
|
if err := c.deleteFile(a.DB); err != nil {
|
|
respondWithError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
|
|
}
|