code-examples/2024/07/golang_demo1/main.go

49 lines
968 B
Go

package main
import (
"context"
"flag"
"fmt"
"github.com/go-pg/pg/v10"
"golang_demo1/handlers"
"net/http"
)
func main() {
var opt, errDb = pg.ParseURL("postgres://db_user:pass@localhost:5432/repo?sslmode=disable")
if errDb != nil {
panic("Failed to parse url: " + errDb.Error())
}
var db = pg.Connect(opt)
if db == nil {
panic("failed to connect to the database")
}
defer func(db *pg.DB) {
_ = db.Close()
}(db)
ctx := context.Background()
if err := db.Ping(ctx); err != nil {
panic("Failed to ping: " + err.Error())
}
portPtr := flag.Int("port", 8080, "port for webserver")
flag.Parse()
port := *portPtr
fmt.Printf("Server is listening on port: %d", port)
server := http.NewServeMux()
server.HandleFunc("/status", handlers.StatusHandler)
server.HandleFunc("/greeting", handlers.GreetingHandler)
err := http.ListenAndServe(fmt.Sprintf("localhost:%d", port), server)
if err != nil {
fmt.Println("Error:", err)
return
}
}