diff --git a/api/handler/mainHandler.go b/api/handler/mainHandler.go index 8bd2cab..006c31a 100644 --- a/api/handler/mainHandler.go +++ b/api/handler/mainHandler.go @@ -1,8 +1,6 @@ package handler -import ( - "net/http" -) +import "net/http" func CatchAllHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusGone) diff --git a/api/handler/userHandler.go b/api/handler/userHandler.go index abeebd1..111374a 100644 --- a/api/handler/userHandler.go +++ b/api/handler/userHandler.go @@ -1 +1,25 @@ package handler + +import ( + "context" + "net/http" + "portfolio-backend/database/query" +) + +func CreateUser(w http.ResponseWriter, r *http.Request) { + _, err := w.Write([]byte("test2")) + if err != nil { + InternalServerErrorHandler(w, r) + } +} + +func GetUser(w http.ResponseWriter, r *http.Request) { + user, err := query.GetUser(context.Background()) + if err != nil { + return + } + _, err = w.Write([]byte(r.PathValue(user.Name))) + if err != nil { + InternalServerErrorHandler(w, r) + } +} diff --git a/database/database.go b/database/database.go index 66da877..b438177 100644 --- a/database/database.go +++ b/database/database.go @@ -10,6 +10,8 @@ import ( _ "github.com/go-sql-driver/mysql" ) +var DBclient *ent.Client + func DB() { err := godotenv.Load() @@ -26,4 +28,6 @@ func DB() { if err := client.Schema.Create(context.Background()); err != nil { log.Fatalf("failed creating schema resources: %v", err) } + + DBclient = client } diff --git a/database/query/userQuery.go b/database/query/userQuery.go new file mode 100644 index 0000000..ccf2c60 --- /dev/null +++ b/database/query/userQuery.go @@ -0,0 +1,24 @@ +package query + +import ( + "context" + "fmt" + "log" + "portfolio-backend/database" + "portfolio-backend/database/ent" + "portfolio-backend/database/ent/user" +) + +func GetUser(ctx context.Context) (*ent.User, error) { + u, err := database.DBclient.User. + Query(). + Where(user.Name("a8m")). + // `Only` fails if no user found, + // or more than 1 user returned. + Only(ctx) + if err != nil { + return nil, fmt.Errorf("failed querying user: %w", err) + } + log.Println("user returned: ", u) + return u, nil +} diff --git a/main.go b/main.go index 65e6889..d599e5a 100644 --- a/main.go +++ b/main.go @@ -2,9 +2,8 @@ package main import ( "net/http" - "portfolio-backend/database" - "portfolio-backend/api/handler" + "portfolio-backend/database" ) func main() { @@ -18,8 +17,8 @@ func main() { // Register the routes and handlers mux.HandleFunc("/", handler.CatchAllHandler) - mux.HandleFunc("/test", handler.TestHandler) - mux.HandleFunc("/test2", handler.Test2Handler) + mux.HandleFunc("POST /user}", handler.CreateUser) + mux.HandleFunc("GET /user/{id}", handler.GetUser) // Run the server http.ListenAndServe(":4002", mux)