/
modify.go
54 lines (43 loc) · 1.12 KB
/
modify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package files
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi"
)
func (h *handler) Modify(rw http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
file, err := Get(h.db, int64(id))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
err = json.NewDecoder(r.Body).Decode(&file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if file.Name == "" {
http.Error(rw, ErrNameRequired.Error(), http.StatusBadRequest)
return
}
err = Update(h.db, int64(id), file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(file)
}
func Update(db *sql.DB, id int64, f *File) error {
f.ModifiedAt = time.Now()
stmt := `update "files" set "name"=$1, "modified_at"=$2, "deleted"=$3 where id=$4`
_, err := db.Exec(stmt, f.Name, f.ModifiedAt, f.Deleted, id)
return err
}