random-api-go/config/config.go
wood chen e70ca4cf52 feat(docker, config, api): update docker-compose for logging, enhance app structure, and add system metrics display
- Updated docker-compose.yml to mount logs directory.
- Changed BASE_URL environment variable to point to the new API endpoint.
- Refactored main.go to implement a structured App type, improving initialization and graceful shutdown.
- Enhanced config management with JSON loading and environment variable support.
- Added monitoring capabilities in api_handler for logging request metrics.
- Introduced new metrics display in index.html with corresponding CSS styles for better visualization.
2024-11-30 23:23:58 +08:00

67 lines
1.1 KiB
Go

package config
import (
"encoding/json"
"math/rand"
"os"
"time"
)
const (
EnvBaseURL = "BASE_URL"
DefaultPort = ":5003"
RequestTimeout = 10 * time.Second
)
type Config struct {
Server struct {
Port string `json:"port"`
ReadTimeout time.Duration `json:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout"`
MaxHeaderBytes int `json:"max_header_bytes"`
} `json:"server"`
Storage struct {
DataDir string `json:"data_dir"`
StatsFile string `json:"stats_file"`
LogFile string `json:"log_file"`
} `json:"storage"`
API struct {
BaseURL string `json:"base_url"`
RequestTimeout time.Duration `json:"request_timeout"`
} `json:"api"`
}
var (
cfg Config
RNG *rand.Rand
)
func Load(configFile string) error {
file, err := os.Open(configFile)
if err != nil {
return err
}
defer file.Close()
decoder := json.NewDecoder(file)
if err := decoder.Decode(&cfg); err != nil {
return err
}
if envBaseURL := os.Getenv(EnvBaseURL); envBaseURL != "" {
cfg.API.BaseURL = envBaseURL
}
return nil
}
func Get() *Config {
return &cfg
}
func InitRNG(r *rand.Rand) {
RNG = r
}