Repository: nuveo/prest
Pull request #148 (2017-05-22 15:18:16)

introduce debug mode
related issue #147 and #138 

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

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

```diff
@@            Coverage Diff             @@
##           master     #148      +/-   ##
==========================================
- Coverage   86.41%   86.14%   -0.28%     
==========================================
  Files          10       10              
  Lines         854      859       +5     
==========================================
+ Hits          738      740       +2     
- Misses         75       77       +2     
- Partials       41       42       +1
```


| [Impacted Files](https://codecov.io/gh/nuveo/prest/pull/148?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [config/middlewares/middlewares.go](https://codecov.io/gh/nuveo/prest/pull/148?src=pr&el=tree#diff-Y29uZmlnL21pZGRsZXdhcmVzL21pZGRsZXdhcmVzLmdv) | `80% <0%> (ø)` | :arrow_up: |
| [config/config.go](https://codecov.io/gh/nuveo/prest/pull/148?src=pr&el=tree#diff-Y29uZmlnL2NvbmZpZy5nbw==) | `77.58% <37.5%> (-3.55%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/nuveo/prest/pull/148?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/148?src=pr&el=footer). Last update [d4ba63e...fc8ebad](https://codecov.io/gh/nuveo/prest/pull/148?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

avelino: @felipeweb tem teste quebrando https://travis-ci.org/nuveo/prest/jobs/234889024#L439
felipeweb: to arrumandando

Patch:
diff --git a/README.md b/README.md
index f69ca85..b5d6332 100644
--- a/README.md
+++ b/README.md
@@ -115,12 +115,20 @@ database = "prest"
 ## API's
 HEADER:
 
-- To start JWT middleware the `PREST_JWT_KEY` environment variable must be set
+- JWT middleware is enable by default. To disable JWT need to run pREST in debug mode
 
 ```
 Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
 ```
 
+## Debug Mode
+
+- Set environment variable `PREST_DEBUG`
+
+```
+PREST_DEBUG=true
+```
+
 ### Filter (WHERE)
 
 ```
diff --git a/config/config.go b/config/config.go
index 8e100cf..f7df0f7 100644
--- a/config/config.go
+++ b/config/config.go
@@ -42,6 +42,7 @@ type Prest struct {
 	QueriesPath     string
 	AccessConf      AccessConf
 	CORSAllowOrigin []string
+	Debug           bool
 }
 
 // PrestConf config variable
@@ -64,6 +65,7 @@ func viperCfg() {
 	viper.SetDefault("pg.maxidleconn", 10)
 	viper.SetDefault("pg.maxopenconn", 10)
 	viper.SetDefault("pg.conntimeout", 10)
+	viper.SetDefault("debug", false)
 
 	user, err := user.Current()
 	if err != nil {
@@ -77,7 +79,12 @@ func viperCfg() {
 func Parse(cfg *Prest) (err error) {
 	err = viper.ReadInConfig()
 	if err != nil {
-		return
+		switch err.(type) {
+		case viper.ConfigFileNotFoundError:
+			fmt.Println("Running without config file")
+		default:
+			return
+		}
 	}
 	cfg.HTTPPort = viper.GetInt("http.port")
 	cfg.PGHost = viper.GetString("pg.host")
@@ -93,6 +100,7 @@ func Parse(cfg *Prest) (err error) {
 	cfg.AccessConf.Restrict = viper.GetBool("access.restrict")
 	cfg.QueriesPath = viper.GetString("queries.location")
 	cfg.CORSAllowOrigin = viper.GetStringSlice("cors.alloworigin")
+	cfg.Debug = viper.GetBool("debug")
 
 	var t []TablesConf
 	err = viper.UnmarshalKey("access.tables", &t)
@@ -109,13 +117,22 @@ func Parse(cfg *Prest) (err error) {
 func Load() {
 	viperCfg()
 	PrestConf = &Prest{}
-	Parse(PrestConf)
+	err := Parse(PrestConf)
+	if err != nil {
+		panic(err)
+	}
 
 	if !PrestConf.AccessConf.Restrict {
 		fmt.Println("You are running pREST in public mode.")
 	}
 
-	if _, err := os.Stat(PrestConf.QueriesPath); os.IsNotExist(err) {
-		os.MkdirAll(PrestConf.QueriesPath, 0777)
+	if PrestConf.Debug {
+		fmt.Println("You are running pREST in debug mode.")
+	}
+
+	if _, err = os.Stat(PrestConf.QueriesPath); os.IsNotExist(err) {
+		if err = os.MkdirAll(PrestConf.QueriesPath, 0700); os.IsNotExist(err) {
+			fmt.Printf("Queries directory %s is not created", PrestConf.QueriesPath)
+		}
 	}
 }
diff --git a/config/middlewares/middlewares.go b/config/middlewares/middlewares.go
index 03e00bc..2238dcd 100644
--- a/config/middlewares/middlewares.go
+++ b/config/middlewares/middlewares.go
@@ -24,7 +24,7 @@ func initApp() {
 	if len(MiddlewareStack) == 0 {
 		MiddlewareStack = append(MiddlewareStack, BaseStack...)
 	}
-	if config.PrestConf.JWTKey != "" {
+	if !config.PrestConf.Debug {
 		MiddlewareStack = append(MiddlewareStack, negroni.Handler(middlewares.JwtMiddleware(config.PrestConf.JWTKey)))
 	}
 	app = negroni.New(MiddlewareStack...)
@@ -32,8 +32,7 @@ func initApp() {
 
 // GetApp get negroni
 func GetApp() *negroni.Negroni {
-	if app == nil {
-		initApp()
-	}
+	// init application every time
+	initApp()
 	return app
 }


Test patch:
diff --git a/config/middlewares/middlewares_test.go b/config/middlewares/middlewares_test.go
index 836badc..10600a3 100644
--- a/config/middlewares/middlewares_test.go
+++ b/config/middlewares/middlewares_test.go
@@ -88,6 +88,8 @@ func TestGetAppWithoutReorderedMiddleware(t *testing.T) {
 }
 
 func TestMiddlewareAccessNoblockingCustomRoutes(t *testing.T) {
+	os.Setenv("PREST_DEBUG", "true")
+	config.Load()
 	app = nil
 	r := router.Get()
 	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("custom route")) })
@@ -152,3 +154,30 @@ func customMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerF
 
 	next(w, r)
 }
+
+func TestDebug(t *testing.T) {
+	os.Setenv("PREST_DEBUG", "true")
+	config.Load()
+	nd := appTest()
+	serverd := httptest.NewServer(nd)
+	defer serverd.Close()
+	respd, err := http.Get(serverd.URL)
+	if err != nil {
+		t.Errorf("expected no errors, but got %v", err)
+	}
+	if respd.StatusCode != http.StatusOK {
+		t.Errorf("expected status code 200, but got %d", respd.StatusCode)
+	}
+}
+
+func appTest() *negroni.Negroni {
+	n := GetApp()
+	r := router.Get()
+
+	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+		w.Write([]byte("test app"))
+	}).Methods("GET")
+
+	n.UseHandler(r)
+	return n
+}
diff --git a/controllers/sql_test.go b/controllers/sql_test.go
index d178749..2e38699 100644
--- a/controllers/sql_test.go
+++ b/controllers/sql_test.go
@@ -109,7 +109,8 @@ func TestRenderWithXML(t *testing.T) {
 	}{
 		{"Get schemas with COUNT clause with XML Render", "/schemas?_count=*&_renderer=xml", "GET", 200, "<objects><object><count>6</count></object></objects>"},
 	}
-
+	os.Setenv("PREST_DEBUG", "true")
+	config.Load()
 	n := middlewares.GetApp()
 	r := router.Get()