2024-05-05 22:10:32 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2024-07-25 05:13:23 +00:00
|
|
|
"context"
|
2024-05-05 22:10:32 +00:00
|
|
|
"encoding/json"
|
2024-07-25 05:13:23 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2024-05-05 22:10:32 +00:00
|
|
|
"os"
|
2024-07-25 05:13:23 +00:00
|
|
|
"time"
|
2024-05-05 22:10:32 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2024-07-25 05:13:23 +00:00
|
|
|
"golang.org/x/exp/rand"
|
2024-05-05 22:10:32 +00:00
|
|
|
)
|
|
|
|
|
2024-07-25 05:13:23 +00:00
|
|
|
func init() {
|
|
|
|
rand.Seed(uint64(time.Now().UnixNano()))
|
|
|
|
}
|
|
|
|
|
2024-05-05 22:10:32 +00:00
|
|
|
type Config struct {
|
|
|
|
Database string
|
2024-07-25 05:13:23 +00:00
|
|
|
Web WebConfig
|
|
|
|
OAuth2 OAuth2
|
|
|
|
LogLevel string
|
|
|
|
}
|
|
|
|
|
|
|
|
type WebConfig struct {
|
|
|
|
Bind string
|
|
|
|
SessionKey string
|
|
|
|
BaseURL string
|
2024-05-05 22:10:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var C = Config{
|
2024-07-25 05:13:23 +00:00
|
|
|
LogLevel: "INFO",
|
|
|
|
Web: WebConfig{
|
|
|
|
Bind: ":8080",
|
|
|
|
},
|
2024-05-05 22:10:32 +00:00
|
|
|
}
|
|
|
|
|
2024-07-25 05:13:23 +00:00
|
|
|
func Load(ctx context.Context) error {
|
2024-05-05 22:10:32 +00:00
|
|
|
logrus.Info("loading config file")
|
|
|
|
|
|
|
|
f, err := os.Open("go-project-template.json")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
err = json.NewDecoder(f).Decode(&C)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-07-25 05:13:23 +00:00
|
|
|
level, err := logrus.ParseLevel(C.LogLevel)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error parsing requested log level %s: %v", C.LogLevel, err)
|
|
|
|
}
|
|
|
|
logrus.SetLevel(level)
|
|
|
|
|
|
|
|
if C.Web.SessionKey == "" {
|
|
|
|
logrus.Info("No session key specified. Here's a good one if you need it: ", generateSessionKey())
|
|
|
|
return errors.New("session key may not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := C.OAuth2.Load(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-05-05 22:10:32 +00:00
|
|
|
return nil
|
|
|
|
}
|
2024-07-25 05:13:23 +00:00
|
|
|
|
|
|
|
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
|
|
|
|
|
|
|
|
func generateSessionKey() string {
|
|
|
|
b := make([]rune, 64)
|
|
|
|
for i := range b {
|
|
|
|
b[i] = letterRunes[rand.Intn(len(letterRunes))]
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|