-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_create_user.go
47 lines (40 loc) · 1.35 KB
/
db_create_user.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"
"log"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
// createUser handles the creation of a new user based on the provided request body.
// It decodes the JSON request body into a User struct and performs validation on the user data.
// If the user data is invalid (empty username or password), it returns a 400 Bad Request status.
// Otherwise, it inserts the user into the database using a prepared statement.
// If there is an error inserting the user, it returns a 500 Internal Server Error status.
// Otherwise, it returns a success response with a 201 Created status.
func CreateUser(w http.ResponseWriter, r *http.Request) {
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Perform validation on the user data
if user.Username == "" || user.Password == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Insert the user into the database
stmt, err := db.Prepare("INSERT INTO users(username, password) VALUES(?, ?)")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = stmt.Exec(user.Username, user.Password)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// Return a success response
log.Println("User creation successful")
w.WriteHeader(http.StatusCreated)
}