Repository: nuveo/prest
Pull request #131 (2017-04-07 16:03:17)

Refactoring to prevent multiple configuration loads
Prevent multiple configuration loads
Remove unnecessary code
Remove redundant variables

codecov[bot]: # [Codecov](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=h1) Report
> Merging [#131](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=desc) into [master](https://codecov.io/gh/nuveo/prest/commit/d062e8276b8302c70d6091d37da4856b2a0e1717?src=pr&el=desc) will **decrease** coverage by `0.22%`.
> The diff coverage is `80%`.

[![Impacted file tree graph](https://codecov.io/gh/nuveo/prest/pull/131/graphs/tree.svg?height=150&width=650&token=eVD9urwIEv&src=pr)](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #131      +/-   ##
==========================================
- Coverage    89.6%   89.37%   -0.23%     
==========================================
  Files          10       10              
  Lines         827      828       +1     
==========================================
- Hits          741      740       -1     
- Misses         55       56       +1     
- Partials       31       32       +1
```


| [Impacted Files](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [config/middlewares/middlewares.go](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=tree#diff-Y29uZmlnL21pZGRsZXdhcmVzL21pZGRsZXdhcmVzLmdv) | `80% <ø> (-1.82%)` | :arrow_down: |
| [adapters/postgres/connection/conn.go](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=tree#diff-YWRhcHRlcnMvcG9zdGdyZXMvY29ubmVjdGlvbi9jb25uLmdv) | `77.77% <80%> (+4.44%)` | :arrow_up: |
| [config/config.go](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=tree#diff-Y29uZmlnL2NvbmZpZy5nbw==) | `77.77% <80%> (-4.05%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=footer). Last update [d062e82...50dcae9](https://codecov.io/gh/nuveo/prest/pull/131?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

Patch:
diff --git a/adapters/postgres/connection/conn.go b/adapters/postgres/connection/conn.go
index 7d0f3a0..4b7d4bf 100644
--- a/adapters/postgres/connection/conn.go
+++ b/adapters/postgres/connection/conn.go
@@ -13,25 +13,27 @@ import (
 
 var (
 	db  *sqlx.DB
-	cfg config.Prest
 	err error
 )
 
 // MustGet get postgres connection
 func MustGet() *sqlx.DB {
 	if db == nil {
-		cfg = config.Prest{}
-		config.Parse(&cfg)
-		dbURI := fmt.Sprintf("user=%s dbname=%s host=%s port=%v sslmode=disable connect_timeout=%d", cfg.PGUser, cfg.PGDatabase, cfg.PGHost, cfg.PGPort, cfg.PGConnTimeout)
-		if cfg.PGPass != "" {
-			dbURI += " password=" + cfg.PGPass
+		dbURI := fmt.Sprintf("user=%s dbname=%s host=%s port=%v sslmode=disable connect_timeout=%d",
+			config.PrestConf.PGUser,
+			config.PrestConf.PGDatabase,
+			config.PrestConf.PGHost,
+			config.PrestConf.PGPort,
+			config.PrestConf.PGConnTimeout)
+		if config.PrestConf.PGPass != "" {
+			dbURI += " password=" + config.PrestConf.PGPass
 		}
 		db, err = sqlx.Connect("postgres", dbURI)
 		if err != nil {
 			panic(fmt.Sprintf("Unable to connection to database: %v\n", err))
 		}
-		db.SetMaxIdleConns(cfg.PGMaxIdleConn)
-		db.SetMaxOpenConns(cfg.PGMAxOpenConn)
+		db.SetMaxIdleConns(config.PrestConf.PGMaxIdleConn)
+		db.SetMaxOpenConns(config.PrestConf.PGMAxOpenConn)
 	}
 	return db
 }
diff --git a/cmd/root.go b/cmd/root.go
index 9d0e6d1..afb154e 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -2,7 +2,6 @@ package cmd
 
 import (
 	"fmt"
-	"log"
 	"os"
 
 	"github.com/gorilla/mux"
@@ -40,20 +39,8 @@ func Execute() {
 	}
 }
 
-func init() {
-	config.InitConf()
-}
-
 func app() {
-	cfg := config.Prest{}
-
-	err := config.Parse(&cfg)
-	if err != nil {
-		log.Fatalf("Error parsing conf: %s", err)
-	}
-
 	n := cfgMiddleware.GetApp()
-
 	r := router.Get()
 
 	r.HandleFunc("/databases", controllers.GetDatabases).Methods("GET")
@@ -74,13 +61,13 @@ func app() {
 		negroni.Wrap(crudRoutes),
 	))
 
-	if cfg.CORSAllowOrigin != nil {
+	if config.PrestConf.CORSAllowOrigin != nil {
 		c := cors.New(cors.Options{
-			AllowedOrigins: cfg.CORSAllowOrigin,
+			AllowedOrigins: config.PrestConf.CORSAllowOrigin,
 		})
 		n.Use(c)
 	}
 
 	n.UseHandler(r)
-	n.Run(fmt.Sprintf(":%v", cfg.HTTPPort))
+	n.Run(fmt.Sprintf(":%v", config.PrestConf.HTTPPort))
 }
diff --git a/config/config.go b/config/config.go
index 0628ace..2c0ecc7 100644
--- a/config/config.go
+++ b/config/config.go
@@ -48,7 +48,7 @@ type Prest struct {
 var PrestConf *Prest
 
 func init() {
-	viperCfg()
+	load()
 }
 
 func viperCfg() {
@@ -109,14 +109,13 @@ func Parse(cfg *Prest) (err error) {
 	return
 }
 
-// InitConf initialize config
-func InitConf() {
+// load configuration
+func load() {
 	viperCfg()
-	prestConfig := Prest{}
-	Parse(&prestConfig)
-	PrestConf = &prestConfig
+	PrestConf = &Prest{}
+	Parse(PrestConf)
 
-	if !prestConfig.AccessConf.Restrict {
+	if !PrestConf.AccessConf.Restrict {
 		fmt.Println("You are running pREST in public mode.")
 	}
 
diff --git a/config/middlewares/middlewares.go b/config/middlewares/middlewares.go
index bc5bb1f..03e00bc 100644
--- a/config/middlewares/middlewares.go
+++ b/config/middlewares/middlewares.go
@@ -21,7 +21,6 @@ var (
 )
 
 func initApp() {
-	config.InitConf()
 	if len(MiddlewareStack) == 0 {
 		MiddlewareStack = append(MiddlewareStack, BaseStack...)
 	}


Test patch:
diff --git a/adapters/postgres/queries_test.go b/adapters/postgres/queries_test.go
index 9716c87..23b4191 100644
--- a/adapters/postgres/queries_test.go
+++ b/adapters/postgres/queries_test.go
@@ -12,7 +12,6 @@ import (
 )
 
 func TestMain(m *testing.M) {
-	config.InitConf()
 	createMockScripts(config.PrestConf.QueriesPath)
 	writeMockScripts(config.PrestConf.QueriesPath)
 
diff --git a/config/config_test.go b/config/config_test.go
index 3e0f023..e40696e 100644
--- a/config/config_test.go
+++ b/config/config_test.go
@@ -6,15 +6,15 @@ import (
 	"os"
 )
 
-func TestInitConf(t *testing.T) {
+func TestLoad(t *testing.T) {
 	os.Setenv("PREST_CONF", "../testdata/prest.toml")
 
-	InitConf()
+	load()
 	if len(PrestConf.AccessConf.Tables) < 2 {
 		t.Errorf("expected > 2, got: %d", len(PrestConf.AccessConf.Tables))
 	}
 
-	InitConf()
+	load()
 	if !PrestConf.AccessConf.Restrict {
 		t.Error("expected true, but got false")
 	}
diff --git a/controllers/sql_test.go b/controllers/sql_test.go
index 9c36ebb..b4c4f77 100644
--- a/controllers/sql_test.go
+++ b/controllers/sql_test.go
@@ -14,7 +14,6 @@ import (
 )
 
 func TestMain(m *testing.M) {
-	config.InitConf()
 	createMockScripts(config.PrestConf.QueriesPath)
 	writeMockScripts(config.PrestConf.QueriesPath)
 
@@ -111,8 +110,6 @@ func TestRenderWithXML(t *testing.T) {
 	n := middlewares.GetApp()
 	r := router.Get()
 
-	config.InitConf()
-
 	r.HandleFunc("/schemas", GetSchemas).Methods("GET")
 	n.UseHandler(r)
 	server := httptest.NewServer(n)
diff --git a/controllers/tables_test.go b/controllers/tables_test.go
index ebb4bb4..ee32997 100644
--- a/controllers/tables_test.go
+++ b/controllers/tables_test.go
@@ -6,7 +6,6 @@ import (
 
 	"github.com/gorilla/mux"
 	"github.com/nuveo/prest/api"
-	"github.com/nuveo/prest/config"
 )
 
 func TestGetTables(t *testing.T) {
@@ -155,7 +154,6 @@ func TestInsertInTables(t *testing.T) {
 }
 
 func TestDeleteFromTable(t *testing.T) {
-	config.InitConf()
 	router := mux.NewRouter()
 	router.HandleFunc("/{database}/{schema}/{table}", DeleteFromTable).Methods("DELETE")
 	server := httptest.NewServer(router)
@@ -182,7 +180,6 @@ func TestDeleteFromTable(t *testing.T) {
 }
 
 func TestUpdateFromTable(t *testing.T) {
-	config.InitConf()
 	router := mux.NewRouter()
 	router.HandleFunc("/{database}/{schema}/{table}", UpdateTable).Methods("PUT", "PATCH")
 	server := httptest.NewServer(router)