115 lines
2.6 KiB
Go
115 lines
2.6 KiB
Go
package service
|
|
|
|
import (
|
|
"Portifolio/internal/database"
|
|
"Portifolio/internal/model"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"runtime"
|
|
"time"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
var startTime = time.Now()
|
|
|
|
func New(db *sql.DB) *Service {
|
|
return &Service{db: db}
|
|
}
|
|
|
|
func (s *Service) HealthHandler() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
health := s.CheckHealth()
|
|
|
|
if health["status"] != "ok" {
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
}
|
|
|
|
json.NewEncoder(w).Encode(health)
|
|
}
|
|
}
|
|
|
|
func (s *Service) CheckHealth() map[string]any {
|
|
dbStatus := "ok"
|
|
dbLatency := ""
|
|
t := time.Now()
|
|
if err := s.db.Ping(); err != nil {
|
|
dbStatus = "error: " + err.Error()
|
|
} else {
|
|
dbLatency = time.Since(t).String()
|
|
}
|
|
|
|
stats := s.db.Stats()
|
|
status := "ok"
|
|
if dbStatus != "ok" {
|
|
status = "degraded"
|
|
}
|
|
|
|
var mem runtime.MemStats
|
|
runtime.ReadMemStats(&mem)
|
|
|
|
return map[string]any{
|
|
"status": status,
|
|
"uptime": time.Since(startTime).String(),
|
|
"database": map[string]any{
|
|
"status": dbStatus,
|
|
"latency": dbLatency,
|
|
"open_connections": stats.OpenConnections,
|
|
"in_use": stats.InUse,
|
|
"idle": stats.Idle,
|
|
},
|
|
"memory": map[string]any{
|
|
"alloc_mb": bToMb(mem.Alloc),
|
|
"sys_mb": bToMb(mem.Sys),
|
|
"num_gc": mem.NumGC,
|
|
},
|
|
"go_version": runtime.Version(),
|
|
"goroutines": runtime.NumGoroutine(),
|
|
}
|
|
}
|
|
|
|
func bToMb(b uint64) float64 {
|
|
return float64(b) / 1024 / 1024
|
|
}
|
|
|
|
func (s *Service) AddCompanyHandler() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var input model.CompanyInput
|
|
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
id, err := database.AddCompany(s.db, input)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
json.NewEncoder(w).Encode(map[string]int{"id": id})
|
|
}
|
|
}
|
|
|
|
func (s *Service) GetAllCompanies() ([]model.Company, error) {
|
|
companies, err := database.GetAllCompanies(s.db)
|
|
return companies, err
|
|
}
|
|
|
|
func (s *Service) GetCompaniesHandler() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
companies, err := database.GetAllCompanies(s.db)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(companies)
|
|
}
|
|
}
|