From e3705a60f16cc58e75b61de9703038bc51130493 Mon Sep 17 00:00:00 2001 From: David Garay Date: Wed, 27 Jul 2022 23:21:31 -0700 Subject: [PATCH] Fix linting added revive config file --- .github/workflows/build.yml | 7 ++-- .vscode/targets.log | 41 ++++++++++------------ LICENSE | 21 ------------ cmd/server/main.go | 8 ++--- internal/apikey/service_test.go | 14 ++++---- internal/auth/api.go | 2 +- internal/auth/api_test.go | 6 ++-- internal/auth/repository.go | 4 +-- internal/auth/repository_test.go | 1 - internal/auth/service.go | 2 +- internal/auth/service_test.go | 18 +++++----- internal/config/config.go | 9 +++-- internal/entity/emailverification.go | 2 +- internal/entity/key.go | 2 +- internal/entity/short.go | 2 +- internal/entity/user.go | 2 +- internal/errors/middleware_test.go | 13 +++---- internal/my/api.go | 4 +-- internal/my/service_test.go | 34 +++++++++---------- internal/short/api.go | 5 ++- internal/short/service.go | 12 +++---- internal/short/service_test.go | 18 +++++----- pkg/dbcontext/db_test.go | 1 - revive.toml | 51 ++++++++++++++++++++++++++++ 24 files changed, 149 insertions(+), 130 deletions(-) delete mode 100644 LICENSE create mode 100644 revive.toml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e3d2992..f5926fc 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,13 +40,12 @@ jobs: go mod verify go get golang.org/x/tools/cmd/cover go get github.com/mattn/goveralls - go get golang.org/x/lint/golint + go get github.com/mgechev/revive - name: Run Revive run: | - GO111MODULE=off go get github.com/mgechev/revive - $(go env GOPATH)/bin/revive ./... # this is ouput for user - $(go env GOPATH)/bin/revive ./...| xargs -0 -r false # this is for github actions + $(go env GOPATH)/bin/revive -config revive.toml ./... # this is ouput for user + $(go env GOPATH)/bin/revive -config revive.toml ./...| xargs -0 -r false # this is for github actions - name: Build run: make build diff --git a/.vscode/targets.log b/.vscode/targets.log index ccfd466..f7994bd 100644 --- a/.vscode/targets.log +++ b/.vscode/targets.log @@ -6,14 +6,8 @@ make.exe all --print-data-base --no-builtin-variables --no-builtin-rules --quest # ALG�N PROP�SITO PARTICULAR. # Este programa fue construido para i386-pc-mingw32 - -"grep" no se reconoce como un comando interno o externo, -programa o archivo por lotes ejecutable. - -El sistema no puede encontrar la ruta especificada. - -# Base de datos del Make, mostrada en Wed Jul 27 14:58:47 2022 +# Base de datos del Make, mostrada en Wed Jul 27 22:36:45 2022 # Variables @@ -40,8 +34,7 @@ SHELL := sh.exe # entorno WINDIR = C:\WINDOWS # entorno -VSCODE_NLS_CO -NFIG = {"locale":"es-419","availableLanguages":{},"_languagePackSupport":true} +VSCODE_NLS_CONFIG = {"locale":"es-419","availableLanguages":{},"_languagePackSupport":true} # entorno ONEDRIVE = C:\Users\Gara\OneDrive # entorno @@ -93,7 +86,7 @@ CONFIG_FILE = ./config/local.yml # autom�tica/o %F = $(notdir $%) # entorno -CHROME_CRASHPAD_PIPE_NAME = \\.\pipe\crashpad_10676_XWFJEHNJBKSNRJJG +CHROME_CRASHPAD_PIPE_NAME = \\.\pipe\crashpad_15460_GWVZDVDUABSFQJTQ # entorno COMPUTERNAME = GARA # entorno @@ -209,7 +202,7 @@ PROCESSOR_LEVEL = 23 # makefile (de `makefile', l�nea 10): PID_FILE := './.pid' # entorno -VSCODE_PID = 10676 +VSCODE_PID = 15460 # entorno USERDOMAIN_ROAMINGPROFILE = GARA # estad�sticas del conjunto de variables de la tabla de hash: @@ -231,7 +224,7 @@ USERDOMAIN_ROAMINGPROFILE = GARA # C:\Program Files (x86)\Razer Chroma SDK\bin (llave C:/Program Files (x86)/Razer Chroma SDK/bin, mtime 1658930707): 233 archivos, no imposibilidades. # C:\Windows\System32\WindowsPowerShell\v1.0\ (llave C:/Windows/System32/WindowsPowerShell/v1.0/, mtime 1644603813): 32 archivos, no imposibilidades. # C:\Windows\System32\Wbem (llave C:/Windows/System32/Wbem, mtime 1657698128): 172 archivos, no imposibilidades. -# . (llave g:/proyectos/goshortv2, mtime 1658651726): 21 archivos, no imposibilidades. +# . (llave g:/proyectos/goshortv2, mtime 1658986341): 19 archivos, no imposibilidades. # C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common (llave C:/Program Files (x86)/NVIDIA Corporation/PhysX/Common, mtime 1592079710): 10 archivos, no imposibilidades. # C:\Users\Gara\AppData\Local\Programs\Microsoft VS Code\bin (llave C:/Users/Gara/AppData/Local/Programs/Microsoft VS Code/bin, mtime 1658242550): 4 archivos, no imposibilidades. # C:\Users\Gara\AppData\Roaming\Python\Python39\Scripts (llave C:/Users/Gara/AppData/Roaming/Python/Python39/Scripts, mtime 1631553126): 25 archivos, no imposibilidades. @@ -263,21 +256,16 @@ USERDOMAIN_ROAMINGPROFILE = GARA # C:\Program Files\dotnet\ (llave C:/Program Files/dotnet/, mtime 1657664583): 13 archivos, no imposibilidades. # C:\Program Files\Razer Chroma SDK\bin (llave C:/Program Files/Razer Chroma SDK/bin, mtime 1636131824): 5 archivos, no imposibilidades. # C:\Program Files\PostgreSQL\12\bin: podr�a no estar establecido. -# C:\Users\Gara\go\bin (llave C:/Users/Gara/go/bin, mtime 1658018312): 18 archivos, no imposibilidades. +# C:\Users\Gara\go\bin (llave C:/Users/Gara/go/bin, mtime 1658983262): 19 archivos, no imposibilidades. # C:\ProgramData\DockerDesktop\version-bin: podr�a no estar establecido. # C:\Users\Gara\AppData\Local\gitkraken\bin (llave C:/Users/Gara/AppData/Local/gitkraken/bin, mtime 1657405896): 3 archivos, no imposibilidades. # C:\Program Files\Git\cmd (llave C:/Program Files/Git/cmd, mtime 1620839345): 8 archivos, no imposibilidades. -# C:\Windows\system32 (llave C:/Windows/system32, mtime 1658912261): 3113 archivos, no imposibilidades. +# C:\Windows\system32 (llave C:/Windows/system32, mtime 1658972896): 3113 archivos, no imposibilidades. # C:\Python38\Lib\site-packages (llave C:/Python38/Lib/site-packages, mtime 1612848763): 85 archivos, no imposibilidades. # C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR (llave C:/Program Files/NVIDIA Corporation/NVIDIA NvDLISR, mtime 1592079149): 5 archivos, no imposibilidades. -# C:\WINDOWS\system32\config\systemprofile\AppData\Local\ -process_begin: CreateProcess(NULL, pwd, ...) failed. -process_begin: CreateProcess(NULL, sed -n s/^dsn:[[:space:]]*\"\(.*\)\"/\1/p ./config/local.yml, ...) failed. -make.exe: *** No hay ninguna regla para construir el objetivo `all'. Alto. +# C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps: podr�a no estar establecido. -Microsoft\WindowsApps: podr�a no estar establecido. - -# 4263 archivos, no imposibilidades en 50 directorios. +# 4262 archivos, no imposibilidades en 50 directorios. # Reglas impl�citas. @@ -374,7 +362,7 @@ test: # No es un objetivo: makefile: # La b�squeda de reglas impl�citas ha sido efectuada. -# �ltima modificaci�n 2022-07-19 22:35:30 +# �ltima modificaci�n 2022-07-27 22:21:38 # El archivo ha sido actualizado. # Actualizado con �xito. # estad�sticas del conjunto de variables de la tabla de hash: @@ -528,6 +516,13 @@ run-live: # strcache size: total = 4096 / max = 4096 / min = 4096 / avg = 4096 # strcache free: total = 4087 / max = 4087 / min = 4087 / avg = 4087 -# Se termina la base de datos de Make en Wed Jul 27 14:58:47 2022 +# Se termina la base de datos de Make en Wed Jul 27 22:36:45 2022 +"grep" no se reconoce como un comando interno o externo, +programa o archivo por lotes ejecutable. +El sistema no puede encontrar la ruta especificada. +process_begin: CreateProcess(NULL, pwd, ...) failed. +process_begin: CreateProcess(NULL, sed -n s/^dsn:[[:space:]]*\"\(.*\)\"/\1/p ./config/local.yml, ...) failed. +make.exe: *** No hay ninguna regla para construir el objetivo `all'. Alto. + diff --git a/LICENSE b/LICENSE deleted file mode 100644 index b2899ff..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019-2020 Qiang Xue - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/cmd/server/main.go b/cmd/server/main.go index dab2d04..2a1a70a 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -57,9 +57,9 @@ func main() { } }() - dbcontext := dbcontext.New(db) + newDbcontext := dbcontext.New(db) - err = cfg.GetConfigFromDB(dbcontext, logger) + err = cfg.GetConfigFromDB(newDbcontext) if err != nil { logger.Errorf("failed to load aditional dynamic configuration: %s", err) os.Exit(-1) @@ -69,7 +69,7 @@ func main() { address := fmt.Sprintf(":%v", cfg.ServerPort) hs := &http.Server{ Addr: address, - Handler: buildHandler(logger, dbcontext, cfg), + Handler: buildHandler(logger, newDbcontext, cfg), } // start the HTTP server with graceful shutdown @@ -82,7 +82,7 @@ func main() { } // buildHandler sets up the HTTP routing and builds an HTTP handler. -func buildHandler(logger log.Logger, db *dbcontext.DB, cfg *config.Config) http.Handler { +func buildHandler(logger log.Logger, db *newDbcontext.DB, cfg *config.Config) http.Handler { router := routing.New() router.Use( diff --git a/internal/apikey/service_test.go b/internal/apikey/service_test.go index a54f438..e51a8ba 100644 --- a/internal/apikey/service_test.go +++ b/internal/apikey/service_test.go @@ -61,7 +61,7 @@ type mockRepository struct { items []entity.APIKey } -func (m mockRepository) Get(ctx context.Context, key string) (entity.APIKey, error) { +func (m mockRepository) Get(_ context.Context, key string) (entity.APIKey, error) { if key == "error" || key == "none" { return entity.APIKey{}, sql.ErrNoRows } @@ -75,7 +75,7 @@ func (m mockRepository) Get(ctx context.Context, key string) (entity.APIKey, err return entity.APIKey{}, sql.ErrNoRows } -func (m mockRepository) GetOwned(ctx context.Context, userID string) ([]APIKey, error) { +func (m mockRepository) GetOwned(_ context.Context, userID string) ([]APIKey, error) { var owned []APIKey for _, item := range m.items { if item.UserID == userID { @@ -90,11 +90,11 @@ func (m mockRepository) GetOwned(ctx context.Context, userID string) ([]APIKey, return []APIKey{}, sql.ErrNoRows } -func (m mockRepository) Count(ctx context.Context) (int, error) { +func (m mockRepository) Count(_ context.Context) (int, error) { return len(m.items), nil } -func (m mockRepository) CountByOwner(ctx context.Context, userID string) (int, error) { +func (m mockRepository) CountByOwner(_ context.Context, userID string) (int, error) { var count int for _, item := range m.items { @@ -106,7 +106,7 @@ func (m mockRepository) CountByOwner(ctx context.Context, userID string) (int, e return count, nil } -func (m *mockRepository) Create(ctx context.Context, apiKey entity.APIKey) error { +func (m *mockRepository) Create(_ context.Context, apiKey entity.APIKey) error { if apiKey.UserID == "error" { return errCRUD } @@ -114,7 +114,7 @@ func (m *mockRepository) Create(ctx context.Context, apiKey entity.APIKey) error return nil } -func (m *mockRepository) Update(ctx context.Context, apiKey entity.APIKey) error { +func (m *mockRepository) Update(_ context.Context, apiKey entity.APIKey) error { if apiKey.Key == "error" { return errCRUD } @@ -127,7 +127,7 @@ func (m *mockRepository) Update(ctx context.Context, apiKey entity.APIKey) error return nil } -func (m *mockRepository) Delete(ctx context.Context, key string) error { +func (m *mockRepository) Delete(_ context.Context, key string) error { for i, item := range m.items { if item.Key == key { m.items[i] = m.items[len(m.items)-1] diff --git a/internal/auth/api.go b/internal/auth/api.go index c6c9219..75f44e4 100644 --- a/internal/auth/api.go +++ b/internal/auth/api.go @@ -63,7 +63,7 @@ func register(service Service, logger log.Logger) routing.Handler { } } -func verify(service Service, logger log.Logger) routing.Handler { +func verify(service Service, _ log.Logger) routing.Handler { return func(c *routing.Context) error { id := c.Param("id") token := c.Param("token") diff --git a/internal/auth/api_test.go b/internal/auth/api_test.go index 66822a8..5e47cd2 100644 --- a/internal/auth/api_test.go +++ b/internal/auth/api_test.go @@ -12,21 +12,21 @@ import ( type mockService struct{} -func (m mockService) Login(ctx context.Context, email, password string) (string, error) { +func (mockService) Login(_ context.Context, email, password string) (string, error) { if email == "test@test.io" && password == "pass" { return "token-100", nil } return "", errors.Unauthorized("") } -func (m mockService) Register(ctx context.Context, email, password string) error { +func (mockService) Register(_ context.Context, email, password string) error { if email == "test@test.io" && password == "pass" { return nil } return errors.Unauthorized("") } -func (m mockService) Verify(ctx context.Context, id, expires string) error { +func (mockService) Verify(_ context.Context, _, _ string) error { return nil } diff --git a/internal/auth/repository.go b/internal/auth/repository.go index 0dfdb12..937c660 100644 --- a/internal/auth/repository.go +++ b/internal/auth/repository.go @@ -2,7 +2,6 @@ package auth import ( "context" - "fmt" "github.com/garaekz/goshort/internal/entity" "github.com/garaekz/goshort/pkg/dbcontext" @@ -71,7 +70,6 @@ func (r repository) Register(ctx context.Context, user entity.User) error { } func (r repository) CreateEmailVerification(ctx context.Context, validation entity.EmailVerification) error { - fmt.Printf("%+v", validation) return r.db.With(ctx).Model(&validation).Insert() } @@ -84,7 +82,7 @@ func (r repository) GetEmailVerification(ctx context.Context, userID, token stri return validation, nil } -func (r repository) VerifyEmail(ctx context.Context, validation VerifyRequest) error { +func (r repository) VerifyEmail(_ context.Context, validation VerifyRequest) error { err := r.db.DB().Transactional(func(tx *dbx.Tx) error { if _, err := tx.Update("users", dbx.Params{"email_verified": true}, dbx.HashExp{"id": validation.UserID}).Execute(); err != nil { return err diff --git a/internal/auth/repository_test.go b/internal/auth/repository_test.go index c766aa5..8ffdd3e 100644 --- a/internal/auth/repository_test.go +++ b/internal/auth/repository_test.go @@ -86,5 +86,4 @@ func TestRepository(t *testing.T) { }) assert.Nil(t, err) - } diff --git a/internal/auth/service.go b/internal/auth/service.go index 58ff9be..fbdf506 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -129,7 +129,7 @@ func (s service) authenticate(ctx context.Context, email, password string) Ident return nil } - if user.EmailVerified == false { + if !user.EmailVerified { logger.Infof("User not verified: Authentication failed") return nil } diff --git a/internal/auth/service_test.go b/internal/auth/service_test.go index b659eec..a0de75e 100644 --- a/internal/auth/service_test.go +++ b/internal/auth/service_test.go @@ -26,7 +26,7 @@ func Test_service_Authenticate(t *testing.T) { pass, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.MinCost) repo := &mockRepository{ items: []entity.User{ - {ID: "100", Email: "test@test.io", Password: string(pass), CreatedAt: time.Now(), UpdatedAt: time.Now(), IsActive: true}, + {ID: "100", Email: "test@test.io", Password: string(pass), CreatedAt: time.Now(), UpdatedAt: time.Now(), IsActive: true, EmailVerified: true}, }, keys: []struct { Key string @@ -44,12 +44,12 @@ func Test_service_Authenticate(t *testing.T) { assert.NotEmpty(t, token) } -func Test_service_authenticate(t *testing.T) { +func Test_service_authenticate_function(t *testing.T) { logger, _ := log.NewForTest() pass, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.MinCost) repo := &mockRepository{ items: []entity.User{ - {ID: "100", Email: "test@test.io", Password: string(pass), CreatedAt: time.Now(), UpdatedAt: time.Now(), IsActive: true}, + {ID: "100", Email: "test@test.io", Password: string(pass), CreatedAt: time.Now(), UpdatedAt: time.Now(), IsActive: true, EmailVerified: true}, }, keys: []struct { Key string @@ -89,7 +89,7 @@ func Test_service_GenerateJWT(t *testing.T) { } } -func (m mockRepository) GetUserByEmail(ctx context.Context, email string) (entity.User, error) { +func (m mockRepository) GetUserByEmail(_ context.Context, email string) (entity.User, error) { for _, item := range m.items { if item.Email == email { return item, nil @@ -98,7 +98,7 @@ func (m mockRepository) GetUserByEmail(ctx context.Context, email string) (entit return entity.User{}, sql.ErrNoRows } -func (m mockRepository) GetUserByAPIKey(ctx context.Context, apiKey string) (entity.User, error) { +func (m mockRepository) GetUserByAPIKey(_ context.Context, apiKey string) (entity.User, error) { var userID string for _, key := range m.keys { if key.UserID == apiKey { @@ -113,7 +113,7 @@ func (m mockRepository) GetUserByAPIKey(ctx context.Context, apiKey string) (ent return entity.User{}, sql.ErrNoRows } -func (m mockRepository) Register(ctx context.Context, user entity.User) error { +func (m mockRepository) Register(_ context.Context, user entity.User) error { if user.ID == "error" { return errors.Unauthorized("") } @@ -121,14 +121,14 @@ func (m mockRepository) Register(ctx context.Context, user entity.User) error { return nil } -func (m mockRepository) CreateEmailVerification(ctx context.Context, verification entity.EmailVerification) error { +func (mockRepository) CreateEmailVerification(_ context.Context, verification entity.EmailVerification) error { if verification.UserID == "duplicate" { return errors.BadRequest("The user you're trying to register already exists") } return nil } -func (m mockRepository) GetEmailVerification(ctx context.Context, userID, token string) (entity.EmailVerification, error) { +func (m mockRepository) GetEmailVerification(_ context.Context, userID, _ string) (entity.EmailVerification, error) { for _, item := range m.items { if item.ID == userID { return entity.EmailVerification{UserID: userID}, nil @@ -137,6 +137,6 @@ func (m mockRepository) GetEmailVerification(ctx context.Context, userID, token return entity.EmailVerification{}, sql.ErrNoRows } -func (m mockRepository) VerifyEmail(ctx context.Context, validation VerifyRequest) error { +func (mockRepository) VerifyEmail(_ context.Context, _ VerifyRequest) error { return nil } diff --git a/internal/config/config.go b/internal/config/config.go index 10e833d..98c1bdb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -70,7 +70,7 @@ func Load(file string, logger log.Logger) (*Config, error) { } // GetConfigFromDB returns an application configuration which is populated from the given database. -func (c *Config) GetConfigFromDB(db *dbcontext.DB, logger log.Logger) error { +func (c *Config) GetConfigFromDB(db *dbcontext.DB) error { var config []struct { Name string `db:"name"` Value string `db:"value"` @@ -82,13 +82,12 @@ func (c *Config) GetConfigFromDB(db *dbcontext.DB, logger log.Logger) error { } for _, cfg := range config { - switch cfg.Name { - case "default_api_keys_quantity": - val, err := strconv.Atoi(cfg.Value) + // TODO: change this to a switch statement when we have more config options + if cfg.Name == "default_api_keys_quantity" { + c.MaxAPIKeysPerUser, err = strconv.Atoi(cfg.Value) if err != nil { return err } - c.MaxAPIKeysPerUser = val } } diff --git a/internal/entity/emailverification.go b/internal/entity/emailverification.go index e62cb7f..45ad765 100644 --- a/internal/entity/emailverification.go +++ b/internal/entity/emailverification.go @@ -10,6 +10,6 @@ type EmailVerification struct { } // TableName represents the table name -func (v EmailVerification) TableName() string { +func (_ EmailVerification) TableName() string { return "email_verifications" } diff --git a/internal/entity/key.go b/internal/entity/key.go index adeb19a..9a4e098 100644 --- a/internal/entity/key.go +++ b/internal/entity/key.go @@ -14,6 +14,6 @@ type APIKey struct { } // TableName represents the table name -func (k APIKey) TableName() string { +func (APIKey) TableName() string { return "keys" } diff --git a/internal/entity/short.go b/internal/entity/short.go index 2c5cd9f..90d5b98 100644 --- a/internal/entity/short.go +++ b/internal/entity/short.go @@ -17,6 +17,6 @@ type Short struct { } // TableName represents the table name -func (s Short) TableName() string { +func (Short) TableName() string { return "shorts" } diff --git a/internal/entity/user.go b/internal/entity/user.go index 629f229..454094c 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -14,7 +14,7 @@ type User struct { } // TableName represents the table name -func (u User) TableName() string { +func (User) TableName() string { return "users" } diff --git a/internal/errors/middleware_test.go b/internal/errors/middleware_test.go index e69812a..b575d42 100644 --- a/internal/errors/middleware_test.go +++ b/internal/errors/middleware_test.go @@ -3,13 +3,14 @@ package errors import ( "database/sql" "fmt" + "net/http" + "net/http/httptest" + "testing" + "github.com/garaekz/goshort/pkg/log" routing "github.com/go-ozzo/ozzo-routing/v2" validation "github.com/go-ozzo/ozzo-validation/v4" "github.com/stretchr/testify/assert" - "net/http" - "net/http/httptest" - "testing" ) func TestHandler(t *testing.T) { @@ -80,14 +81,14 @@ func handlerOK(c *routing.Context) error { return c.Write("test") } -func handlerError(c *routing.Context) error { +func handlerError(_ *routing.Context) error { return fmt.Errorf("abc") } -func handlerHTTPError(c *routing.Context) error { +func handlerHTTPError(_ *routing.Context) error { return NotFound("") } -func handlerPanic(c *routing.Context) error { +func handlerPanic(_ *routing.Context) error { panic("xyz") } diff --git a/internal/my/api.go b/internal/my/api.go index a33aef7..21ede06 100644 --- a/internal/my/api.go +++ b/internal/my/api.go @@ -63,9 +63,9 @@ func (r resource) createMyShort(c *routing.Context) error { return errors.BadRequest("") } input.IP = realip.GetRealIP(c.Request) - short, err := r.shortService.Create(c.Request.Context(), input) + newShort, err := r.shortService.Create(c.Request.Context(), input) if err != nil { return err } - return c.WriteWithStatus(short, http.StatusCreated) + return c.WriteWithStatus(newShort, http.StatusCreated) } diff --git a/internal/my/service_test.go b/internal/my/service_test.go index d1990b9..f2693f4 100644 --- a/internal/my/service_test.go +++ b/internal/my/service_test.go @@ -38,7 +38,7 @@ type shortMockRepository struct { shorts []entity.Short } -func (m mockRepository) Get(ctx context.Context, id string) (entity.User, error) { +func (m mockRepository) Get(_ context.Context, id string) (entity.User, error) { for _, user := range m.users { if user.ID == id { return user, nil @@ -48,67 +48,67 @@ func (m mockRepository) Get(ctx context.Context, id string) (entity.User, error) return entity.User{}, sql.ErrNoRows } -func (m apiKeyMockRepository) Get(ctx context.Context, key string) (entity.APIKey, error) { +func (apiKeyMockRepository) Get(_ context.Context, _ string) (entity.APIKey, error) { return entity.APIKey{}, sql.ErrNoRows } -func (m apiKeyMockRepository) GetOwned(ctx context.Context, userID string) ([]apikey.APIKey, error) { +func (apiKeyMockRepository) GetOwned(_ context.Context, _ string) ([]apikey.APIKey, error) { return []apikey.APIKey{}, sql.ErrNoRows } -func (m apiKeyMockRepository) Count(ctx context.Context) (int, error) { +func (apiKeyMockRepository) Count(_ context.Context) (int, error) { return 0, nil } -func (m apiKeyMockRepository) CountByOwner(ctx context.Context, userID string) (int, error) { +func (apiKeyMockRepository) CountByOwner(_ context.Context, _ string) (int, error) { var count int return count, nil } -func (m *apiKeyMockRepository) Create(ctx context.Context, apiKey entity.APIKey) error { +func (apiKeyMockRepository) Create(_ context.Context, _ entity.APIKey) error { return nil } -func (m *apiKeyMockRepository) Update(ctx context.Context, apiKey entity.APIKey) error { +func (apiKeyMockRepository) Update(_ context.Context, _ entity.APIKey) error { return nil } -func (m *apiKeyMockRepository) Delete(ctx context.Context, key string) error { +func (apiKeyMockRepository) Delete(_ context.Context, _ string) error { return nil } -func (m shortMockRepository) Get(ctx context.Context, code string) (entity.Short, error) { +func (shortMockRepository) Get(_ context.Context, _ string) (entity.Short, error) { return entity.Short{}, sql.ErrNoRows } -func (m shortMockRepository) Count(ctx context.Context) (int, error) { +func (shortMockRepository) Count(_ context.Context) (int, error) { return 0, nil } -func (m shortMockRepository) Query(ctx context.Context, offset, limit int) ([]entity.Short, error) { +func (m shortMockRepository) Query(_ context.Context, _, _ int) ([]entity.Short, error) { return m.shorts, nil } -func (m *shortMockRepository) Create(ctx context.Context, short entity.Short) error { +func (shortMockRepository) Create(_ context.Context, _ entity.Short) error { return nil } -func (m *shortMockRepository) Update(ctx context.Context, short entity.Short) error { +func (shortMockRepository) Update(_ context.Context, _ entity.Short) error { return nil } -func (m *shortMockRepository) Delete(ctx context.Context, code string) error { +func (shortMockRepository) Delete(_ context.Context, _ string) error { return nil } -func (m *shortMockRepository) GenerateUniqueCode(ctx context.Context) (string, error) { +func (shortMockRepository) GenerateUniqueCode(_ context.Context) (string, error) { return "code", nil } -func (m *shortMockRepository) GetByOriginalURL(ctx context.Context, URL, userID string) (entity.Short, error) { +func (shortMockRepository) GetByOriginalURL(_ context.Context, _, _ string) (entity.Short, error) { return entity.Short{}, nil } -func (m *shortMockRepository) GetOwned(ctx context.Context, userID string) ([]entity.Short, error) { +func (m *shortMockRepository) GetOwned(_ context.Context, _ string) ([]entity.Short, error) { return m.shorts, nil } diff --git a/internal/short/api.go b/internal/short/api.go index f3f294f..e0fab7d 100644 --- a/internal/short/api.go +++ b/internal/short/api.go @@ -35,7 +35,10 @@ func (r resource) get(c *routing.Context) error { if err != nil { return err } - r.service.RegisterVisit(c.Request.Context(), short.Code) + if err = r.service.RegisterVisit(c.Request.Context(), short.Code); err != nil { + return err + } + return c.Write(short) } diff --git a/internal/short/service.go b/internal/short/service.go index c58ecfe..96c0bf4 100644 --- a/internal/short/service.go +++ b/internal/short/service.go @@ -24,7 +24,7 @@ type Service interface { Update(ctx context.Context, id string, input UpdateShortRequest) (Short, error) Delete(ctx context.Context, id string) (Short, error) GetCreated(ctx context.Context, id string) (Short, error) - RegisterVisit(ctx context.Context, code string) (Short, error) + RegisterVisit(ctx context.Context, code string) error } // Short represents the data about an short. @@ -218,17 +218,13 @@ func (s service) Query(ctx context.Context, offset, limit int) ([]Short, error) } // RegisterVisit updates the short visit count with the specified code. -func (s service) RegisterVisit(ctx context.Context, code string) (Short, error) { +func (s service) RegisterVisit(ctx context.Context, code string) error { short, err := s.repo.Get(ctx, code) if err != nil { - return Short{}, err + return err } short.Visits++ - - if err := s.repo.Update(ctx, short); err != nil { - return Short{}, err - } - return Short{ParseResponse(short)}, nil + return s.repo.Update(ctx, short) } // ParseResponse parses a Short entity into a secure response. diff --git a/internal/short/service_test.go b/internal/short/service_test.go index 0d3f370..a6033d5 100644 --- a/internal/short/service_test.go +++ b/internal/short/service_test.go @@ -130,7 +130,7 @@ type mockRepository struct { items []entity.Short } -func (m mockRepository) Get(ctx context.Context, code string) (entity.Short, error) { +func (m mockRepository) Get(_ context.Context, code string) (entity.Short, error) { for _, item := range m.items { if item.Code == code { return item, nil @@ -139,7 +139,7 @@ func (m mockRepository) Get(ctx context.Context, code string) (entity.Short, err return entity.Short{}, sql.ErrNoRows } -func (m mockRepository) GetOwned(ctx context.Context, userID string) ([]entity.Short, error) { +func (m mockRepository) GetOwned(_ context.Context, userID string) ([]entity.Short, error) { var shorts []entity.Short for _, item := range m.items { if item.UserID == userID { @@ -152,15 +152,15 @@ func (m mockRepository) GetOwned(ctx context.Context, userID string) ([]entity.S return shorts, nil } -func (m mockRepository) Count(ctx context.Context) (int, error) { +func (m mockRepository) Count(_ context.Context) (int, error) { return len(m.items), nil } -func (m mockRepository) Query(ctx context.Context, offset, limit int) ([]entity.Short, error) { +func (m mockRepository) Query(_ context.Context, _, _ int) ([]entity.Short, error) { return m.items, nil } -func (m *mockRepository) Create(ctx context.Context, short entity.Short) error { +func (m *mockRepository) Create(_ context.Context, short entity.Short) error { if short.Code == "error" { return errCRUD } @@ -168,7 +168,7 @@ func (m *mockRepository) Create(ctx context.Context, short entity.Short) error { return nil } -func (m *mockRepository) Update(ctx context.Context, short entity.Short) error { +func (m *mockRepository) Update(_ context.Context, short entity.Short) error { if short.Code == "error" { return errCRUD } @@ -181,7 +181,7 @@ func (m *mockRepository) Update(ctx context.Context, short entity.Short) error { return nil } -func (m *mockRepository) Delete(ctx context.Context, code string) error { +func (m *mockRepository) Delete(_ context.Context, code string) error { for i, item := range m.items { if item.Code == code { m.items[i] = m.items[len(m.items)-1] @@ -192,10 +192,10 @@ func (m *mockRepository) Delete(ctx context.Context, code string) error { return nil } -func (m *mockRepository) GenerateUniqueCode(ctx context.Context) (string, error) { +func (*mockRepository) GenerateUniqueCode(_ context.Context) (string, error) { return "code", nil } -func (m *mockRepository) GetByOriginalURL(ctx context.Context, URL, userID string) (entity.Short, error) { +func (*mockRepository) GetByOriginalURL(_ context.Context, _, _ string) (entity.Short, error) { return entity.Short{}, nil } diff --git a/pkg/dbcontext/db_test.go b/pkg/dbcontext/db_test.go index 6df72fb..06df7e1 100644 --- a/pkg/dbcontext/db_test.go +++ b/pkg/dbcontext/db_test.go @@ -138,5 +138,4 @@ func runCountQuery(t *testing.T, db *dbx.DB) int { err := db.NewQuery("SELECT COUNT(*) FROM dbcontexttest").Row(&count) assert.Nil(t, err) return count - } diff --git a/revive.toml b/revive.toml new file mode 100644 index 0000000..ae127be --- /dev/null +++ b/revive.toml @@ -0,0 +1,51 @@ +ignoreGeneratedHeader = false +severity = "warning" +confidence = 0.8 +errorCode = 1 +warningCode = 1 + +[rule.blank-imports] +[rule.context-as-argument] +[rule.context-keys-type] +[rule.dot-imports] +[rule.error-return] +[rule.error-strings] +[rule.error-naming] +[rule.exported] +[rule.if-return] +[rule.increment-decrement] +[rule.var-naming] +[rule.var-declaration] +[rule.range] +[rule.receiver-naming] +[rule.time-naming] +[rule.unexported-return] +[rule.indent-error-flow] +[rule.errorf] +[rule.duplicated-imports] +[rule.unused-parameter] +[rule.useless-break] +[rule.defer] +[rule.identical-branches] +[rule.unconditional-recursion] +[rule.early-return] +[rule.string-format] +[rule.string-of-int] +[rule.unused-receiver] +[rule.unhandled-error] +[rule.import-shadowing] +[rule.empty-lines] +[rule.waitgroup-by-value] +[rule.range-val-address] +[rule.range-val-in-closure] +[rule.redefines-builtin-id] +[rule.bool-literal-in-expr] +[rule.constant-logical-expr] +[rule.modifies-value-receiver] +[rule.unnecessary-stmt] +[rule.unreachable-code] +[rule.confusing-results] +[rule.modifies-parameter] +[rule.get-return] +[rule.confusing-naming] +[rule.superfluous-else] \ No newline at end of file