-
Notifications
You must be signed in to change notification settings - Fork 0
/
handleUser.go
47 lines (36 loc) · 1.03 KB
/
handleUser.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"github.com/zulfikar-ditya/go-course/internal/database"
)
func (APIConfig *APIConfig) handleCreateNewUser(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
type person struct {
Name string `json:"name"`
}
decoder := json.NewDecoder(r.Body)
params := person{}
err := decoder.Decode(¶ms)
if err != nil {
responseWithError(w, http.StatusBadRequest, fmt.Sprintf("Invalid request payload", err))
return
}
user, err := APIConfig.DB.CreateUser(r.Context(), database.CreateUserParams{
ID: uuid.New(),
Name: params.Name,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
})
if err != nil {
responseWithError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to create user: %s", err))
return
}
responseWithJson(w, http.StatusOK, user)
}
func (cfg *APIConfig) handlerUsersGet(w http.ResponseWriter, r *http.Request, user database.User) {
responseWithJson(w, http.StatusOK, database.User(user))
}