First query setup
multiple endpoint setup
This commit is contained in:
parent
e1c3c5c8ee
commit
13358f66b6
@ -1,8 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
import "net/http"
|
||||
|
||||
func CatchAllHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusGone)
|
||||
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
24
database/query/userQuery.go
Normal file
24
database/query/userQuery.go
Normal file
@ -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
|
||||
}
|
||||
7
main.go
7
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)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user