78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package config
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"golang.org/x/exp/rand"
|
|
)
|
|
|
|
func init() {
|
|
rand.Seed(uint64(time.Now().UnixNano()))
|
|
}
|
|
|
|
type Config struct {
|
|
Database string
|
|
Web WebConfig
|
|
OAuth2 OAuth2
|
|
LogLevel string
|
|
}
|
|
|
|
type WebConfig struct {
|
|
Bind string
|
|
SessionKey string
|
|
BaseURL string
|
|
}
|
|
|
|
var C = Config{
|
|
LogLevel: "INFO",
|
|
Web: WebConfig{
|
|
Bind: ":8080",
|
|
},
|
|
}
|
|
|
|
func Load(ctx context.Context) error {
|
|
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
|
|
}
|
|
|
|
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
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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)
|
|
}
|