added config via viper
This commit is contained in:
parent
532d77a02d
commit
ec4e870bdf
4 changed files with 99 additions and 13 deletions
36
main.go
36
main.go
|
|
@ -9,6 +9,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/mmcdole/gofeed"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Update struct {
|
||||
|
|
@ -21,7 +22,7 @@ var (
|
|||
cacheMu sync.Mutex
|
||||
cachedUpdates []Update
|
||||
cacheExpiry time.Time
|
||||
cacheDuration = 5 * time.Minute // adjust as needed
|
||||
cacheDuration time.Duration
|
||||
)
|
||||
|
||||
func fetchUpdates(feedURL string) ([]Update, error) {
|
||||
|
|
@ -86,7 +87,7 @@ func invalidateCache(w http.ResponseWriter, r *http.Request) {
|
|||
defer cacheMu.Unlock()
|
||||
|
||||
cachedUpdates = nil
|
||||
cacheExpiry = time.Time{} // zero time to force refresh on next request
|
||||
cacheExpiry = time.Time{}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("Cache invalidated\n"))
|
||||
|
|
@ -108,10 +109,37 @@ func updatesHandler(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
func main() {
|
||||
// Setup Viper
|
||||
viper.SetDefault("port", "8080")
|
||||
viper.SetDefault("cache_duration", "5m") // 5 minutes
|
||||
|
||||
viper.SetConfigName("config") // config file name (without extension)
|
||||
viper.SetConfigType("yaml") // or json, toml, etc.
|
||||
viper.AddConfigPath(".") // look for config in working directory
|
||||
|
||||
// Read config file (if exists)
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
log.Println("No config file found or error reading config, continuing with defaults/env")
|
||||
}
|
||||
|
||||
// Allow environment variables to override config
|
||||
viper.AutomaticEnv() // read env variables matching keys (e.g., PORT, CACHE_DURATION)
|
||||
|
||||
// Parse cache duration
|
||||
cacheDurationStr := viper.GetString("cache_duration")
|
||||
dur, err := time.ParseDuration(cacheDurationStr)
|
||||
if err != nil {
|
||||
log.Fatalf("Invalid cache_duration: %v", err)
|
||||
}
|
||||
cacheDuration = dur
|
||||
|
||||
port := viper.GetString("port")
|
||||
|
||||
http.HandleFunc("/updates", updatesHandler)
|
||||
http.HandleFunc("/invalidate-cache", invalidateCache)
|
||||
|
||||
log.Println("Listening on http://localhost:8080/")
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
log.Printf("Listening on http://localhost:%s/", port)
|
||||
log.Fatal(http.ListenAndServe(":"+port, nil))
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue