66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/joho/godotenv"
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
"github.com/uptrace/bun"
|
|
"github.com/uptrace/bun/dialect/pgdialect"
|
|
"github.com/uptrace/bun/driver/pgdriver"
|
|
_"github.com/lib/pq"
|
|
)
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
|
|
}
|
|
|
|
func handlerCreateUser(w http.ResponseWriter, r *http.Request) {
|
|
dsn:="posgres://postgres:@localhost:5432/latosa-db?sslmode=disable"
|
|
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
|
|
db := bun.NewDB(sqldb, pgdialect.New())
|
|
|
|
|
|
if r.Method != http.MethodPost {
|
|
// return an empty json
|
|
}
|
|
|
|
user := &User{
|
|
FirstName: "John",
|
|
LastName: "Doe",
|
|
Email: "john.doe@example.com",
|
|
Phone: "1234567890",
|
|
}
|
|
|
|
_, err := db.NewInsert().Model(user).Exec(context.Background())
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
fmt.Println("User inserted successfully")
|
|
}
|
|
|
|
func main() {
|
|
err := godotenv.Load()
|
|
if err != nil {
|
|
log.Fatalf("Error loading .env file: %v", err)
|
|
}
|
|
port := os.Getenv("BACKEND_PORT")
|
|
http.HandleFunc("/", handler)
|
|
|
|
http.HandleFunc("/user/new", handlerCreateUser)
|
|
|
|
fmt.Printf("Serving on port %s\n", port)
|
|
err = http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
|
|
if err != nil {
|
|
fmt.Printf("Error starting server: %s\n", err)
|
|
}
|
|
}
|
|
|