Added some routes for users
And some fixes
This commit is contained in:
@@ -2,34 +2,65 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
core "fr.latosa-escrima/api/core"
|
||||
)
|
||||
|
||||
func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
w.Write([]byte(`{"message": "Resource created successfully"}`))
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: "This method is not allowed",
|
||||
}.Respond(w, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
user := &core.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "john.doe@example.com",
|
||||
Phone: "1234567890",
|
||||
Password: "1234",
|
||||
}
|
||||
|
||||
_, err := core.DB.NewInsert().Model(user).Exec(context.Background())
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: "The body of your message is invalid.",
|
||||
}.Respond(w, http.StatusNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("User inserted successfully")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"message": "Inserted the user"}`))
|
||||
var user core.User
|
||||
err = json.Unmarshal(body, &user)
|
||||
if err != nil {
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: "It seems your body in invalid JSON.",
|
||||
}.Respond(w, http.StatusNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println(user)
|
||||
|
||||
res, err := core.DB.NewInsert().Model(user).Exec(context.Background())
|
||||
if res == nil {
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: "The user couldn't be inserted.",
|
||||
}.Respond(w, http.StatusNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: err.Error(),
|
||||
}.Respond(w, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
core.JSONSuccess{
|
||||
Status: core.Success,
|
||||
Message: "User inserted successfully.",
|
||||
Data: nil,
|
||||
}.Respond(w, http.StatusCreated)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user