90 lines
1.8 KiB
Go
90 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"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 {
|
|
log.Fatalf("Error loading .env file: %v", err)
|
|
}
|
|
environ := os.Getenv("ENVIRONMENT")
|
|
port := os.Getenv("BACKEND_DOCKER_PORT")
|
|
if environ == "DEV" {
|
|
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 {
|
|
fmt.Printf("Error starting server: %s\n", err)
|
|
}
|
|
}
|