Skip to content

Commit

Permalink
Fix some lint warnings (heroiclabs#376)
Browse files Browse the repository at this point in the history
* Fix lint warnings

Fix warnings related to variable names, unnecessary nil var initialisation, unnecessary
else blocks after return statements and unary variable {inc|dec}rements.

* gofmt -s fixes
  • Loading branch information
sesposito authored Sep 19, 2019
1 parent 3f6a294 commit 8a46f28
Show file tree
Hide file tree
Showing 46 changed files with 468 additions and 491 deletions.
12 changes: 6 additions & 6 deletions cronexpr/cronexpr.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func Parse(cronLine string) (*Expression, error) {
if err != nil {
return nil, err
}
field += 1
field++
} else {
expr.secondList = []int{0}
}
Expand All @@ -100,35 +100,35 @@ func Parse(cronLine string) (*Expression, error) {
if err != nil {
return nil, err
}
field += 1
field++

// hour field
err = expr.hourFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
field++

// day of month field
err = expr.domFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
field++

// month field
err = expr.monthFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
field++

// day of week field
err = expr.dowFieldHandler(cron[indices[field][0]:indices[field][1]])
if err != nil {
return nil, err
}
field += 1
field++

// year field
if field < fieldCount {
Expand Down
4 changes: 2 additions & 2 deletions cronexpr/cronexpr_next.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,13 +277,13 @@ func workdayOfMonth(targetDom, lastDom time.Time) int {
dow := targetDom.Weekday()
if dow == time.Saturday {
if dom > 1 {
dom -= 1
dom--
} else {
dom += 2
}
} else if dow == time.Sunday {
if dom < lastDom.Day() {
dom += 1
dom++
} else {
dom -= 2
}
Expand Down
2 changes: 1 addition & 1 deletion cronexpr/cronexpr_parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ func toList(set map[int]bool) []int {
i := 0
for k := range set {
list[i] = k
i += 1
i++
}
sort.Ints(list)
return list
Expand Down
20 changes: 10 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,26 +211,26 @@ func main() {
}

func dbConnect(multiLogger *zap.Logger, config server.Config) (*sql.DB, string) {
rawUrl := fmt.Sprintf("postgresql://%s", config.GetDatabase().Addresses[0])
parsedUrl, err := url.Parse(rawUrl)
rawURL := fmt.Sprintf("postgresql://%s", config.GetDatabase().Addresses[0])
parsedURL, err := url.Parse(rawURL)
if err != nil {
multiLogger.Fatal("Bad database connection URL", zap.Error(err))
}
query := parsedUrl.Query()
query := parsedURL.Query()
if len(query.Get("sslmode")) == 0 {
query.Set("sslmode", "disable")
parsedUrl.RawQuery = query.Encode()
parsedURL.RawQuery = query.Encode()
}

if len(parsedUrl.User.Username()) < 1 {
parsedUrl.User = url.User("root")
if len(parsedURL.User.Username()) < 1 {
parsedURL.User = url.User("root")
}
if len(parsedUrl.Path) < 1 {
parsedUrl.Path = "/nakama"
if len(parsedURL.Path) < 1 {
parsedURL.Path = "/nakama"
}

multiLogger.Debug("Complete database connection URL", zap.String("raw_url", parsedUrl.String()))
db, err := sql.Open("pgx", parsedUrl.String())
multiLogger.Debug("Complete database connection URL", zap.String("raw_url", parsedURL.String()))
db, err := sql.Open("pgx", parsedURL.String())
if err != nil {
multiLogger.Fatal("Error connecting to database", zap.Error(err))
}
Expand Down
26 changes: 13 additions & 13 deletions migrate/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
"github.com/gobuffalo/packr"
"github.com/heroiclabs/nakama/v2/server"
"github.com/jackc/pgx"
_ "github.com/jackc/pgx/stdlib"
_ "github.com/jackc/pgx/stdlib" // Blank import to register SQL driver
"github.com/rubenv/sql-migrate"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -117,29 +117,29 @@ func Parse(args []string, tmpLogger *zap.Logger) {
ms.parseSubcommand(args[1:], tmpLogger)
logger := server.NewJSONLogger(os.Stdout, zapcore.InfoLevel, ms.loggerFormat)

rawUrl := fmt.Sprintf("postgresql://%s", ms.dbAddress)
parsedUrl, err := url.Parse(rawUrl)
rawURL := fmt.Sprintf("postgresql://%s", ms.dbAddress)
parsedURL, err := url.Parse(rawURL)
if err != nil {
logger.Fatal("Bad connection URL", zap.Error(err))
}
query := parsedUrl.Query()
query := parsedURL.Query()
if len(query.Get("sslmode")) == 0 {
query.Set("sslmode", "disable")
parsedUrl.RawQuery = query.Encode()
parsedURL.RawQuery = query.Encode()
}

if len(parsedUrl.User.Username()) < 1 {
parsedUrl.User = url.User("root")
if len(parsedURL.User.Username()) < 1 {
parsedURL.User = url.User("root")
}
dbname := "nakama"
if len(parsedUrl.Path) > 1 {
dbname = parsedUrl.Path[1:]
if len(parsedURL.Path) > 1 {
dbname = parsedURL.Path[1:]
}

logger.Info("Database connection", zap.String("dsn", ms.dbAddress))

parsedUrl.Path = ""
db, err := sql.Open("pgx", parsedUrl.String())
parsedURL.Path = ""
db, err := sql.Open("pgx", parsedURL.String())
if err != nil {
logger.Fatal("Failed to open database", zap.Error(err))
}
Expand All @@ -165,8 +165,8 @@ func Parse(args []string, tmpLogger *zap.Logger) {
_ = db.Close()

// Append dbname to data source name.
parsedUrl.Path = fmt.Sprintf("/%s", dbname)
db, err = sql.Open("pgx", parsedUrl.String())
parsedURL.Path = fmt.Sprintf("/%s", dbname)
db, err = sql.Open("pgx", parsedURL.String())
if err != nil {
logger.Fatal("Failed to open database", zap.Error(err))
}
Expand Down
4 changes: 2 additions & 2 deletions server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ func traceApiBefore(ctx context.Context, logger *zap.Logger, fullMethodName stri
err = fn(clientIP, clientPort)

span.End()
stats.Record(statsCtx, MetricsApiTimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsApiCount.M(1))
stats.Record(statsCtx, MetricsAPITimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsAPICount.M(1))

return err
}
Expand All @@ -543,5 +543,5 @@ func traceApiAfter(ctx context.Context, logger *zap.Logger, fullMethodName strin
fn(clientIP, clientPort)

span.End()
stats.Record(statsCtx, MetricsApiTimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsApiCount.M(1))
stats.Record(statsCtx, MetricsAPITimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsAPICount.M(1))
}
8 changes: 4 additions & 4 deletions server/api_leaderboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ func (s *ApiServer) ListLeaderboardRecords(ctx context.Context, in *api.ListLead
}

if len(in.GetOwnerIds()) != 0 {
for _, ownerId := range in.OwnerIds {
if _, err := uuid.FromString(ownerId); err != nil {
for _, ownerID := range in.OwnerIds {
if _, err := uuid.FromString(ownerID); err != nil {
return nil, status.Error(codes.InvalidArgument, "One or more owner IDs are invalid.")
}
}
Expand Down Expand Up @@ -252,7 +252,7 @@ func (s *ApiServer) ListLeaderboardRecordsAroundOwner(ctx context.Context, in *a
return nil, status.Error(codes.InvalidArgument, "Owner ID must be provided for a haystack query.")
}

ownerId, err := uuid.FromString(in.GetOwnerId())
ownerID, err := uuid.FromString(in.GetOwnerId())
if err != nil {
return nil, status.Error(codes.InvalidArgument, "Invalid owner ID provided.")
}
Expand All @@ -262,7 +262,7 @@ func (s *ApiServer) ListLeaderboardRecordsAroundOwner(ctx context.Context, in *a
overrideExpiry = in.Expiry.Value
}

records, err := LeaderboardRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetLeaderboardId(), ownerId, limit, overrideExpiry)
records, err := LeaderboardRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetLeaderboardId(), ownerID, limit, overrideExpiry)
if err == ErrLeaderboardNotFound {
return nil, status.Error(codes.NotFound, "Leaderboard not found.")
} else if err != nil {
Expand Down
16 changes: 8 additions & 8 deletions server/api_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,14 @@ func (s *ApiServer) LinkDevice(ctx context.Context, in *api.AccountDevice) (*emp
}

err = ExecuteInTx(ctx, tx, func() error {
var dbDeviceIdLinkedUser int64
err := tx.QueryRowContext(ctx, "SELECT COUNT(id) FROM user_device WHERE id = $1 AND user_id = $2 LIMIT 1", deviceID, userID).Scan(&dbDeviceIdLinkedUser)
var dbDeviceIDLinkedUser int64
err := tx.QueryRowContext(ctx, "SELECT COUNT(id) FROM user_device WHERE id = $1 AND user_id = $2 LIMIT 1", deviceID, userID).Scan(&dbDeviceIDLinkedUser)
if err != nil {
s.logger.Debug("Cannot link device ID.", zap.Error(err), zap.Any("input", in))
return err
}

if dbDeviceIdLinkedUser == 0 {
if dbDeviceIDLinkedUser == 0 {
_, err = tx.ExecContext(ctx, "INSERT INTO user_device (id, user_id) VALUES ($1, $2)", deviceID, userID)
if err != nil {
if e, ok := err.(pgx.PgError); ok && e.Code == dbErrorUniqueViolation {
Expand Down Expand Up @@ -449,11 +449,11 @@ func (s *ApiServer) LinkGoogle(ctx context.Context, in *api.AccountGoogle) (*emp
displayName = ""
}

avatarUrl := googleProfile.Picture
if len(avatarUrl) > 512 {
avatarURL := googleProfile.Picture
if len(avatarURL) > 512 {
// Ignore the url in case it is longer than db can store
s.logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarUrl))
avatarUrl = ""
s.logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarURL))
avatarURL = ""
}

res, err := s.db.ExecContext(ctx, `
Expand All @@ -465,7 +465,7 @@ AND (NOT EXISTS
FROM users
WHERE google_id = $2 AND NOT id = $1))`,
userID,
googleProfile.Sub, displayName, avatarUrl)
googleProfile.Sub, displayName, avatarURL)

if err != nil {
s.logger.Error("Could not link Google ID.", zap.Error(err), zap.Any("input", in))
Expand Down
16 changes: 8 additions & 8 deletions server/api_notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,17 @@ func (s *ApiServer) ListNotifications(ctx context.Context, in *api.ListNotificat
}

cursor := in.GetCacheableCursor()
var nc *notificationCacheableCursor = nil
var nc *notificationCacheableCursor
if cursor != "" {
nc = &notificationCacheableCursor{}
if cb, err := base64.RawURLEncoding.DecodeString(cursor); err != nil {
nc := &notificationCacheableCursor{}
cb, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
s.logger.Warn("Could not base64 decode notification cursor.", zap.String("cursor", cursor))
return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.")
} else {
if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(nc); err != nil {
s.logger.Warn("Could not decode notification cursor.", zap.String("cursor", cursor))
return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.")
}
}
if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(nc); err != nil {
s.logger.Warn("Could not decode notification cursor.", zap.String("cursor", cursor))
return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.")
}
}

Expand Down
28 changes: 14 additions & 14 deletions server/api_rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ var (
authTokenInvalidBytes = []byte(`{"error":"Auth token invalid","message":"Auth token invalid","code":16}`)
httpKeyInvalidBytes = []byte(`{"error":"HTTP key invalid","message":"HTTP key invalid","code":16}`)
noAuthBytes = []byte(`{"error":"Auth token or HTTP key required","message":"Auth token or HTTP key required","code":16}`)
rpcIdMustBeSetBytes = []byte(`{"error":"RPC ID must be set","message":"RPC ID must be set","code":3}`)
rpcIDMustBeSetBytes = []byte(`{"error":"RPC ID must be set","message":"RPC ID must be set","code":3}`)
rpcFunctionNotFoundBytes = []byte(`{"error":"RPC function not found","message":"RPC function not found","code":5}`)
internalServerErrorBytes = []byte(`{"error":"Internal Server Error","message":"Internal Server Error","code":13}`)
badJsonBytes = []byte(`{"error":"json: cannot unmarshal object into Go value of type string","message":"json: cannot unmarshal object into Go value of type string","code":3}`)
badJSONBytes = []byte(`{"error":"json: cannot unmarshal object into Go value of type string","message":"json: cannot unmarshal object into Go value of type string","code":3}`)
)

func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -84,18 +84,18 @@ func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) {
}

// Check the RPC function ID.
maybeId, ok := mux.Vars(r)["id"]
if !ok || maybeId == "" {
maybeID, ok := mux.Vars(r)["id"]
if !ok || maybeID == "" {
// Missing RPC function ID.
w.WriteHeader(http.StatusBadRequest)
w.Header().Set("content-type", "application/json")
_, err := w.Write(rpcIdMustBeSetBytes)
_, err := w.Write(rpcIDMustBeSetBytes)
if err != nil {
s.logger.Debug("Error writing response to client", zap.Error(err))
}
return
}
id := strings.ToLower(maybeId)
id := strings.ToLower(maybeID)

// Find the correct RPC function.
fn := s.runtime.Rpc(id)
Expand Down Expand Up @@ -136,7 +136,7 @@ func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) {
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Header().Set("content-type", "application/json")
_, err := w.Write(badJsonBytes)
_, err := w.Write(badJSONBytes)
if err != nil {
s.logger.Debug("Error writing response to client", zap.Error(err))
}
Expand Down Expand Up @@ -210,14 +210,14 @@ func (s *ApiServer) RpcFunc(ctx context.Context, in *api.Rpc) (*api.Rpc, error)
}

queryParams := make(map[string][]string, 0)
if md, ok := metadata.FromIncomingContext(ctx); !ok {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Internal, "RPC function could not get incoming context")
} else {
for k, vs := range md {
// Only process the keys representing custom query parameters.
if strings.HasPrefix(k, "q_") {
queryParams[k[2:]] = vs
}
}
for k, vs := range md {
// Only process the keys representing custom query parameters.
if strings.HasPrefix(k, "q_") {
queryParams[k[2:]] = vs
}
}

Expand Down
Loading

0 comments on commit 8a46f28

Please sign in to comment.