init socle
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
parent
4ba5c58a37
commit
599479d746
12 changed files with 400 additions and 0 deletions
24
internal/config/config.go
Normal file
24
internal/config/config.go
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package config
|
||||
|
||||
import "os"
|
||||
|
||||
type Config struct {
|
||||
DatabaseURL string
|
||||
Port string
|
||||
Env string
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
DatabaseURL: getenv("DATABASE_URL", "postgres://account:account@localhost:5432/account?sslmode=disable"),
|
||||
Port: getenv("PORT", "8080"),
|
||||
Env: getenv("ENV", "development"),
|
||||
}
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
46
internal/server/server.go
Normal file
46
internal/server/server.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.g3e.fr/H6N/account/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
mux *http.ServeMux
|
||||
pool *pgxpool.Pool
|
||||
logger *slog.Logger
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, pool *pgxpool.Pool, logger *slog.Logger) *Server {
|
||||
s := &Server{
|
||||
mux: http.NewServeMux(),
|
||||
pool: pool,
|
||||
logger: logger,
|
||||
cfg: cfg,
|
||||
}
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.mux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.mux.HandleFunc("GET /health", s.handleHealth)
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.pool.Ping(r.Context()); err != nil {
|
||||
s.logger.Error("health check failed", "error", err)
|
||||
http.Error(w, "database unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue