commit
This commit is contained in:
115
internal/database/database.go
Normal file
115
internal/database/database.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
)
|
||||
|
||||
// Service represents a service that interacts with a database.
|
||||
type Service interface {
|
||||
// Health returns a map of health status information.
|
||||
// The keys and values in the map are service-specific.
|
||||
Health() map[string]string
|
||||
|
||||
// Close terminates the database connection.
|
||||
// It returns an error if the connection cannot be closed.
|
||||
Close() error
|
||||
}
|
||||
|
||||
type service struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
var (
|
||||
database = os.Getenv("BLUEPRINT_DB_DATABASE")
|
||||
password = os.Getenv("BLUEPRINT_DB_PASSWORD")
|
||||
username = os.Getenv("BLUEPRINT_DB_USERNAME")
|
||||
port = os.Getenv("BLUEPRINT_DB_PORT")
|
||||
host = os.Getenv("BLUEPRINT_DB_HOST")
|
||||
schema = os.Getenv("BLUEPRINT_DB_SCHEMA")
|
||||
dbInstance *service
|
||||
)
|
||||
|
||||
func New() Service {
|
||||
// Reuse Connection
|
||||
if dbInstance != nil {
|
||||
return dbInstance
|
||||
}
|
||||
connStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable&search_path=%s", username, password, host, port, database, schema)
|
||||
db, err := sql.Open("pgx", connStr)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
dbInstance = &service{
|
||||
db: db,
|
||||
}
|
||||
return dbInstance
|
||||
}
|
||||
|
||||
// Health checks the health of the database connection by pinging the database.
|
||||
// It returns a map with keys indicating various health statistics.
|
||||
func (s *service) Health() map[string]string {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
stats := make(map[string]string)
|
||||
|
||||
// Ping the database
|
||||
err := s.db.PingContext(ctx)
|
||||
if err != nil {
|
||||
stats["status"] = "down"
|
||||
stats["error"] = fmt.Sprintf("db down: %v", err)
|
||||
log.Fatalf("db down: %v", err) // Log the error and terminate the program
|
||||
return stats
|
||||
}
|
||||
|
||||
// Database is up, add more statistics
|
||||
stats["status"] = "up"
|
||||
stats["message"] = "It's healthy"
|
||||
|
||||
// Get database stats (like open connections, in use, idle, etc.)
|
||||
dbStats := s.db.Stats()
|
||||
stats["open_connections"] = strconv.Itoa(dbStats.OpenConnections)
|
||||
stats["in_use"] = strconv.Itoa(dbStats.InUse)
|
||||
stats["idle"] = strconv.Itoa(dbStats.Idle)
|
||||
stats["wait_count"] = strconv.FormatInt(dbStats.WaitCount, 10)
|
||||
stats["wait_duration"] = dbStats.WaitDuration.String()
|
||||
stats["max_idle_closed"] = strconv.FormatInt(dbStats.MaxIdleClosed, 10)
|
||||
stats["max_lifetime_closed"] = strconv.FormatInt(dbStats.MaxLifetimeClosed, 10)
|
||||
|
||||
// Evaluate stats to provide a health message
|
||||
if dbStats.OpenConnections > 40 { // Assuming 50 is the max for this example
|
||||
stats["message"] = "The database is experiencing heavy load."
|
||||
}
|
||||
|
||||
if dbStats.WaitCount > 1000 {
|
||||
stats["message"] = "The database has a high number of wait events, indicating potential bottlenecks."
|
||||
}
|
||||
|
||||
if dbStats.MaxIdleClosed > int64(dbStats.OpenConnections)/2 {
|
||||
stats["message"] = "Many idle connections are being closed, consider revising the connection pool settings."
|
||||
}
|
||||
|
||||
if dbStats.MaxLifetimeClosed > int64(dbStats.OpenConnections)/2 {
|
||||
stats["message"] = "Many connections are being closed due to max lifetime, consider increasing max lifetime or revising the connection usage pattern."
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
// Close closes the database connection.
|
||||
// It logs a message indicating the disconnection from the specific database.
|
||||
// If the connection is successfully closed, it returns nil.
|
||||
// If an error occurs while closing the connection, it returns the error.
|
||||
func (s *service) Close() error {
|
||||
log.Printf("Disconnected from database: %s", database)
|
||||
return s.db.Close()
|
||||
}
|
||||
100
internal/database/database_test.go
Normal file
100
internal/database/database_test.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
)
|
||||
|
||||
func mustStartPostgresContainer() (func(context.Context, ...testcontainers.TerminateOption) error, error) {
|
||||
var (
|
||||
dbName = "database"
|
||||
dbPwd = "password"
|
||||
dbUser = "user"
|
||||
)
|
||||
|
||||
dbContainer, err := postgres.Run(
|
||||
context.Background(),
|
||||
"postgres:latest",
|
||||
postgres.WithDatabase(dbName),
|
||||
postgres.WithUsername(dbUser),
|
||||
postgres.WithPassword(dbPwd),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(5*time.Second)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
database = dbName
|
||||
password = dbPwd
|
||||
username = dbUser
|
||||
|
||||
dbHost, err := dbContainer.Host(context.Background())
|
||||
if err != nil {
|
||||
return dbContainer.Terminate, err
|
||||
}
|
||||
|
||||
dbPort, err := dbContainer.MappedPort(context.Background(), "5432/tcp")
|
||||
if err != nil {
|
||||
return dbContainer.Terminate, err
|
||||
}
|
||||
|
||||
host = dbHost
|
||||
port = dbPort.Port()
|
||||
|
||||
return dbContainer.Terminate, err
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
teardown, err := mustStartPostgresContainer()
|
||||
if err != nil {
|
||||
log.Fatalf("could not start postgres container: %v", err)
|
||||
}
|
||||
|
||||
m.Run()
|
||||
|
||||
if teardown != nil && teardown(context.Background()) != nil {
|
||||
log.Fatalf("could not teardown postgres container: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
srv := New()
|
||||
if srv == nil {
|
||||
t.Fatal("New() returned nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealth(t *testing.T) {
|
||||
srv := New()
|
||||
|
||||
stats := srv.Health()
|
||||
|
||||
if stats["status"] != "up" {
|
||||
t.Fatalf("expected status to be up, got %s", stats["status"])
|
||||
}
|
||||
|
||||
if _, ok := stats["error"]; ok {
|
||||
t.Fatalf("expected error not to be present")
|
||||
}
|
||||
|
||||
if stats["message"] != "It's healthy" {
|
||||
t.Fatalf("expected message to be 'It's healthy', got %s", stats["message"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClose(t *testing.T) {
|
||||
srv := New()
|
||||
|
||||
if srv.Close() != nil {
|
||||
t.Fatalf("expected Close() to return nil")
|
||||
}
|
||||
}
|
||||
71
internal/server/routes.go
Normal file
71
internal/server/routes.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"go-htmx/cmd/web"
|
||||
)
|
||||
|
||||
func (s *Server) RegisterRoutes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Register routes
|
||||
mux.HandleFunc("/", s.HelloWorldHandler)
|
||||
|
||||
mux.HandleFunc("/health", s.healthHandler)
|
||||
|
||||
fileServer := http.FileServer(http.FS(web.Files))
|
||||
mux.Handle("/assets/", fileServer)
|
||||
mux.Handle("/web", templ.Handler(web.HelloForm()))
|
||||
mux.HandleFunc("/hello", web.HelloWebHandler)
|
||||
|
||||
// Wrap the mux with CORS middleware
|
||||
return s.corsMiddleware(mux)
|
||||
}
|
||||
|
||||
func (s *Server) corsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Set CORS headers
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*") // Replace "*" with specific origins if needed
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token")
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "false") // Set to "true" if credentials are required
|
||||
|
||||
// Handle preflight OPTIONS requests
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
// Proceed with the next handler
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
|
||||
resp := map[string]string{"message": "Hello World"}
|
||||
jsonResp, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to marshal response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if _, err := w.Write(jsonResp); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := json.Marshal(s.db.Health())
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to marshal health check response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if _, err := w.Write(resp); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
31
internal/server/routes_test.go
Normal file
31
internal/server/routes_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHandler(t *testing.T) {
|
||||
s := &Server{}
|
||||
server := httptest.NewServer(http.HandlerFunc(s.HelloWorldHandler))
|
||||
defer server.Close()
|
||||
resp, err := http.Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("error making request to server. Err: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Assertions
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("expected status OK; got %v", resp.Status)
|
||||
}
|
||||
expected := "{\"message\":\"Hello World\"}"
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("error reading response body. Err: %v", err)
|
||||
}
|
||||
if expected != string(body) {
|
||||
t.Errorf("expected response body to be %v; got %v", expected, string(body))
|
||||
}
|
||||
}
|
||||
39
internal/server/server.go
Normal file
39
internal/server/server.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
|
||||
"go-htmx/internal/database"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
port int
|
||||
|
||||
db database.Service
|
||||
}
|
||||
|
||||
func NewServer() *http.Server {
|
||||
port, _ := strconv.Atoi(os.Getenv("PORT"))
|
||||
NewServer := &Server{
|
||||
port: port,
|
||||
|
||||
db: database.New(),
|
||||
}
|
||||
|
||||
// Declare Server config
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", NewServer.port),
|
||||
Handler: NewServer.RegisterRoutes(),
|
||||
IdleTimeout: time.Minute,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
return server
|
||||
}
|
||||
Reference in New Issue
Block a user