Open platform to collect and prioritize feedback
tooling: add golangci-lint and fix all server side linter errors (#794)
Guilherme Oenning7964b3178020
diff --git a/.github/workflows/fider.yml b/.github/workflows/fider.ymlindex 1399da4d5..70abb2864 100644--- a/.github/workflows/fider.yml+++ b/.github/workflows/fider.yml@@ -13,7 +13,7 @@ jobs:name: test-uiruns-on: ubuntu-latestcontainer:- image: getfider/githubci:0.0.1+ image: getfider/githubci:0.0.2steps:- name: checkout code@@ -26,7 +26,7 @@ jobs:name: test-serverruns-on: ubuntu-latestcontainer:- image: getfider/githubci:0.0.1+ image: getfider/githubci:0.0.2services:minio:@@ -62,7 +62,7 @@ jobs:runs-on: ubuntu-latestneeds: [test-server, test-ui]container:- image: getfider/githubci:0.0.1+ image: getfider/githubci:0.0.2steps:- name: checkout codediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 98d59f3a9..7796112eb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -25,6 +25,7 @@ If you know these technologies or would like to learn them, lucky you! This is t| cosmtrek/air | https://github.com/cosmtrek/air | Live reload for Go apps. When you change the code, it automatically recompiles the application || joho/godotenv | https://github.com/joho/godotenv | To load environment variables from a `.env` so that you don't have to change your machine environment variables | #### 2. Setup your Go environemnt:| magefile/mage | https://github.com/magefile/mage | A cross-platform Make alternative |+| golangci-lint | https://github.com/golangci/golangci-lint | A linter for Go apps |#### 2. To setup your development workspace:diff --git a/app/actions/settings.go b/app/actions/settings.goindex 40f0fc3e1..f15c8f75e 100644--- a/app/actions/settings.go+++ b/app/actions/settings.go@@ -66,7 +66,7 @@ func (input *UpdateUserSettings) Validate(ctx context.Context, user *models.User}}}- if ok == false {+ if !ok {result.AddFieldFailure("settings", fmt.Sprintf("Unknown settings named %s.", k))}}diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex 6eb6a0051..1682f3280 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -207,7 +207,7 @@ func GetComment() web.HandlerFunc {}commentByID := &query.GetCommentByID{CommentID: id}- if bus.Dispatch(c, commentByID); err != nil {+ if err := bus.Dispatch(c, commentByID); err != nil {return c.Failure(err)}diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.goindex d5e08bef3..cdad37321 100644--- a/app/handlers/signin_test.go+++ b/app/handlers/signin_test.go@@ -595,7 +595,7 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {}func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *models.User) {- cookies := response.HeaderMap["Set-Cookie"]+ cookies := response.Header()["Set-Cookie"]if expected == nil {for _, c := range cookies {cookie := web.ParseCookie(c)diff --git a/app/middlewares/compress.go b/app/middlewares/compress.goindex be17b7581..3f228743d 100644--- a/app/middlewares/compress.go+++ b/app/middlewares/compress.go@@ -63,18 +63,21 @@ func (w *gzipResponseWriter) Flush() {w.Header().Set("Content-Encoding", "gzip")w.response.WriteHeader(w.code)w.writer.Reset(w.response)- w.buffer.WriteTo(w.writer)+ _, err := w.buffer.WriteTo(w.writer)+ if err != nil {+ panic(err)+ }+w.writer.Close()} else if w.code > 0 {w.response.WriteHeader(w.code)- w.buffer.WriteTo(w.response)+ _, err := w.buffer.WriteTo(w.response)+ if err != nil {+ panic(err)+ }}}func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {return w.response.(http.Hijacker).Hijack()}--func (w *gzipResponseWriter) CloseNotify() <-chan bool {- return w.response.(http.CloseNotifier).CloseNotify()-}diff --git a/app/middlewares/maintenance.go b/app/middlewares/maintenance.goindex fc18f9c2e..8f70fd742 100644--- a/app/middlewares/maintenance.go+++ b/app/middlewares/maintenance.go@@ -11,7 +11,7 @@ import (func Maintenance() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c *web.Context) error {- if env.Config.Maintenance.Enabled == false {+ if !env.Config.Maintenance.Enabled {return next(c)}diff --git a/app/middlewares/panic.go b/app/middlewares/panic.goindex aea50b9e3..1b7be5044 100644--- a/app/middlewares/panic.go+++ b/app/middlewares/panic.go@@ -14,7 +14,7 @@ func CatchPanic() web.MiddlewareFunc {return func(c *web.Context) error {defer func() {if r := recover(); r != nil {- c.Failure(errors.Panicked(r))+ _ = c.Failure(errors.Panicked(r))c.Rollback()log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} panicked in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{"HttpMethod": c.Request.Method,diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex 45f6b6fd2..79bd66a77 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -36,8 +36,8 @@ func WorkerSetup() worker.MiddlewareFunc {//In case it panics somewheredefer func() {if r := recover(); r != nil {- c.Failure(errors.Panicked(r))- trx.Rollback()+ _ = c.Failure(errors.Panicked(r))+ trx.MustRollback()log.Debugf(c, "Task '@{TaskName:magenta}' panicked in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{"TaskName": c.TaskName(),"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),@@ -49,7 +49,7 @@ func WorkerSetup() worker.MiddlewareFunc {//Execute the chainif err = next(c); err != nil {- trx.Rollback()+ trx.MustRollback()log.Debugf(c, "Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{"TaskName": c.TaskName(),"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),diff --git a/app/middlewares/tenant_test.go b/app/middlewares/tenant_test.goindex 7cbf7ce8f..a46f1a461 100644--- a/app/middlewares/tenant_test.go+++ b/app/middlewares/tenant_test.go@@ -410,7 +410,7 @@ func TestBlockLockedTenants_LockedTenant(t *testing.T) {})Expect(status).Equals(http.StatusTemporaryRedirect)- Expect(response.HeaderMap.Get("Location")).Equals("/signin")+ Expect(response.Header().Get("Location")).Equals("/signin")}func TestBlockLockedTenants_LockedTenant_APICall(t *testing.T) {diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.goindex 87534b46e..b8219e303 100644--- a/app/middlewares/user_test.go+++ b/app/middlewares/user_test.go@@ -64,7 +64,7 @@ func TestUser_WithCookie(t *testing.T) {Expect(status).Equals(http.StatusOK)Expect(response.Body.String()).Equals("Jon Snow")- Expect(response.HeaderMap["Set-Cookie"]).HasLen(0)+ Expect(response.Header()["Set-Cookie"]).HasLen(0)}func TestUser_Blocked(t *testing.T) {@@ -244,7 +244,7 @@ func TestUser_WithSignUpCookie(t *testing.T) {Expect(status).Equals(http.StatusOK)Expect(response.Body.String()).Equals("Jon Snow")- cookies := response.HeaderMap["Set-Cookie"]+ cookies := response.Header()["Set-Cookie"]Expect(cookies).HasLen(2)cookie := web.ParseCookie(cookies[0])diff --git a/app/pkg/assert/assert.go b/app/pkg/assert/assert.goindex a14565836..3f1c5b266 100644--- a/app/pkg/assert/assert.go+++ b/app/pkg/assert/assert.go@@ -53,7 +53,7 @@ func RegisterT(t *testing.T) {}func copyEnv() {- envVariables = make(map[string]string, 0)+ envVariables = make(map[string]string)for _, e := range os.Environ() {key := strings.Split(e, "=")[0]envVariables[key] = os.Getenv(key)diff --git a/app/pkg/backup/export.go b/app/pkg/backup/export.goindex 293fe4085..b7b306de7 100644--- a/app/pkg/backup/export.go+++ b/app/pkg/backup/export.go@@ -51,12 +51,12 @@ func jsonify(rows *sql.Rows) []map[string]interface{} {}for i, value := range values {- switch value.(type) {+ switch value := value.(type) {case nil:results[columns[i]] = nilcase []byte:- s := string(value.([]byte))+ s := string(value)x, err := strconv.Atoi(s)if err != nil {diff --git a/app/pkg/bus/bus.go b/app/pkg/bus/bus.goindex 17398c3e8..9b516372d 100644--- a/app/pkg/bus/bus.go+++ b/app/pkg/bus/bus.go@@ -83,6 +83,13 @@ func AddListener(handler HandlerFunc) {listeners[eventName] = append(listeners[eventName], handler)}+func MustDispatch(ctx context.Context, msgs ...Msg) {+ err := Dispatch(ctx, msgs...)+ if err != nil {+ panic(err)+ }+}+func Dispatch(ctx context.Context, msgs ...Msg) error {if len(msgs) == 0 {return nildiff --git a/app/pkg/dbx/dbx.go b/app/pkg/dbx/dbx.goindex 67e6094a7..765f58fbe 100644--- a/app/pkg/dbx/dbx.go+++ b/app/pkg/dbx/dbx.go@@ -280,6 +280,14 @@ func (trx *Trx) Commit() error {return nil}+// MustCommit current transaction+func (trx *Trx) MustCommit() {+ err := trx.Commit()+ if err != nil {+ panic(err)+ }+}+// Rollback current transactionfunc (trx *Trx) Rollback() error {err := trx.tx.Rollback()@@ -289,6 +297,14 @@ func (trx *Trx) Rollback() error {return nil}+// MustRollback current transaction+func (trx *Trx) MustRollback() {+ err := trx.Rollback()+ if err != nil {+ panic(err)+ }+}+func wrap(err error, format string, a ...interface{}) error {if pqErr, ok := err.(*pq.Error); ok {if pqErr.Code == "57014" { //query canceleddiff --git a/app/pkg/dbx/dbx_test.go b/app/pkg/dbx/dbx_test.goindex 263456564..db7db1abd 100644--- a/app/pkg/dbx/dbx_test.go+++ b/app/pkg/dbx/dbx_test.go@@ -45,7 +45,7 @@ func TestBind_SimpleStruct(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := user{}err := trx.Get(&u, "SELECT id, name FROM users LIMIT 1")@@ -59,7 +59,7 @@ func TestBind_DeepNestedStruct(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := userProvider{}err := trx.Get(&u, `SELECT up.provider,@@ -79,7 +79,7 @@ func TestBind_SimpleStruct_SingleField(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := user{}err := trx.Get(&u, "SELECT name FROM users LIMIT 1")@@ -92,7 +92,7 @@ func TestBind_SimpleStruct_Multiple(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := []*user{}err := trx.Select(&u, "SELECT name FROM users WHERE tenant_id = 1 ORDER BY id")@@ -108,7 +108,7 @@ func TestBind_NestedStruct(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := userWithTenant{}@@ -132,7 +132,7 @@ func TestBind_NestedStruct_Multiple(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()u := []*userWithTenant{}@@ -158,7 +158,7 @@ func TestExists_True(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()exists, err := trx.Exists("SELECT 1 FROM users WHERE id = 1")Expect(err).IsNil()@@ -169,7 +169,7 @@ func TestExists_False(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()exists, err := trx.Exists("SELECT 1 FROM users WHERE id = 0")Expect(err).IsNil()@@ -180,7 +180,7 @@ func TestCount(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()count, err := trx.Count("SELECT 1 FROM users WHERE id = 1")Expect(err).IsNil()@@ -191,7 +191,7 @@ func TestCount_Empty(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()count, err := trx.Count("SELECT 1 FROM users WHERE id = 0")Expect(err).IsNil()@@ -202,7 +202,7 @@ func TestScalar(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()var value interr := trx.Scalar(&value, "SELECT id FROM users WHERE id = 1")@@ -214,7 +214,7 @@ func TestArray(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()type postTags struct {ID int `db:"id"`@@ -234,7 +234,7 @@ func TestArray_Empty(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()type postTags struct {ID int `db:"id"`@@ -254,7 +254,7 @@ func TestByteArray(t *testing.T) {RegisterT(t)trx, _ := dbx.BeginTx(context.Background())- defer trx.Rollback()+ defer trx.MustRollback()type file struct {ContentType string `db:"content_type"`diff --git a/app/pkg/dbx/mapping.go b/app/pkg/dbx/mapping.goindex 0bd15e9d4..88e261428 100644--- a/app/pkg/dbx/mapping.go+++ b/app/pkg/dbx/mapping.go@@ -17,7 +17,7 @@ type RowMapper struct {//NewRowMapper creates a new instance of RowMapperfunc NewRowMapper() *RowMapper {return &RowMapper{- cache: make(map[reflect.Type]TypeMapper, 0),+ cache: make(map[reflect.Type]TypeMapper),}}@@ -83,7 +83,7 @@ type TypeMapper struct {//NewTypeMapper creates a new instance of TypeMapper for given reflect.Typefunc NewTypeMapper(t reflect.Type) TypeMapper {- all := make(map[string]FieldInfo, 0)+ all := make(map[string]FieldInfo)if t.Kind() != reflect.Struct {return TypeMapper{@@ -101,7 +101,6 @@ func NewTypeMapper(t reflect.Type) TypeMapper {if fieldKind == reflect.Ptr {fieldType = field.Type.Elem()- fieldKind = fieldType.Kind()mapper := NewTypeMapper(fieldType)for _, f := range mapper.Fields {all[columnName+"_"+f.ColumnName] = FieldInfo{diff --git a/app/pkg/dbx/mapping_test.go b/app/pkg/dbx/mapping_test.goindex 33621c791..e9d6805a9 100644--- a/app/pkg/dbx/mapping_test.go+++ b/app/pkg/dbx/mapping_test.go@@ -70,7 +70,8 @@ func TestRowMapper_NonStruct(t *testing.T) {RegisterT(t)mapper := dbx.NewRowMapper()var id int- mapper.Map(&id, []string{"id"}, createScanner(5))+ err := mapper.Map(&id, []string{"id"}, createScanner(5))+ Expect(err).IsNil()Expect(id).Equals(5)}@@ -82,7 +83,8 @@ func TestRowMapper_Concurrent(t *testing.T) {wg.Add(1)go func() {var id int- mapper.Map(&id, []string{"id"}, createScanner(5))+ err := mapper.Map(&id, []string{"id"}, createScanner(5))+ Expect(err).IsNil()wg.Done()}()}@@ -93,7 +95,8 @@ func TestRowMapper_SimpleStruct(t *testing.T) {RegisterT(t)mapper := dbx.NewRowMapper()u := user{}- mapper.Map(&u, []string{"id", "name"}, createScanner(1, "Hello World"))+ err := mapper.Map(&u, []string{"id", "name"}, createScanner(1, "Hello World"))+ Expect(err).IsNil()Expect(u.ID).Equals(1)Expect(u.Name).Equals("Hello World")}@@ -102,7 +105,8 @@ func TestRowMapper_NestedStruct(t *testing.T) {RegisterT(t)mapper := dbx.NewRowMapper()u := userWithTenant{}- mapper.Map(&u, []string{"id", "name", "tenant_id", "tenant_name"}, createScanner(1, "Hello World", 2, "Demonstration"))+ err := mapper.Map(&u, []string{"id", "name", "tenant_id", "tenant_name"}, createScanner(1, "Hello World", 2, "Demonstration"))+ Expect(err).IsNil()Expect(u.ID).Equals(1)Expect(u.Name).Equals("Hello World")Expect(u.Tenant.ID).Equals(2)@@ -113,7 +117,8 @@ func TestRowMapper_DeepNestedStruct(t *testing.T) {RegisterT(t)mapper := dbx.NewRowMapper()u := userProvider{}- mapper.Map(&u, []string{"provider", "user_id", "user_name", "user_tenant_id", "user_tenant_name"}, createScanner("google", 1, "Jon Snow", 2, "The Tenant"))+ err := mapper.Map(&u, []string{"provider", "user_id", "user_name", "user_tenant_id", "user_tenant_name"}, createScanner("google", 1, "Jon Snow", 2, "The Tenant"))+ Expect(err).IsNil()Expect(u.Provider).Equals("google")Expect(u.User.ID).Equals(1)Expect(u.User.Name).Equals("Jon Snow")diff --git a/app/pkg/dbx/migrate.go b/app/pkg/dbx/migrate.goindex 9e55d5f75..bfd04cea2 100644--- a/app/pkg/dbx/migrate.go+++ b/app/pkg/dbx/migrate.go@@ -136,7 +136,7 @@ func getLastMigration() (int, error) {// If it's the first run, maybe we have records on old migrations table, so try to get from it.// This SHOULD be removed in the far future.row := conn.QueryRow("SELECT version FROM schema_migrations LIMIT 1")- row.Scan(&lastVersion)+ _ = row.Scan(&lastVersion)}return int(lastVersion.Int64), nildiff --git a/app/pkg/dbx/migrate_test.go b/app/pkg/dbx/migrate_test.goindex 618fa0e5e..7ee8cc504 100644--- a/app/pkg/dbx/migrate_test.go+++ b/app/pkg/dbx/migrate_test.go@@ -13,10 +13,10 @@ func setupMigrationTest(t *testing.T) {ctx := context.Background()trx, _ := dbx.BeginTx(ctx)- trx.Execute("DELETE FROM migrations_history WHERE version >= 210001010000")- trx.Execute("DROP TABLE IF EXISTS dummy")- trx.Execute("DROP TABLE IF EXISTS foo")- trx.Commit()+ _, _ = trx.Execute("DELETE FROM migrations_history WHERE version >= 210001010000")+ _, _ = trx.Execute("DROP TABLE IF EXISTS dummy")+ _, _ = trx.Execute("DROP TABLE IF EXISTS foo")+ trx.MustCommit()}func TestMigrate_Success(t *testing.T) {@@ -36,7 +36,7 @@ func TestMigrate_Success(t *testing.T) {err = trx.Scalar(&count, "SELECT COUNT(*) FROM dummy")Expect(err).IsNil()Expect(count).Equals(2)- trx.Rollback()+ trx.MustRollback()}func TestMigrate_Failure(t *testing.T) {@@ -44,7 +44,7 @@ func TestMigrate_Failure(t *testing.T) {ctx := context.Background()trx, _ := dbx.BeginTx(ctx)- defer trx.Rollback()+ defer trx.MustRollback()err := dbx.Migrate(context.Background(), "/app/pkg/dbx/testdata/migration_failure")Expect(err).IsNotNil()diff --git a/app/pkg/errors/errors.go b/app/pkg/errors/errors.goindex 54021a4fb..8795626a2 100644--- a/app/pkg/errors/errors.go+++ b/app/pkg/errors/errors.go@@ -1,7 +1,6 @@package errorsimport (- stdError "errors""fmt""runtime""runtime/debug"@@ -23,7 +22,7 @@ func caller(skip int) (string, int) {func New(format string, a ...interface{}) error {file, line := caller(2)text := fmt.Sprintf(format, a...)- return stdError.New(fmt.Sprintf("%s (%s:%d)", text, file, line))+ return fmt.Errorf("%s (%s:%d)", text, file, line)}//Wrap existing error with additional textdiff --git a/app/pkg/errors/errors_test.go b/app/pkg/errors/errors_test.goindex dece76419..1319330d3 100644--- a/app/pkg/errors/errors_test.go+++ b/app/pkg/errors/errors_test.go@@ -89,7 +89,7 @@ runtime/debug.Stack`)Expect(err.Error()).ContainsSubstring(`github.com/getfider/fider/app/pkg/errors.Panicked`)Expect(err.Error()).ContainsSubstring(`-- github.com/getfider/fider/app/pkg/errors_test.TestPanicked:84 (app/pkg/errors/errors.go:40)+- github.com/getfider/fider/app/pkg/errors_test.TestPanicked:84 (app/pkg/errors/errors.go:39)- Boom!`)}}()diff --git a/app/pkg/jsonq/jsonq.go b/app/pkg/jsonq/jsonq.goindex a77fa67f6..a4a85270b 100644--- a/app/pkg/jsonq/jsonq.go+++ b/app/pkg/jsonq/jsonq.go@@ -69,7 +69,10 @@ func (q *Query) IsArray() bool {func (q *Query) ArrayLength() int {if q.IsArray() {var arr []interface{}- json.Unmarshal([]byte(q.json), &arr)+ err := json.Unmarshal([]byte(q.json), &arr)+ if err != nil {+ panic(err)+ }return len(arr)}return 0@@ -95,7 +98,7 @@ func (q *Query) get(selector string) *json.RawMessage {idx, _ := strconv.Atoi(part[len(part)-2 : len(part)-1])part = part[:len(part)-3]- if current != nil {+ if current[part] != nil {result = current[part]} else {result = q.m[part]@@ -103,7 +106,11 @@ func (q *Query) get(selector string) *json.RawMessage {if result != nil {var arr []*json.RawMessagebytes, _ := result.MarshalJSON()- json.Unmarshal(bytes, &arr)+ err := json.Unmarshal(bytes, &arr)+ if err != nil {+ panic(err)+ }+if len(arr) > idx {bytes, _ = arr[idx].MarshalJSON()err := json.Unmarshal(bytes, ¤t)@@ -114,7 +121,7 @@ func (q *Query) get(selector string) *json.RawMessage {}} else {- if current != nil {+ if current[part] != nil {result = current[part]} else {result = q.m[part]@@ -122,7 +129,7 @@ func (q *Query) get(selector string) *json.RawMessage {if result != nil {bytes, _ := result.MarshalJSON()- json.Unmarshal(bytes, ¤t)+ _ = json.Unmarshal(bytes, ¤t)} else {return nil}diff --git a/app/pkg/jsonq/jsonq_test.go b/app/pkg/jsonq/jsonq_test.goindex 204bc6d42..42ae1e40f 100644--- a/app/pkg/jsonq/jsonq_test.go+++ b/app/pkg/jsonq/jsonq_test.go@@ -22,6 +22,14 @@ func TestGetNull(t *testing.T) {Expect(query.String("name")).Equals("")}+func TestGet_NestedObject(t *testing.T) {+ RegisterT(t)++ query := jsonq.New(`{ "person": { "name": "Jon Snow", "age": 23 } }`)+ Expect(query.String("person.name")).Equals("Jon Snow")+ Expect(query.Int32("person.age")).Equals(23)+}+func TestGet_EmptyKey(t *testing.T) {RegisterT(t)@@ -62,6 +70,24 @@ func TestGetValueFromObjectArray(t *testing.T) {Expect(query.String("data[1].age")).Equals("23")}+func TestGetValueFromNestedArray(t *testing.T) {+ RegisterT(t)++ query := jsonq.New(`{ "data": [ { "numbers": [52, 6, 24] } ] }`)+ Expect(query.Int32("data[0].numbers[0]")).Equals(52)+ Expect(query.Int32("data[0].numbers[1]")).Equals(6)+ Expect(query.Int32("data[0].numbers[2]")).Equals(24)+}++func TestGetValueFromNestedObjectArray(t *testing.T) {+ RegisterT(t)++ query := jsonq.New(`{ "data": [{ "person": { "name": "Jon Snow" } }, { "person": { "age": "23" } }] }`)+ Expect(query.String("data[0].person.name")).Equals("Jon Snow")+ Expect(query.String("data[0].person.age")).Equals("")+ Expect(query.String("data[1].person.age")).Equals("23")+}+func TestGetValueFromStringArray(t *testing.T) {RegisterT(t)diff --git a/app/pkg/log/props.go b/app/pkg/log/props.goindex 6e2224f3e..5d10dc4a6 100644--- a/app/pkg/log/props.go+++ b/app/pkg/log/props.go@@ -7,8 +7,6 @@ import ("github.com/getfider/fider/app/models/dto")-type logCtxKey string-const (// PropertyKeySessionID is the session id of current loggerPropertyKeySessionID = "SessionID"diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.goindex 03b66caf4..ccf0312a5 100644--- a/app/pkg/mock/server.go+++ b/app/pkg/mock/server.go@@ -105,7 +105,7 @@ func (s *Server) Execute(handler web.HandlerFunc) (int, *httptest.ResponseRecord}if err := next(s.context); err != nil {- s.context.Failure(err)+ _ = s.context.Failure(err)}return s.recorder.Code, s.recorderdiff --git a/app/pkg/validate/general.go b/app/pkg/validate/general.goindex cc654d696..3f81cb131 100644--- a/app/pkg/validate/general.go+++ b/app/pkg/validate/general.go@@ -62,12 +62,12 @@ func CNAME(ctx context.Context, cname string) []string {return []string{"Custom domain name must have less than 100 characters."}}- if !hostnameRegex.MatchString(cname) || strings.Index(cname, ".") == -1 {+ if !hostnameRegex.MatchString(cname) || !strings.Contains(cname, ".") {return []string{fmt.Sprintf("'%s' is not a valid custom domain.", cname)}}isAvailable := &query.IsCNAMEAvailable{CNAME: cname}- bus.Dispatch(ctx, isAvailable)+ bus.MustDispatch(ctx, isAvailable)if !isAvailable.Result {return []string{"This custom domain is already in use by someone else."}}diff --git a/app/pkg/web/binder.go b/app/pkg/web/binder.goindex db3f1fed4..19e0a44b8 100644--- a/app/pkg/web/binder.go+++ b/app/pkg/web/binder.go@@ -45,7 +45,9 @@ func (b *DefaultBinder) Bind(target interface{}, c *Context) error {targetValue := reflect.ValueOf(target).Elem()targetType := targetValue.Type()for i := 0; i < targetValue.NumField(); i++ {- b.bindRoute(i, targetValue, targetType, c.params)+ if err := b.bindRoute(i, targetValue, targetType, c.params); err != nil {+ return err+ }b.format(i, targetValue, targetType)}return nildiff --git a/app/pkg/web/binder_test.go b/app/pkg/web/binder_test.goindex 0fe8adf8f..81fa28d68 100644--- a/app/pkg/web/binder_test.go+++ b/app/pkg/web/binder_test.go@@ -21,7 +21,7 @@ func TestDefaultBinder_FromParams(t *testing.T) {}RegisterT(t)- params := make(web.StringMap, 0)+ params := make(web.StringMap)params["number"] = "2"params["slug"] = "jon-snow"@@ -46,7 +46,7 @@ func TestDefaultBinder_TrimSpaces(t *testing.T) {Other string}- params := make(web.StringMap, 0)+ params := make(web.StringMap)body := `{ "name": " Jon Snow ", "email": " [email protected] ", "color": "ff00ad" }`ctx := newBodyContext("POST", params, body, "application/json")u := new(user)@@ -69,7 +69,7 @@ func TestDefaultBinder_Base64ToBytes(t *testing.T) {Resume []byte `json:"resume"`}- params := make(web.StringMap, 0)+ params := make(web.StringMap)body := fmt.Sprintf(`{ "name": "Jon Snow", "resume": "%s" }`, resumeBase64)ctx := newBodyContext("POST", params, body, "application/json")u := new(user)@@ -93,7 +93,7 @@ func TestDefaultBinder_NestedJson(t *testing.T) {}}- params := make(web.StringMap, 0)+ params := make(web.StringMap)body := fmt.Sprintf(`{ "name": "Jon Snow", "resume": { "fileName": "README.md", "file": "%s" } }`, resumeBase64)ctx := newBodyContext("POST", params, body, "application/json")u := new(user)@@ -111,7 +111,7 @@ func TestDefaultBinder_Array_TrimSpaces(t *testing.T) {Providers []string `json:"providers" format:"lower"`}- params := make(web.StringMap, 0)+ params := make(web.StringMap)body := `{ "providers": [ " Google", " FACEBOOK ", " MicroSoft " ] }`ctx := newBodyContext("POST", params, body, "application/json")u := new(user)@@ -132,7 +132,7 @@ func TestDefaultBinder_DELETE(t *testing.T) {Other string}- params := make(web.StringMap, 0)+ params := make(web.StringMap)body := `{ "name": " Jon Snow " }`ctx := newBodyContext("DELETE", params, body, "application/json")u := new(user)@@ -150,7 +150,7 @@ func TestDefaultBinder_POST_WithoutBody(t *testing.T) {Slug string `route:"slug"`}- params := make(web.StringMap, 0)+ params := make(web.StringMap)params["number"] = "2"params["slug"] = "jon-snow"ctx := newBodyContext("POST", params, "", web.UTF8JSONContentType)@@ -168,7 +168,7 @@ func TestDefaultBinder_POST_NonJSON(t *testing.T) {Name string `json:"name"`}- params := make(web.StringMap, 0)+ params := make(web.StringMap)ctx := newBodyContext("POST", params, `name=JonSnow`, web.UTF8HTMLContentType)u := new(user)@@ -207,7 +207,7 @@ func (p *Size) UnmarshalText(s []byte) error {func TestDefaultBinder_POST_CustomType(t *testing.T) {RegisterT(t)- params := make(web.StringMap, 0)+ params := make(web.StringMap)params["size"] = "1"params["size32"] = "4"params["size64"] = "5"@@ -228,7 +228,7 @@ func TestDefaultBinder_POST_CustomType_Unmarshal(t *testing.T) {TheSize Size `route:"size"`}- params := make(web.StringMap, 0)+ params := make(web.StringMap)params["size"] = "large"ctx := newBodyContext("POST", params, `{ }`, "application/json")diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 56a95b993..292f21aca 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -139,13 +139,11 @@ func (c *Context) Commit() error {}//Rollback everything that is pending on current context-func (c *Context) Rollback() error {+func (c *Context) Rollback() {trx, ok := c.Value(app.TransactionCtxKey).(*dbx.Trx)if ok && trx != nil {- return trx.Rollback()+ trx.MustRollback()}-- return nil}//Enqueue given task to be processed in background@@ -250,10 +248,12 @@ func (c *Context) Failure(err error) error {"URL": c.Request.URL.String(),})- c.Render(http.StatusInternalServerError, "500.html", Props{+ if renderErr := c.Render(http.StatusInternalServerError, "500.html", Props{Title: "Shoot! Well, this is unexpected…",Description: "An error has occurred and we're working to fix the problem!",- })+ }); renderErr != nil {+ return renderErr+ }return err}diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.goindex 75e04a966..20792ba06 100644--- a/app/pkg/web/context_test.go+++ b/app/pkg/web/context_test.go@@ -26,10 +26,8 @@ func newGetContext(rawurl string, headers map[string]string) *web.Context {req.TLS = &tls.ConnectionState{}}- if headers != nil {- for k, v := range headers {- req.Header.Set(k, v)- }+ for k, v := range headers {+ req.Header.Set(k, v)}return web.NewContext(e, req, res, nil)diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex cda51379b..23bf2dca4 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -46,7 +46,7 @@ type notFoundHandler struct {func (h *notFoundHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {ctx := NewContext(h.engine, req, res, nil)- h.handler(ctx)+ _ = h.handler(ctx)}//HandlerFunc represents an HTTP handler@@ -224,12 +224,12 @@ func (e *Engine) handle(middlewares []MiddlewareFunc, handler HandlerFunc) httprnext = middlewares[i](next)}var h = func(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {- params := make(StringMap, 0)+ params := make(StringMap)for _, p := range ps {params[p.Key] = p.Value}ctx := NewContext(e, req, res, params)- next(ctx)+ _ = next(ctx)}return h}diff --git a/app/pkg/web/request_test.go b/app/pkg/web/request_test.goindex 176a4edc2..4a5e4492c 100644--- a/app/pkg/web/request_test.go+++ b/app/pkg/web/request_test.go@@ -12,7 +12,7 @@ import (func TestRequest_Basic(t *testing.T) {RegisterT(t)- header := make(http.Header, 0)+ header := make(http.Header)header.Set("Content-Type", "application/json")req := web.WrapRequest(@@ -37,7 +37,7 @@ func TestRequest_Basic(t *testing.T) {func TestRequest_WithPort(t *testing.T) {RegisterT(t)- header := make(http.Header, 0)+ header := make(http.Header)header.Set("Content-Type", "application/json")req := web.WrapRequest(@@ -62,7 +62,7 @@ func TestRequest_WithPort(t *testing.T) {func TestRequest_BehindTLSTerminationProxy(t *testing.T) {RegisterT(t)- header := make(http.Header, 0)+ header := make(http.Header)header.Set("X-Forwarded-Host", "feedback.mycompany.com")header.Set("X-Forwarded-Proto", "https")header.Set("X-Forwarded-For", "127.5.5.5, 129.2.2.2, 121.2.2.5")@@ -147,7 +147,7 @@ func TestRequest_IsCrawler(t *testing.T) {}for _, tt := range testCases {- header := make(http.Header, 0)+ header := make(http.Header)header.Set("User-Agent", tt.userAgent)req := web.WrapRequest(diff --git a/app/pkg/web/ssl.go b/app/pkg/web/ssl.goindex 4d6845335..85a4d726b 100644--- a/app/pkg/web/ssl.go+++ b/app/pkg/web/ssl.go@@ -97,7 +97,10 @@ func (m *CertificateManager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Ce//StartHTTPServer creates a new HTTP server on port 80 that is used for the ACME HTTP Challengefunc (m *CertificateManager) StartHTTPServer() {- http.ListenAndServe(":80", m.autossl.HTTPHandler(nil))+ err := http.ListenAndServe(":80", m.autossl.HTTPHandler(nil))+ if err != nil {+ panic(err)+ }}func acmeClient() *acme.Client {diff --git a/app/pkg/worker/worker.go b/app/pkg/worker/worker.goindex ce27afdb5..e0fcd7f9f 100644--- a/app/pkg/worker/worker.go+++ b/app/pkg/worker/worker.go@@ -70,7 +70,7 @@ func (w *BackgroundWorker) Run(workerID string) {for task := range w.queue {c := NewContext(w, workerID, task)- w.middleware(task.Job)(c)+ _ = w.middleware(task.Job)(c)w.Lock()w.len = w.len - 1w.Unlock()diff --git a/app/services/billing/billing.go b/app/services/billing/billing.goindex a170637aa..a2ddbaf85 100644--- a/app/services/billing/billing.go+++ b/app/services/billing/billing.go@@ -32,7 +32,7 @@ func (s Service) Enabled() bool {}func (s Service) Init() {- stripe.LogLevel = 0+ stripe.DefaultLeveledLogger = &stripe.LeveledLogger{Level: 0}stripeClient = &client.API{}stripeClient.Init(env.Config.Stripe.SecretKey, nil)diff --git a/app/services/billing/billing_test.go b/app/services/billing/billing_test.goindex 0e35655e5..55b30b781 100644--- a/app/services/billing/billing_test.go+++ b/app/services/billing/billing_test.go@@ -103,6 +103,7 @@ func TestUpdatePaymentInfo(t *testing.T) {AddressCountry: "IE",},})+ Expect(err).IsNil()paymentInfoQuery := &query.GetPaymentInfo{}err = bus.Dispatch(ctx, paymentInfoQuery)diff --git a/app/services/blob/blob_test.go b/app/services/blob/blob_test.goindex 44f5f5bb7..b7374ba8e 100644--- a/app/services/blob/blob_test.go+++ b/app/services/blob/blob_test.go@@ -36,7 +36,7 @@ func setupS3(t *testing.T) {bus.Init(s3.Service{})bucket := aws.String(env.Config.BlobStorage.S3.BucketName)- s3.DefaultClient.CreateBucket(&awss3.CreateBucketInput{+ _, _ = s3.DefaultClient.CreateBucket(&awss3.CreateBucketInput{Bucket: bucket,})}diff --git a/app/services/blob/s3/s3.go b/app/services/blob/s3/s3.goindex 59e3655e1..75aea2b19 100644--- a/app/services/blob/s3/s3.go+++ b/app/services/blob/s3/s3.go@@ -59,7 +59,11 @@ func (s Service) Init() {DisableSSL: aws.Bool(strings.HasSuffix(s3EnvConfig.EndpointURL, "http://")),S3ForcePathStyle: aws.Bool(true),}- awsSession := session.New(s3Config)+ awsSession, err := session.NewSession(s3Config)+ if err != nil {+ panic(err)+ }+DefaultClient = s3.New(awsSession)}diff --git a/app/services/blob/sql/sql.go b/app/services/blob/sql/sql.goindex 31e4bb1db..afbc16397 100644--- a/app/services/blob/sql/sql.go+++ b/app/services/blob/sql/sql.go@@ -59,7 +59,7 @@ func listBlobs(ctx context.Context, q *query.ListBlobs) error {if err != nil {return errors.Wrap(err, "failed to open transaction")}- defer trx.Commit()+ defer trx.MustCommit()blobs := []*dbBlob{}err = trx.Select(&blobs, "SELECT key FROM blobs WHERE tenant_id = $1", tenant.ID)@@ -82,14 +82,17 @@ func getBlobByKey(ctx context.Context, q *query.GetBlobByKey) error {return using(ctx, func(tenant *models.Tenant) error {var tenantID sql.NullInt64if tenant != nil {- tenantID.Scan(tenant.ID)+ err := tenantID.Scan(tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed scan tenant id")+ }}trx, err := dbx.BeginTx(ctx)if err != nil {return errors.Wrap(err, "failed to open transaction")}- defer trx.Commit()+ defer trx.MustCommit()b := dbBlob{}err = trx.Get(&b, "SELECT file, content_type, size FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", q.Key, tenantID)@@ -117,14 +120,17 @@ func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {return using(ctx, func(tenant *models.Tenant) error {var tenantID sql.NullInt64if tenant != nil {- tenantID.Scan(tenant.ID)+ err := tenantID.Scan(tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed scan tenant id")+ }}trx, err := dbx.BeginTx(ctx)if err != nil {return errors.Wrap(err, "failed to open transaction")}- defer trx.Commit()+ defer trx.MustCommit()now := time.Now()_, err = trx.Execute(`@@ -148,14 +154,17 @@ func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {return using(ctx, func(tenant *models.Tenant) error {var tenantID sql.NullInt64if tenant != nil {- tenantID.Scan(tenant.ID)+ err := tenantID.Scan(tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed scan tenant id")+ }}trx, err := dbx.BeginTx(ctx)if err != nil {return errors.Wrap(err, "failed to open transaction")}- defer trx.Commit()+ defer trx.MustCommit()_, err = trx.Execute("DELETE FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", c.Key, tenantID)if err != nil {diff --git a/app/services/log/sql/sql.go b/app/services/log/sql/sql.goindex 3f95199bd..fb51d4898 100644--- a/app/services/log/sql/sql.go+++ b/app/services/log/sql/sql.go@@ -73,8 +73,10 @@ func writeLog(ctx context.Context, level log.Level, message string, props dto.Pr}delete(props, log.PropertyKeyTag)- go dbx.Connection().Exec(- "INSERT INTO logs (tag, level, text, created_at, properties) VALUES ($1, $2, $3, $4, $5)",- tag, level.String(), message, time.Now(), props,- )+ go func() {+ _, _ = dbx.Connection().Exec(+ "INSERT INTO logs (tag, level, text, created_at, properties) VALUES ($1, $2, $3, $4, $5)",+ tag, level.String(), message, time.Now(), props,+ )+ }()}diff --git a/app/services/sqlstore/postgres/attachment.go b/app/services/sqlstore/postgres/attachment.goindex 614a1923d..86db24110 100644--- a/app/services/sqlstore/postgres/attachment.go+++ b/app/services/sqlstore/postgres/attachment.go@@ -20,7 +20,10 @@ func setAttachments(ctx context.Context, c *cmd.SetAttachments) error {postID := c.Post.IDvar commentID sql.NullInt64if c.Comment != nil {- commentID.Scan(c.Comment.ID)+ err := commentID.Scan(c.Comment.ID)+ if err != nil {+ return errors.Wrap(err, "failed scan comment id")+ }}for _, attachment := range c.Attachments {@@ -52,7 +55,10 @@ func getAttachments(ctx context.Context, q *query.GetAttachments) error {postID := q.Post.IDvar commentID sql.NullInt64if q.Comment != nil {- commentID.Scan(q.Comment.ID)+ err := commentID.Scan(q.Comment.ID)+ if err != nil {+ return errors.Wrap(err, "failed scan comment id")+ }}type entry struct {diff --git a/app/services/sqlstore/postgres/notifications_test.go b/app/services/sqlstore/postgres/notifications_test.goindex 4c1285e62..38290af47 100644--- a/app/services/sqlstore/postgres/notifications_test.go+++ b/app/services/sqlstore/postgres/notifications_test.go@@ -76,10 +76,11 @@ func TestNotificationStorage_GetActiveNotifications(t *testing.T) {Expect(err).IsNil()Expect(activeNotifications.Result).HasLen(2)- bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[0].ID})- bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[1].ID})+ bus.MustDispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[0].ID})+ bus.MustDispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[1].ID})- trx.Execute("UPDATE notifications SET updated_at = $1 WHERE id = $2", time.Now().AddDate(0, 0, -31), activeNotifications.Result[0].ID)+ _, err = trx.Execute("UPDATE notifications SET updated_at = $1 WHERE id = $2", time.Now().AddDate(0, 0, -31), activeNotifications.Result[0].ID)+ Expect(err).IsNil()err = bus.Dispatch(aryaStarkCtx, activeNotifications)Expect(err).IsNil()diff --git a/app/services/sqlstore/postgres/post_test.go b/app/services/sqlstore/postgres/post_test.goindex 075d8b27d..01e2ffe94 100644--- a/app/services/sqlstore/postgres/post_test.go+++ b/app/services/sqlstore/postgres/post_test.go@@ -23,11 +23,14 @@ func TestPostStorage_GetAll(t *testing.T) {now := time.Now()- trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('add twitter integration', 'add-twitter-integration', 1, 'Would be great to see it integrated with twitter', $1, 1, 1, 1)", now)- trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('this is my post', 'this-is-my-post', 2, 'no description', $1, 1, 2, 2)", now)+ _, err := trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('add twitter integration', 'add-twitter-integration', 1, 'Would be great to see it integrated with twitter', $1, 1, 1, 1)", now)+ Expect(err).IsNil()++ _, err = trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('this is my post', 'this-is-my-post', 2, 'no description', $1, 1, 2, 2)", now)+ Expect(err).IsNil()allPosts := &query.GetAllPosts{}- err := bus.Dispatch(demoTenantCtx, allPosts)+ err = bus.Dispatch(demoTenantCtx, allPosts)Expect(err).IsNil()Expect(allPosts.Result).HasLen(2)@@ -111,8 +114,11 @@ func TestPostStorage_AddAndReturnComments(t *testing.T) {err := bus.Dispatch(jonSnowCtx, newPost)Expect(err).IsNil()- bus.Dispatch(jonSnowCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #1"})- bus.Dispatch(aryaStarkCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #2"})+ err = bus.Dispatch(jonSnowCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #1"})+ Expect(err).IsNil()++ err = bus.Dispatch(aryaStarkCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #2"})+ Expect(err).IsNil()commentsByPost := &query.GetCommentsByPost{Post: newPost.Result}err = bus.Dispatch(aryaStarkCtx, commentsByPost)@@ -365,16 +371,16 @@ func TestPostStorage_SetResponse_ChangeText(t *testing.T) {getPost := &query.GetPostByID{PostID: newPost.Result.ID}- bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostStarted})- bus.Dispatch(jonSnowCtx, getPost)+ bus.MustDispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostStarted})+ bus.MustDispatch(jonSnowCtx, getPost)firstResponseAt := getPost.Result.Response.RespondedAt- bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post and we'll work on it", Status: enum.PostStarted})- bus.Dispatch(jonSnowCtx, getPost)+ bus.MustDispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post and we'll work on it", Status: enum.PostStarted})+ bus.MustDispatch(jonSnowCtx, getPost)Expect(getPost.Result.Response.RespondedAt).Equals(firstResponseAt)- bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We finished it", Status: enum.PostCompleted})- bus.Dispatch(jonSnowCtx, getPost)+ bus.MustDispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We finished it", Status: enum.PostCompleted})+ bus.MustDispatch(jonSnowCtx, getPost)Expect(getPost.Result.Response.RespondedAt).TemporarilySimilar(firstResponseAt, time.Second)}@@ -425,7 +431,7 @@ func TestPostStorage_SetResponse_AsDeleted(t *testing.T) {err := bus.Dispatch(jonSnowCtx, newPost)Expect(err).IsNil()- bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Spam!", Status: enum.PostDeleted})+ bus.MustDispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Spam!", Status: enum.PostDeleted})postByID := &query.GetPostByID{PostID: newPost.Result.ID}err = bus.Dispatch(aryaStarkCtx, postByID)@@ -466,7 +472,7 @@ func TestPostStorage_RemoveVote_ClosedPost(t *testing.T) {err := bus.Dispatch(jonSnowCtx, newPost)Expect(err).IsNil()- bus.Dispatch(+ bus.MustDispatch(jonSnowCtx,&cmd.AddVote{Post: newPost.Result, User: jonSnow},&cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostCompleted},@@ -489,9 +495,9 @@ func TestPostStorage_WithTags(t *testing.T) {addBug := &cmd.AddNewTag{Name: "Bug", Color: "FF0000", IsPublic: true}addFeatureRequest := &cmd.AddNewTag{Name: "Feature Request", Color: "00FF00", IsPublic: false}- bus.Dispatch(jonSnowCtx, addBug, addFeatureRequest)- bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addBug.Result, Post: newPost.Result})- bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addFeatureRequest.Result, Post: newPost.Result})+ bus.MustDispatch(jonSnowCtx, addBug, addFeatureRequest)+ bus.MustDispatch(jonSnowCtx, &cmd.AssignTag{Tag: addBug.Result, Post: newPost.Result})+ bus.MustDispatch(jonSnowCtx, &cmd.AssignTag{Tag: addFeatureRequest.Result, Post: newPost.Result})getPost := &query.GetPostByNumber{Number: newPost.Result.Number}err = bus.Dispatch(aryaStarkCtx, getPost)@@ -516,8 +522,8 @@ func TestPostStorage_IsReferenced(t *testing.T) {err := bus.Dispatch(jonSnowCtx, newPost1, newPost2, newPost3)Expect(err).IsNil()- bus.Dispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost2.Result, Original: newPost3.Result})- bus.Dispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost3.Result, Original: newPost1.Result})+ bus.MustDispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost2.Result, Original: newPost3.Result})+ bus.MustDispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost3.Result, Original: newPost1.Result})isReferenced1 := &query.PostIsReferenced{PostID: newPost1.Result.ID}isReferenced2 := &query.PostIsReferenced{PostID: newPost2.Result.ID}@@ -538,8 +544,8 @@ func TestPostStorage_ListVotesOfPost(t *testing.T) {err := bus.Dispatch(jonSnowCtx, newPost)Expect(err).IsNil()- bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: jonSnow})- bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: aryaStark})+ bus.MustDispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: jonSnow})+ bus.MustDispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: aryaStark})listVotes := &query.ListPostVotes{PostID: newPost.Result.ID}err = bus.Dispatch(jonSnowCtx, listVotes)diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex 8e0e74bcc..058a18ac8 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -8,11 +8,8 @@ import ("github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/dbx"- "github.com/stripe/stripe-go/client")-var stripeClient *client.API-func init() {bus.Register(Service{})}diff --git a/app/services/sqlstore/postgres/setup_test.go b/app/services/sqlstore/postgres/setup_test.goindex f5da5ca06..50985ceda 100644--- a/app/services/sqlstore/postgres/setup_test.go+++ b/app/services/sqlstore/postgres/setup_test.go@@ -52,7 +52,7 @@ func SetupDatabaseTest(t *testing.T) context.Context {getDemo := &query.GetTenantByDomain{Domain: "demo"}getAvengers := &query.GetTenantByDomain{Domain: "avengers"}getGameOfThrones := &query.GetTenantByDomain{Domain: "got"}- bus.Dispatch(trxCtx, getDemo, getAvengers, getGameOfThrones)+ _ = bus.Dispatch(trxCtx, getDemo, getAvengers, getGameOfThrones)demoTenant = getDemo.ResultavengersTenant = getAvengers.ResultgotTenant = getGameOfThrones.Result@@ -64,13 +64,13 @@ func SetupDatabaseTest(t *testing.T) context.Context {getJonSnow := &query.GetUserByEmail{Email: "[email protected]"}getAryaStark := &query.GetUserByEmail{Email: "[email protected]"}getSansaStark := &query.GetUserByEmail{Email: "[email protected]"}- bus.Dispatch(demoTenantCtx, getJonSnow, getSansaStark, getAryaStark)+ _ = bus.Dispatch(demoTenantCtx, getJonSnow, getSansaStark, getAryaStark)jonSnow = getJonSnow.ResultaryaStark = getAryaStark.ResultsansaStark = getSansaStark.ResultgetTonyStark := &query.GetUserByEmail{Email: "[email protected]"}- bus.Dispatch(avengersTenantCtx, getTonyStark)+ bus.MustDispatch(avengersTenantCtx, getTonyStark)tonyStark = getTonyStark.ResultjonSnowCtx = withUser(trxCtx, jonSnow)@@ -81,7 +81,7 @@ func SetupDatabaseTest(t *testing.T) context.Context {}func TeardownDatabaseTest() {- trx.Rollback()+ trx.MustRollback()}func TestMain(m *testing.M) {diff --git a/app/services/sqlstore/postgres/subscription_test.go b/app/services/sqlstore/postgres/subscription_test.goindex b04762f7f..bea2a6f45 100644--- a/app/services/sqlstore/postgres/subscription_test.go+++ b/app/services/sqlstore/postgres/subscription_test.go@@ -142,8 +142,8 @@ func TestSubscription_AdminUnsubscribed(t *testing.T) {err := bus.Dispatch(aryaStarkCtx, newPost)Expect(err).IsNil()- bus.Dispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: aryaStark})- bus.Dispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: jonSnow})+ bus.MustDispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: aryaStark})+ bus.MustDispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: jonSnow})newCommentSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}err = bus.Dispatch(aryaStarkCtx, newCommentSubscribers)@@ -286,7 +286,8 @@ func TestSubscription_DeletedPost(t *testing.T) {err := bus.Dispatch(aryaStarkCtx, newPost)Expect(err).IsNil()- bus.Dispatch(aryaStarkCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Invalid Post!", Status: enum.PostDeleted})+ err = bus.Dispatch(aryaStarkCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Invalid Post!", Status: enum.PostDeleted})+ Expect(err).IsNil()q := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}err = bus.Dispatch(aryaStarkCtx, q)diff --git a/app/services/sqlstore/postgres/tenant_test.go b/app/services/sqlstore/postgres/tenant_test.goindex 910fb18a4..2b0374e1c 100644--- a/app/services/sqlstore/postgres/tenant_test.go+++ b/app/services/sqlstore/postgres/tenant_test.go@@ -107,7 +107,7 @@ func TestTenantStorage_Empty_First(t *testing.T) {ctx := SetupDatabaseTest(t)defer TeardownDatabaseTest()- trx.Execute("TRUNCATE tenants CASCADE")+ _, _ = trx.Execute("TRUNCATE tenants CASCADE")getFirst := &query.GetFirstTenant{}err := bus.Dispatch(ctx, getFirst)diff --git a/app/services/sqlstore/postgres/user.go b/app/services/sqlstore/postgres/user.goindex f2e1efdc0..4be35cf6c 100644--- a/app/services/sqlstore/postgres/user.go+++ b/app/services/sqlstore/postgres/user.go@@ -318,11 +318,11 @@ func updateCurrentUser(ctx context.Context, c *cmd.UpdateCurrentUser) error {func getUserByID(ctx context.Context, q *query.GetUserByID) error {return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {- user, err := queryUser(ctx, trx, "id = $1", q.UserID)+ u, err := queryUser(ctx, trx, "id = $1", q.UserID)if err != nil {return errors.Wrap(err, "failed to get user with id '%d'", q.UserID)}- q.Result = user+ q.Result = ureturn nil})}@@ -330,11 +330,11 @@ func getUserByID(ctx context.Context, q *query.GetUserByID) error {func getUserByEmail(ctx context.Context, q *query.GetUserByEmail) error {return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {email := strings.ToLower(q.Email)- user, err := queryUser(ctx, trx, "email = $1 AND tenant_id = $2", email, tenant.ID)+ u, err := queryUser(ctx, trx, "email = $1 AND tenant_id = $2", email, tenant.ID)if err != nil {return errors.Wrap(err, "failed to get user with email '%s'", email)}- q.Result = user+ q.Result = ureturn nil})}diff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.goindex 849d34580..9761f9ae1 100644--- a/app/services/sqlstore/postgres/user_test.go+++ b/app/services/sqlstore/postgres/user_test.go@@ -157,11 +157,12 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {defer TeardownDatabaseTest()var tenantID int- trx.Get(&tenantID, `+ err := trx.Get(&tenantID, `INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey)VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '')RETURNING id`)+ Expect(err).IsNil()newTenantCtx := context.WithValue(ctx, app.TenantCtxKey, &models.Tenant{ID: tenantID})@@ -181,7 +182,7 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {},}- err := bus.Dispatch(newTenantCtx, &cmd.RegisterUser{User: user})+ err = bus.Dispatch(newTenantCtx, &cmd.RegisterUser{User: user})Expect(err).IsNil()Expect(user.ID).NotEquals(0)Expect(user.Name).Equals("Jon Snow")diff --git a/magefile.go b/magefile.goindex 3d6d04b65..fc6acf1cf 100644--- a/magefile.go+++ b/magefile.go@@ -26,6 +26,7 @@ var requiredDeps = []string{"npm","node","mage",+ "golangci-lint",}var buildTime = time.Now().Format("2006.01.02.150405")var buildNumber = os.Getenv("CIRCLE_BUILD_NUM")@@ -35,6 +36,7 @@ var Aliases = map[string]interface{}{"build": Build.All,"test": Test.All,"watch": Watch.All,+ "lint": Lint.All,}func init() {@@ -58,10 +60,6 @@ func Migrate() error {return sh.Run("godotenv", "-f", ".env", "./"+exeName, "migrate")}-func Lint() error {- return sh.Run("npx", "tslint", "-c", "tslint.json", "'public/**/*.{ts,tsx}'", "'tests/**/*.{ts,tsx}'")-}-func Clean() error {os.RemoveAll("./dist")return os.Mkdir("./dist", 0777)@@ -138,6 +136,20 @@ func (Test) UI() error {return sh.RunWith(env, "npx", "jest", "./public")}+type Lint mg.Namespace++func (Lint) All() {+ mg.Deps(Lint.Server, Lint.UI)+}++func (Lint) UI() error {+ return sh.Run("npx", "tslint", "-c", "tslint.json", "'public/**/*.{ts,tsx}'", "'tests/**/*.{ts,tsx}'")+}++func (Lint) Server() error {+ return sh.Run("golangci-lint", "run")+}+// Utilsfunc buildServer(env map[string]string) error {ldflags := "-s -w -X main.buildtime=" + buildTime + " -X main.buildnumber=" + buildNumber