-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
51 lines (40 loc) · 1.18 KB
/
update.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
package handlers
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/devbersi/finance-go/models"
"github.com/go-chi/chi"
)
func Update(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
log.Printf("Erro ao tentar fazer o parse: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var expense models.Expense
err = json.NewDecoder(r.Body).Decode(&expense)
if err != nil {
log.Printf("Erro ao fazer decode do json: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
rows, err := models.Update(int64(id), expense)
if err != nil {
log.Printf("Erro ao atualizar registro: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if rows > 1 {
log.Printf("Error: foram atualizados %d registros", rows)
}
resp :=map[string]any {
"Error": false,
"Message": fmt.Sprintf("Expense atualizado com sucesso! ID: %v", id),
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}