Merge remote-tracking branch 'origin/dev/guerby' into dev/cedric
This commit is contained in:
@@ -7,12 +7,55 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"context"
|
||||
|
||||
"database/sql"
|
||||
_ "github.com/lib/pq"
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/dialect/pgdialect"
|
||||
"github.com/uptrace/bun/driver/pgdriver"
|
||||
)
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
|
||||
}
|
||||
|
||||
var DB *bun.DB
|
||||
|
||||
type DSN struct {
|
||||
Hostname string
|
||||
Port string
|
||||
DBName string
|
||||
User string
|
||||
Password string
|
||||
}
|
||||
|
||||
func (dsn *DSN) ToString() string {
|
||||
return fmt.Sprintf("posgres://%s:%s@%s:%s/%s?sslmode=disable", dsn.User, dsn.Password, dsn.Hostname, dsn.Port, dsn.DBName)
|
||||
}
|
||||
|
||||
func handlerCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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 {
|
||||
@@ -24,7 +67,20 @@ func main() {
|
||||
port = os.Getenv("BACKEND_PORT")
|
||||
}
|
||||
|
||||
dsn := DSN{
|
||||
Hostname: "localhost",
|
||||
Port: port,
|
||||
DBName: os.Getenv("POSTGRES_DB"),
|
||||
User: os.Getenv("POSTGRES_USER"),
|
||||
Password: os.Getenv("POSTGRES_PASSWORD"),
|
||||
}
|
||||
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString())))
|
||||
DB = bun.NewDB(sqldb, pgdialect.New())
|
||||
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user