backend update

This commit is contained in:
rl544
2026-09-15 00:11:57 +09:00
parent 574783ab15
commit 4a5a0be6c9
5 changed files with 47 additions and 7 deletions
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
{
"port": "8080",
"db_url": "postgres://monitor:monitorpassword@localhost:5432/vdimonitor?sslmode=disable"
}
+2
View File
@@ -0,0 +1,2 @@
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
+40 -7
View File
@@ -6,10 +6,41 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"strings"
_ "github.com/lib/pq" _ "github.com/lib/pq"
) )
type Config struct {
Port string `json:"port"`
DBUrl string `json:"db_url"`
}
func loadConfig() Config {
cfg := Config{
Port: "8080",
DBUrl: "postgres://monitor:monitorpassword@localhost:5432/vdimonitor?sslmode=disable",
}
file, err := os.Open("config.json")
if err == nil {
defer file.Close()
decoder := json.NewDecoder(file)
if err := decoder.Decode(&cfg); err != nil {
log.Printf("Warning: Failed to parse config.json: %v", err)
}
}
if envPort := os.Getenv("PORT"); envPort != "" {
cfg.Port = envPort
}
if envDB := os.Getenv("DB_URL"); envDB != "" {
cfg.DBUrl = envDB
}
return cfg
}
type MetricPayload struct { type MetricPayload struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
TotalCpuPercent float64 `json:"total_cpu_percent"` TotalCpuPercent float64 `json:"total_cpu_percent"`
@@ -25,13 +56,10 @@ type MetricPayload struct {
var db *sql.DB var db *sql.DB
func main() { func main() {
dbUrl := os.Getenv("DB_URL") cfg := loadConfig()
if dbUrl == "" {
dbUrl = "postgres://monitor:monitorpassword@localhost:5432/vdimonitor?sslmode=disable"
}
var err error var err error
db, err = sql.Open("postgres", dbUrl) db, err = sql.Open("postgres", cfg.DBUrl)
if err != nil { if err != nil {
log.Fatalf("Failed to connect to db: %v", err) log.Fatalf("Failed to connect to db: %v", err)
} }
@@ -39,8 +67,13 @@ func main() {
http.HandleFunc("/api/metrics", handleMetrics) http.HandleFunc("/api/metrics", handleMetrics)
log.Println("Server starting on :8080") port := cfg.Port
log.Fatal(http.ListenAndServe(":8080", nil)) if !strings.HasPrefix(port, ":") {
port = ":" + port
}
log.Printf("Server starting on %s\n", port)
log.Fatal(http.ListenAndServe(port, nil))
} }
func handleMetrics(w http.ResponseWriter, r *http.Request) { func handleMetrics(w http.ResponseWriter, r *http.Request) {
+1
View File
@@ -16,6 +16,7 @@ services:
ports: ports:
- "8081:8080" - "8081:8080"
environment: environment:
PORT: "8080"
DB_URL: postgres://monitor:monitorpassword@db:5432/vdimonitor?sslmode=disable DB_URL: postgres://monitor:monitorpassword@db:5432/vdimonitor?sslmode=disable
depends_on: depends_on:
- db - db