package main
import (
"context"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
_ "github.com/lib/pq"
migrate "github.com/rubenv/sql-migrate"
)
func main() {
SetupDatabase()
router := http.NewServeMux()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
fmt.Fprintln(w, map[string]interface{}{"data": "hello wordl"})
})
SetupGraceFullShutdown(router)
}
func SetupDatabase() *sql.DB {
driver_name := "postgres"
dsn_url := "postgres://admin:admin@localhost:5432/postgres?sslmode=disable"
migration_dir := "./database/migrations"
db, _ := sql.Open(driver_name, dsn_url)
if err := db.Ping(); err != nil {
log.Fatalf("Database connection error: %s", err.Error())
}
if os.Getenv("GO_ENV") == "development" {
migrations := migrate.FileMigrationSource{
Dir: migration_dir,
}
if _, err := migrations.FindMigrations(); err != nil {
log.Fatalf("Find migration database error: %s", err.Error())
}
if _, err := migrate.Exec(db, driver_name, migrations, migrate.Up); err != nil {
log.Fatalf("Execute migration database error: %s", err.Error())
}
}
defer log.Println("Database connection success")
return db
}
func SetupGraceFullShutdown(handler *http.ServeMux) {
httpServer := http.Server{
Addr: fmt.Sprintf(":%s", "3000"),
ReadTimeout: time.Duration(time.Second) * 60,
WriteTimeout: time.Duration(time.Second) * 30,
IdleTimeout: time.Duration(time.Second) * 120,
MaxHeaderBytes: 3145728,
Handler: handler,
}
if err := httpServer.ListenAndServe(); err != nil {
log.Fatalf("Server is not running: %s", err.Error())
os.Exit(0)
}
osSignal := make(chan os.Signal, 1)
signal.Notify(osSignal, os.Interrupt, syscall.SIGTERM)
log.Printf("Signal received: %v", <-osSignal)
if sig := <-osSignal; sig == os.Interrupt || sig == syscall.SIGTERM {
log.Println("Waiting to server shutdown")
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second)*10)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Println("HTTP server shutdown error: %s", err.Error())
}
log.Println("HTTP server shutdown")
}
}