/
modify.go
56 lines (44 loc) · 1.13 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
55
56
package users
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi"
)
func (h *handler) Modify(rw http.ResponseWriter, r *http.Request) {
u := new(User)
err := json.NewDecoder(r.Body).Decode(u)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if u.Name == "" {
http.Error(rw, ErrNameRequired.Error(), http.StatusBadRequest)
return
}
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
err = Update(h.db, int64(id), u)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
u, err = Get(h.db, int64(id))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(u)
}
func Update(db *sql.DB, id int64, u *User) error {
u.ModifiedAt = time.Now()
stmt := `update "users" set "name"=$1, "modified_at"=$2, "last_login"=$3 where id=$4`
_, err := db.Exec(stmt, u.Name, u.ModifiedAt, u.LastLogin, id)
return err
}