-
Notifications
You must be signed in to change notification settings - Fork 0
/
hanlder_user_create.go
48 lines (40 loc) · 1.05 KB
/
hanlder_user_create.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
package main
import (
"encoding/json"
"math/rand"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"github.com/miguelvalente/smooth_aggregator/internal/database"
)
func randomString(length int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var sb strings.Builder
sb.Grow(length)
for i := 0; i < length; i++ {
sb.WriteRune(letters[rand.Intn(len(letters))])
}
return sb.String()
}
func (apiCfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Name string `json:"name"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
user := database.CreateUserParams{
ID: uuid.New(),
Name: params.Name,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
ApiKey: randomString(64),
}
apiCfg.DB.CreateUser(r.Context(), user)
respondWithJSON(w, http.StatusOK, user)
}