Browse Source

- Added optional config file: fix #40

- Fixed go vet tests
- renamed config keys: fix #39
dependabot/npm_and_yarn/web/prismjs-1.21.0
Max Schmitt 8 years ago
parent
commit
3a7dde4223
  1. 1
      .gitignore
  2. 13
      build/config.yaml
  3. 2
      handlers/auth.go
  4. 4
      handlers/auth_test.go
  5. 4
      handlers/handlers.go
  6. 2
      handlers/public.go
  7. 7
      handlers/test.yaml
  8. 2
      main.go
  9. 2
      store/store.go
  10. 4
      store/store_test.go
  11. 2
      store/util.go
  12. 22
      util/config.go
  13. 2
      util/private.go

1
.gitignore

@ -12,6 +12,7 @@
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/ .glide/
debug
/config.* /config.*
/handlers/static.go /handlers/static.go

13
build/config.yaml

@ -1,11 +1,8 @@
http: listen_addr: ':8080' # Consists of 'IP:Port', e.g. ':8080' listens on any IP and on Port 8080
ListenAddr: ':8080' # Consists of 'IP:Port', e.g. ':8080' listens on any IP and on Port 8080 base_url: 'http://localhost:3000' # Origin URL, required for the authentication via OAuth
BaseURL: 'http://localhost:3000' # Origin URL, required for the authentication via OAuth data_dir: ./data # Contains: the database and the private key
General: enable_debug_mode: true # Activates more detailed logging
DataDir: ./data # Contains: the database and the private key shorted_id_length: 4 # Length of the random generated ID which is used for new shortened URLs
EnableDebugMode: true # Activates more detailed logging
ShortedIDLength: 4 # Length of the random generated ID which is used for new shortened URLs
oAuth:
Google: Google:
ClientID: replace me # ClientID which you get from console.cloud.google.com ClientID: replace me # ClientID which you get from console.cloud.google.com
ClientSecret: replace me # ClientSecret which get from console.cloud.google.com ClientSecret: replace me # ClientSecret which get from console.cloud.google.com

2
handlers/auth.go

@ -17,7 +17,7 @@ import (
func (h *Handler) initOAuth() { func (h *Handler) initOAuth() {
h.engine.Use(sessions.Sessions("backend", sessions.NewCookieStore(util.GetPrivateKey()))) h.engine.Use(sessions.Sessions("backend", sessions.NewCookieStore(util.GetPrivateKey())))
auth.WithAdapterWrapper(auth.NewGoogleAdapter(viper.GetString("oAuth.Google.ClientID"), viper.GetString("oAuth.Google.ClientSecret"), viper.GetString("http.BaseURL")), h.engine.Group("/api/v1/auth/google")) auth.WithAdapterWrapper(auth.NewGoogleAdapter(viper.GetString("Google.ClientID"), viper.GetString("Google.ClientSecret"), viper.GetString("base_url")), h.engine.Group("/api/v1/auth/google"))
h.engine.POST("/api/v1/check", h.handleGoogleCheck) h.engine.POST("/api/v1/check", h.handleGoogleCheck)
} }

4
handlers/auth_test.go

@ -27,9 +27,9 @@ var (
ExpiresAt: time.Now().Add(time.Hour * 24 * 365).Unix(), ExpiresAt: time.Now().Add(time.Hour * 24 * 365).Unix(),
}, },
"google", "google",
"sub sub sub", "id",
"name", "name",
"url", "picture",
} }
tokenString string tokenString string
) )

4
handlers/handlers.go

@ -29,7 +29,7 @@ var DoNotPrivateKeyChecking = false
// New initializes the http handlers // New initializes the http handlers
func New(store store.Store) (*Handler, error) { func New(store store.Store) (*Handler, error) {
if !viper.GetBool("General.EnableDebugMode") { if !viper.GetBool("enable_debug_mode") {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
} }
h := &Handler{ h := &Handler{
@ -77,7 +77,7 @@ func (h *Handler) setHandlers() error {
// Listen starts the http server // Listen starts the http server
func (h *Handler) Listen() error { func (h *Handler) Listen() error {
return h.engine.Run(viper.GetString("http.ListenAddr")) return h.engine.Run(viper.GetString("listen_addr"))
} }
// CloseStore stops the http server and the closes the db gracefully // CloseStore stops the http server and the closes the db gracefully

2
handlers/public.go

@ -55,7 +55,7 @@ func (h *Handler) handleAccess(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return return
} }
if h.store.IncreaseVisitCounter(id); err != nil { if err := h.store.IncreaseVisitCounter(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }

7
handlers/test.yaml

@ -1,4 +1,3 @@
General: data_dir: ../data
DataDir: ../data enable_debug_mode: true
EnableDebugMode: true shorted_id_length: 4
ShortedIDLength: 4

2
main.go

@ -34,7 +34,7 @@ func initShortener() (func(), error) {
if err := util.ReadInConfig(); err != nil { if err := util.ReadInConfig(); err != nil {
return nil, errors.Wrap(err, "could not reload config file") return nil, errors.Wrap(err, "could not reload config file")
} }
if viper.GetBool("General.EnableDebugMode") { if viper.GetBool("enable_debug_mode") {
logrus.SetLevel(logrus.DebugLevel) logrus.SetLevel(logrus.DebugLevel)
} }
store, err := store.New() store, err := store.New()

2
store/store.go

@ -64,7 +64,7 @@ func New() (*Store, error) {
} }
return &Store{ return &Store{
db: db, db: db,
idLength: viper.GetInt("General.ShortedIDLength"), idLength: viper.GetInt("shorted_id_length"),
bucketName: bucketName, bucketName: bucketName,
}, nil }, nil
} }

4
store/store_test.go

@ -12,8 +12,8 @@ const (
) )
func TestGenerateRandomString(t *testing.T) { func TestGenerateRandomString(t *testing.T) {
viper.SetDefault("General.DataDir", "data") viper.SetDefault("data_dir", "data")
viper.SetDefault("General.ShortedIDLength", 4) viper.SetDefault("shorted_id_length", 4)
tt := []struct { tt := []struct {
name string name string
length int length int

2
store/util.go

@ -45,7 +45,7 @@ func (s *Store) createEntry(entry Entry, entryID string) (string, error) {
// generateRandomString generates a random string with an predefined length // generateRandomString generates a random string with an predefined length
func generateRandomString(length int) (string, error) { func generateRandomString(length int) (string, error) {
var result string var result string
for len(result) < int(length) { for len(result) < length {
num, err := rand.Int(rand.Reader, big.NewInt(int64(127))) num, err := rand.Int(rand.Reader, big.NewInt(int64(127)))
if err != nil { if err != nil {
return "", err return "", err

22
util/config.go

@ -5,6 +5,8 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/sirupsen/logrus"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -26,20 +28,24 @@ func ReadInConfig() error {
} }
viper.AddConfigPath(".") viper.AddConfigPath(".")
setConfigDefaults() setConfigDefaults()
if err := viper.ReadInConfig(); err != nil { switch err := viper.ReadInConfig(); err.(type) {
return errors.Wrap(err, "could not reload config file") case viper.ConfigFileNotFoundError:
logrus.Info("No configuration file found, using defaults and environment overrides.")
break
default:
return errors.Wrap(err, "could not read config file")
} }
return checkForDatadir() return checkForDatadir()
} }
// setConfigDefaults sets the default values for the configuration // setConfigDefaults sets the default values for the configuration
func setConfigDefaults() { func setConfigDefaults() {
viper.SetDefault("http.ListenAddr", ":8080") viper.SetDefault("listen_addr", ":8080")
viper.SetDefault("http.BaseURL", "http://localhost:3000") viper.SetDefault("base_url", "http://localhost:3000")
viper.SetDefault("General.DataDir", "data") viper.SetDefault("data_dir", "data")
viper.SetDefault("General.EnableDebugMode", true) viper.SetDefault("enable_debug_mode", true)
viper.SetDefault("General.ShortedIDLength", 4) viper.SetDefault("shorted_id_length", 4)
} }
// GetDataDir returns the absolute path of the data directory // GetDataDir returns the absolute path of the data directory
@ -50,7 +56,7 @@ func GetDataDir() string {
// checkForDatadir checks for the data dir and creates it if it not exists // checkForDatadir checks for the data dir and creates it if it not exists
func checkForDatadir() error { func checkForDatadir() error {
var err error var err error
dataDirPath, err = filepath.Abs(viper.GetString("General.DataDir")) dataDirPath, err = filepath.Abs(viper.GetString("data_dir"))
if err != nil { if err != nil {
return errors.Wrap(err, "could not get relative data dir path") return errors.Wrap(err, "could not get relative data dir path")
} }

2
util/private.go

@ -19,7 +19,7 @@ func CheckForPrivateKey() error {
privateKey = privateDatContent privateKey = privateDatContent
} else if os.IsNotExist(err) { } else if os.IsNotExist(err) {
randomGeneratedKey := make([]byte, 256) randomGeneratedKey := make([]byte, 256)
if _, err := rand.Read(randomGeneratedKey); err != nil { if _, err = rand.Read(randomGeneratedKey); err != nil {
return errors.Wrap(err, "could not read random bytes") return errors.Wrap(err, "could not read random bytes")
} }
if err = ioutil.WriteFile(privateDatPath, randomGeneratedKey, 0644); err != nil { if err = ioutil.WriteFile(privateDatPath, randomGeneratedKey, 0644); err != nil {

Loading…
Cancel
Save