forked from nihonium/nyanimedb
feat: config initialization routines
This commit is contained in:
parent
21e19fbc36
commit
a5605262b3
7 changed files with 264 additions and 0 deletions
78
modules/server/main.go
Normal file
78
modules/server/main.go
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"reflect"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var AppConfig Config
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
AppConfig.Mode = "env"
|
||||
} else {
|
||||
AppConfig.Mode = "argv"
|
||||
}
|
||||
|
||||
err := InitConfig()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to init config: %v\n", err)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
r.LoadHTMLGlob("templates/*")
|
||||
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "index.html", gin.H{
|
||||
"title": "Welcome Page",
|
||||
"message": "Hello, Gin with HTML templates!",
|
||||
})
|
||||
})
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
|
||||
func InitConfig() error {
|
||||
if AppConfig.Mode == "argv" {
|
||||
content, err := os.ReadFile(os.Args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
toml.Unmarshal(content, &AppConfig)
|
||||
|
||||
fmt.Printf("%+v\n", AppConfig)
|
||||
|
||||
return nil
|
||||
} else if AppConfig.Mode == "env" {
|
||||
f := reflect.ValueOf(AppConfig)
|
||||
|
||||
for i := 0; i < f.NumField(); i++ {
|
||||
field := f.Type().Field(i)
|
||||
tag := field.Tag
|
||||
env_var := tag.Get("env")
|
||||
fmt.Printf("Field: %v.\nEnvironment variable: %v.\n", field.Name, env_var)
|
||||
if env_var != "" {
|
||||
env_value, exists := os.LookupEnv(env_var)
|
||||
if !exists {
|
||||
return fmt.Errorf("there is no env variable %s", env_var)
|
||||
}
|
||||
err := setField(&AppConfig, field.Name, env_value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set config field %s: %v", field.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("incorrect config mode")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue