diff --git a/core/bloom/bloom.go b/core/bloom/bloom.go index f6d437ad..6118fce0 100644 --- a/core/bloom/bloom.go +++ b/core/bloom/bloom.go @@ -127,11 +127,12 @@ func (r *redisBitSet) check(offsets []uint) (bool, error) { return false, err } - if exists, ok := resp.(int64); !ok { + exists, ok := resp.(int64) + if !ok { return false, nil - } else { - return exists == 1, nil } + + return exists == 1, nil } func (r *redisBitSet) del() error { @@ -152,7 +153,7 @@ func (r *redisBitSet) set(offsets []uint) error { _, err = r.store.Eval(setScript, []string{r.key}, args) if err == redis.Nil { return nil - } else { - return err } + + return err } diff --git a/core/breaker/googlebreaker.go b/core/breaker/googlebreaker.go index 6e09b5e4..48795b8e 100644 --- a/core/breaker/googlebreaker.go +++ b/core/breaker/googlebreaker.go @@ -64,9 +64,9 @@ func (b *googleBreaker) doReq(req func() error, fallback func(err error) error, if err := b.accept(); err != nil { if fallback != nil { return fallback(err) - } else { - return err } + + return err } defer func() { diff --git a/core/codec/aesecb.go b/core/codec/aesecb.go index c597ba6c..205233b2 100644 --- a/core/codec/aesecb.go +++ b/core/codec/aesecb.go @@ -150,11 +150,12 @@ func getKeyBytes(key string) ([]byte, error) { return []byte(key), nil } - if keyBytes, err := base64.StdEncoding.DecodeString(key); err != nil { + keyBytes, err := base64.StdEncoding.DecodeString(key) + if err != nil { return nil, err - } else { - return keyBytes, nil } + + return keyBytes, nil } func pkcs5Padding(ciphertext []byte, blockSize int) []byte { diff --git a/core/collection/cache.go b/core/collection/cache.go index 368e79a3..bcbfc30e 100644 --- a/core/collection/cache.go +++ b/core/collection/cache.go @@ -136,11 +136,10 @@ func (c *Cache) Take(key string, fetch func() (interface{}, error)) (interface{} if fresh { c.stats.IncrementMiss() return val, nil - } else { - // got the result from previous ongoing query - c.stats.IncrementHit() } + // got the result from previous ongoing query + c.stats.IncrementHit() return val, nil } diff --git a/core/collection/rollingwindow.go b/core/collection/rollingwindow.go index 2795195d..bfd9027e 100644 --- a/core/collection/rollingwindow.go +++ b/core/collection/rollingwindow.go @@ -73,9 +73,9 @@ func (rw *RollingWindow) span() int { offset := int(timex.Since(rw.lastTime) / rw.interval) if 0 <= offset && offset < rw.size { return offset - } else { - return rw.size } + + return rw.size } func (rw *RollingWindow) updateOffset() { diff --git a/core/collection/safemap.go b/core/collection/safemap.go index a8547a5f..62d161fd 100644 --- a/core/collection/safemap.go +++ b/core/collection/safemap.go @@ -59,10 +59,10 @@ func (m *SafeMap) Get(key interface{}) (interface{}, bool) { if val, ok := m.dirtyOld[key]; ok { return val, true - } else { - val, ok := m.dirtyNew[key] - return val, ok } + + val, ok := m.dirtyNew[key] + return val, ok } func (m *SafeMap) Set(key, value interface{}) { diff --git a/core/conf/config.go b/core/conf/config.go index 29f180bf..30c31513 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -34,9 +34,9 @@ func LoadConfig(file string, v interface{}, opts ...Option) error { if opt.env { return loader([]byte(os.ExpandEnv(string(content))), v) - } else { - return loader(content, v) } + + return loader(content, v) } func LoadConfigFromJsonBytes(content []byte, v interface{}) error { diff --git a/core/conf/properties.go b/core/conf/properties.go index 268961f6..b344039a 100644 --- a/core/conf/properties.go +++ b/core/conf/properties.go @@ -31,7 +31,7 @@ type mapBasedProperties struct { lock sync.RWMutex } -// Loads the properties into a properties configuration instance. +// LoadProperties loads the properties into a properties configuration instance. // Returns an error that indicates if there was a problem loading the configuration. func LoadProperties(filename string, opts ...Option) (Properties, error) { lines, err := iox.ReadTextLines(filename, iox.WithoutBlank(), iox.OmitWithPrefix("#")) @@ -97,7 +97,7 @@ func (config *mapBasedProperties) SetInt(key string, value int) { config.lock.Unlock() } -// Dumps the configuration internal map into a string. +// ToString dumps the configuration internal map into a string. func (config *mapBasedProperties) ToString() string { config.lock.RLock() ret := fmt.Sprintf("%s", config.properties) @@ -106,12 +106,12 @@ func (config *mapBasedProperties) ToString() string { return ret } -// Returns the error message. +// Error returns the error message. func (configError *PropertyError) Error() string { return configError.message } -// Builds a new properties configuration structure +// NewProperties builds a new properties configuration structure. func NewProperties() Properties { return &mapBasedProperties{ properties: make(map[string]string), diff --git a/core/discov/subscriber.go b/core/discov/subscriber.go index b96c2617..94c81bfc 100644 --- a/core/discov/subscriber.go +++ b/core/discov/subscriber.go @@ -100,9 +100,9 @@ func (c *container) addKv(key, value string) ([]string, bool) { if early { return previous, true - } else { - return nil, false } + + return nil, false } func (c *container) addListener(listener func()) { diff --git a/core/executors/periodicalexecutor.go b/core/executors/periodicalexecutor.go index 61319fc2..4e7be6d9 100644 --- a/core/executors/periodicalexecutor.go +++ b/core/executors/periodicalexecutor.go @@ -16,7 +16,7 @@ import ( const idleRound = 10 type ( - // A type that satisfies executors.TaskContainer can be used as the underlying + // TaskContainer interface defines a type that can be used as the underlying // container that used to do periodical executions. TaskContainer interface { // AddTask adds the task into the container. diff --git a/core/fx/fn.go b/core/fx/fn.go index cc7c722e..4e560e52 100644 --- a/core/fx/fn.go +++ b/core/fx/fn.go @@ -300,9 +300,9 @@ func (p Stream) Walk(fn WalkFunc, opts ...Option) Stream { option := buildOptions(opts...) if option.unlimitedWorkers { return p.walkUnlimited(fn, option) - } else { - return p.walkLimited(fn, option) } + + return p.walkLimited(fn, option) } func (p Stream) walkLimited(fn WalkFunc, option *rxOptions) Stream { diff --git a/core/jsontype/time.go b/core/jsontype/time.go index d55ec162..8d38c6d7 100644 --- a/core/jsontype/time.go +++ b/core/jsontype/time.go @@ -19,10 +19,10 @@ func (mt *MilliTime) UnmarshalJSON(data []byte) error { var milli int64 if err := json.Unmarshal(data, &milli); err != nil { return err - } else { - mt.Time = time.Unix(0, milli*int64(time.Millisecond)) - return nil } + + mt.Time = time.Unix(0, milli*int64(time.Millisecond)) + return nil } func (mt MilliTime) GetBSON() (interface{}, error) { diff --git a/core/limit/periodlimit.go b/core/limit/periodlimit.go index e4e827e7..92b4d110 100644 --- a/core/limit/periodlimit.go +++ b/core/limit/periodlimit.go @@ -97,9 +97,9 @@ func (h *PeriodLimit) calcExpireSeconds() int { if h.align { unix := time.Now().Unix() + zoneDiff return h.period - int(unix%int64(h.period)) - } else { - return h.period } + + return h.period } func Align() LimitOption { diff --git a/core/logx/rotatelogger.go b/core/logx/rotatelogger.go index 181bdab1..ec2261a6 100644 --- a/core/logx/rotatelogger.go +++ b/core/logx/rotatelogger.go @@ -163,9 +163,9 @@ func (l *RotateLogger) Write(data []byte) (int, error) { func (l *RotateLogger) getBackupFilename() string { if len(l.backup) == 0 { return l.rule.BackupFileName() - } else { - return l.backup } + + return l.backup } func (l *RotateLogger) init() error { diff --git a/core/mapping/fieldoptions.go b/core/mapping/fieldoptions.go index 075753db..37cc13e4 100644 --- a/core/mapping/fieldoptions.go +++ b/core/mapping/fieldoptions.go @@ -35,9 +35,9 @@ func (o *fieldOptionsWithContext) fromString() bool { func (o *fieldOptionsWithContext) getDefault() (string, bool) { if o == nil { return "", false - } else { - return o.Default, len(o.Default) > 0 } + + return o.Default, len(o.Default) > 0 } func (o *fieldOptionsWithContext) optional() bool { @@ -55,9 +55,9 @@ func (o *fieldOptionsWithContext) options() []string { func (o *fieldOptions) optionalDep() string { if o == nil { return "" - } else { - return o.OptionalDep } + + return o.OptionalDep } func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) ( @@ -77,29 +77,29 @@ func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName strin _, selfOn := m.Value(key) if baseOn == selfOn { return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName) - } else { - optional = baseOn } + + optional = baseOn } else { _, baseOn := m.Value(dep) _, selfOn := m.Value(key) if baseOn != selfOn { return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q", dep, key, fullName) - } else { - optional = !baseOn } + + optional = !baseOn } } if o.fieldOptionsWithContext.Optional == optional { return &o.fieldOptionsWithContext, nil - } else { - return &fieldOptionsWithContext{ - FromString: o.FromString, - Optional: optional, - Options: o.Options, - Default: o.Default, - }, nil } + + return &fieldOptionsWithContext{ + FromString: o.FromString, + Optional: optional, + Options: o.Options, + Default: o.Default, + }, nil } diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 409be72b..3b068a92 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -114,9 +114,9 @@ func (u *Unmarshaler) processAnonymousField(field reflect.StructField, value ref if options.optional() { return u.processAnonymousFieldOptional(field, value, key, m, fullName) - } else { - return u.processAnonymousFieldRequired(field, value, m, fullName) } + + return u.processAnonymousFieldRequired(field, value, m, fullName) } func (u *Unmarshaler) processAnonymousFieldOptional(field reflect.StructField, value reflect.Value, @@ -184,9 +184,9 @@ func (u *Unmarshaler) processField(field reflect.StructField, value reflect.Valu if field.Anonymous { return u.processAnonymousField(field, value, m, fullName) - } else { - return u.processNamedField(field, value, m, fullName) } + + return u.processNamedField(field, value, m, fullName) } func (u *Unmarshaler) processFieldNotFromString(field reflect.StructField, value reflect.Value, @@ -319,9 +319,9 @@ func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect mapValue, hasValue := getValue(m, key) if hasValue { return u.processNamedFieldWithValue(field, value, mapValue, key, opts, fullName) - } else { - return u.processNamedFieldWithoutValue(field, value, opts, fullName) } + + return u.processNamedFieldWithoutValue(field, value, opts, fullName) } func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, value reflect.Value, @@ -329,9 +329,9 @@ func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, valu if mapValue == nil { if opts.optional() { return nil - } else { - return fmt.Errorf("field %s mustn't be nil", key) } + + return fmt.Errorf("field %s mustn't be nil", key) } maybeNewValue(field, value) diff --git a/core/mapping/utils.go b/core/mapping/utils.go index 64d0d3d4..0ac03167 100644 --- a/core/mapping/utils.go +++ b/core/mapping/utils.go @@ -124,23 +124,26 @@ func convertType(kind reflect.Kind, str string) (interface{}, error) { case reflect.Bool: return str == "1" || strings.ToLower(str) == "true", nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if intValue, err := strconv.ParseInt(str, 10, 64); err != nil { + intValue, err := strconv.ParseInt(str, 10, 64) + if err != nil { return 0, fmt.Errorf("the value %q cannot parsed as int", str) - } else { - return intValue, nil } + + return intValue, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if uintValue, err := strconv.ParseUint(str, 10, 64); err != nil { + uintValue, err := strconv.ParseUint(str, 10, 64) + if err != nil { return 0, fmt.Errorf("the value %q cannot parsed as uint", str) - } else { - return uintValue, nil } + + return uintValue, nil case reflect.Float32, reflect.Float64: - if floatValue, err := strconv.ParseFloat(str, 64); err != nil { + floatValue, err := strconv.ParseFloat(str, 64) + if err != nil { return 0, fmt.Errorf("the value %q cannot parsed as float", str) - } else { - return floatValue, nil } + + return floatValue, nil case reflect.String: return str, nil default: @@ -180,26 +183,28 @@ func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fie segs := strings.Split(option, equalToken) if len(segs) != 2 { return "", nil, fmt.Errorf("field %s has wrong options", field.Name) - } else { - fieldOpts.Options = strings.Split(segs[1], optionSeparator) } + + fieldOpts.Options = strings.Split(segs[1], optionSeparator) case strings.HasPrefix(option, defaultOption): segs := strings.Split(option, equalToken) if len(segs) != 2 { return "", nil, fmt.Errorf("field %s has wrong default option", field.Name) - } else { - fieldOpts.Default = strings.TrimSpace(segs[1]) } + + fieldOpts.Default = strings.TrimSpace(segs[1]) case strings.HasPrefix(option, rangeOption): segs := strings.Split(option, equalToken) if len(segs) != 2 { return "", nil, fmt.Errorf("field %s has wrong range", field.Name) } - if nr, err := parseNumberRange(segs[1]); err != nil { + + nr, err := parseNumberRange(segs[1]) + if err != nil { return "", nil, err - } else { - fieldOpts.Range = nr } + + fieldOpts.Range = nr } } diff --git a/core/mapping/yamlunmarshaler.go b/core/mapping/yamlunmarshaler.go index 6452d41b..c7f6947f 100644 --- a/core/mapping/yamlunmarshaler.go +++ b/core/mapping/yamlunmarshaler.go @@ -34,9 +34,9 @@ func unmarshalYamlBytes(content []byte, v interface{}, unmarshaler *Unmarshaler) if m, ok := o.(map[string]interface{}); ok { return unmarshaler.Unmarshal(m, v) - } else { - return ErrUnsupportedType } + + return ErrUnsupportedType } func unmarshalYamlReader(reader io.Reader, v interface{}, unmarshaler *Unmarshaler) error { diff --git a/core/mathx/int.go b/core/mathx/int.go index 58499618..d2fb4274 100644 --- a/core/mathx/int.go +++ b/core/mathx/int.go @@ -3,15 +3,15 @@ package mathx func MaxInt(a, b int) int { if a > b { return a - } else { - return b } + + return b } func MinInt(a, b int) int { if a < b { return a - } else { - return b } + + return b } diff --git a/core/proc/profile.go b/core/proc/profile.go index a1483e71..387406de 100644 --- a/core/proc/profile.go +++ b/core/proc/profile.go @@ -161,7 +161,7 @@ func (p *Profile) Stop() { atomic.StoreUint32(&started, 0) } -// Start starts a new profiling session. +// StartProfile starts a new profiling session. // The caller should call the Stop method on the value returned // to cleanly stop profiling. func StartProfile() Stopper { diff --git a/core/prof/profilecenter.go b/core/prof/profilecenter.go index 84c380f7..81ee704c 100644 --- a/core/prof/profilecenter.go +++ b/core/prof/profilecenter.go @@ -83,9 +83,9 @@ func generateReport() string { calcFn := func(total, count int64) string { if count == 0 { return "-" - } else { - return (time.Duration(total) / time.Duration(count)).String() } + + return (time.Duration(total) / time.Duration(count)).String() } func() { diff --git a/core/queue/queue_test.go b/core/queue/queue_test.go index 32279094..41ca7480 100644 --- a/core/queue/queue_test.go +++ b/core/queue/queue_test.go @@ -78,10 +78,10 @@ func (p *mockedProducer) Produce() (string, bool) { if atomic.AddInt32(&p.count, 1) <= p.total { p.wait.Done() return "item", true - } else { - time.Sleep(time.Second) - return "", false } + + time.Sleep(time.Second) + return "", false } type mockedListener struct { diff --git a/core/search/tree.go b/core/search/tree.go index 0163b37d..0bcb3322 100644 --- a/core/search/tree.go +++ b/core/search/tree.go @@ -114,9 +114,9 @@ func (t *Tree) next(n *node, route string, result *Result) bool { func (nd *node) getChildren(route string) map[string]*node { if len(route) > 0 && route[0] == colon { return nd.children[1] - } else { - return nd.children[0] } + + return nd.children[0] } func add(nd *node, route string, item interface{}) error { @@ -140,9 +140,9 @@ func add(nd *node, route string, item interface{}) error { if child, ok := children[token]; ok { if child != nil { return add(child, route[i+1:], item) - } else { - return ErrInvalidState } + + return ErrInvalidState } else { child := newNode(nil) children[token] = child diff --git a/core/service/servicegroup.go b/core/service/servicegroup.go index 25ee8a75..fff4ec17 100644 --- a/core/service/servicegroup.go +++ b/core/service/servicegroup.go @@ -38,6 +38,7 @@ func (sg *ServiceGroup) Add(service Service) { sg.services = append(sg.services, service) } +// Start starts the ServiceGroup. // There should not be any logic code after calling this method, because this method is a blocking one. // Also, quitting this method will close the logx output. func (sg *ServiceGroup) Start() { diff --git a/core/stat/internal/cgroup_linux.go b/core/stat/internal/cgroup_linux.go index 28bb63db..f7de44a0 100644 --- a/core/stat/internal/cgroup_linux.go +++ b/core/stat/internal/cgroup_linux.go @@ -110,16 +110,16 @@ func parseUint(s string) (uint64, error) { if err != nil { if err.(*strconv.NumError).Err == strconv.ErrRange { return 0, nil - } else { - return 0, fmt.Errorf("cgroup: bad int format: %s", s) - } - } else { - if v < 0 { - return 0, nil - } else { - return uint64(v), nil } + + return 0, fmt.Errorf("cgroup: bad int format: %s", s) + } + + if v < 0 { + return 0, nil } + + return uint64(v), nil } func parseUints(val string) ([]uint64, error) { diff --git a/core/stat/metrics.go b/core/stat/metrics.go index d848d02d..d8981e39 100644 --- a/core/stat/metrics.go +++ b/core/stat/metrics.go @@ -185,9 +185,9 @@ func getTopDuration(tasks []Task) float32 { top := topK(tasks, 1) if len(top) < 1 { return 0 - } else { - return float32(top[0].Duration) / float32(time.Millisecond) } + + return float32(top[0].Duration) / float32(time.Millisecond) } func log(report *StatReport) { diff --git a/core/stores/cache/cachenode.go b/core/stores/cache/cachenode.go index e66a35d9..213a7c92 100644 --- a/core/stores/cache/cachenode.go +++ b/core/stores/cache/cachenode.go @@ -75,11 +75,12 @@ func (c cacheNode) DelCache(keys ...string) error { // GetCache gets the cache with key and fills into v. func (c cacheNode) GetCache(key string, v interface{}) error { - if err := c.doGetCache(key, v); err == errPlaceholder { + err := c.doGetCache(key, v) + if err == errPlaceholder { return c.errNotFound - } else { - return err } + + return err } // IsNotFound checks if the given error is the defined errNotFound. diff --git a/core/stores/clickhouse/clickhouse.go b/core/stores/clickhouse/clickhouse.go index 540620a8..a78a0477 100644 --- a/core/stores/clickhouse/clickhouse.go +++ b/core/stores/clickhouse/clickhouse.go @@ -1,6 +1,7 @@ package clickhouse import ( + // imports the driver. _ "github.com/ClickHouse/clickhouse-go" "github.com/tal-tech/go-zero/core/stores/sqlx" ) diff --git a/core/stores/kv/store.go b/core/stores/kv/store.go index 927867c5..bf835848 100644 --- a/core/stores/kv/store.go +++ b/core/stores/kv/store.go @@ -655,9 +655,10 @@ func (cs clusterStore) Zscore(key string, value string) (int64, error) { } func (cs clusterStore) getRedis(key string) (*redis.Redis, error) { - if val, ok := cs.dispatcher.Get(key); !ok { + val, ok := cs.dispatcher.Get(key) + if !ok { return nil, ErrNoRedisNode - } else { - return val.(*redis.Redis), nil } + + return val.(*redis.Redis), nil } diff --git a/core/stores/mongo/sessionmanager.go b/core/stores/mongo/sessionmanager.go index a86c6d91..f262e321 100644 --- a/core/stores/mongo/sessionmanager.go +++ b/core/stores/mongo/sessionmanager.go @@ -66,7 +66,7 @@ func (cs *concurrentSession) takeSession(opts ...Option) (*mgo.Session, error) { if err := cs.limit.Borrow(o.timeout); err != nil { return nil, err - } else { - return cs.Copy(), nil } + + return cs.Copy(), nil } diff --git a/core/stores/postgres/postgresql.go b/core/stores/postgres/postgresql.go index 77800ff2..550c7367 100644 --- a/core/stores/postgres/postgresql.go +++ b/core/stores/postgres/postgresql.go @@ -1,6 +1,7 @@ package postgres import ( + // imports the driver. _ "github.com/lib/pq" "github.com/tal-tech/go-zero/core/stores/sqlx" ) diff --git a/core/stores/redis/redis.go b/core/stores/redis/redis.go index 573e5e2b..a58e61d9 100644 --- a/core/stores/redis/redis.go +++ b/core/stores/redis/redis.go @@ -72,7 +72,7 @@ func NewRedis(redisAddr, redisType string, redisPass ...string) *Redis { } } -// Use passed in redis connection to execute blocking queries +// Blpop uses passed in redis connection to execute blocking queries. // Doesn't benefit from pooling redis connections of blocking queries func (s *Redis) Blpop(redisNode RedisNode, key string) (string, error) { if redisNode == nil { @@ -1093,15 +1093,16 @@ func (s *Redis) Zadd(key string, score int64, value string) (val bool, err error return err } - if v, err := conn.ZAdd(key, red.Z{ + v, err := conn.ZAdd(key, red.Z{ Score: float64(score), Member: value, - }).Result(); err != nil { + }).Result() + if err != nil { return err - } else { - val = v == 1 - return nil } + + val = v == 1 + return nil }, acceptable) return @@ -1339,15 +1340,16 @@ func (s *Redis) ZrangebyscoreWithScores(key string, start, stop int64) (val []Pa return err } - if v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{ + v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{ Min: strconv.FormatInt(start, 10), Max: strconv.FormatInt(stop, 10), - }).Result(); err != nil { + }).Result() + if err != nil { return err - } else { - val = toPairs(v) - return nil } + + val = toPairs(v) + return nil }, acceptable) return @@ -1365,17 +1367,18 @@ func (s *Redis) ZrangebyscoreWithScoresAndLimit(key string, start, stop int64, p return err } - if v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{ + v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{ Min: strconv.FormatInt(start, 10), Max: strconv.FormatInt(stop, 10), Offset: int64(page * size), Count: int64(size), - }).Result(); err != nil { + }).Result() + if err != nil { return err - } else { - val = toPairs(v) - return nil } + + val = toPairs(v) + return nil }, acceptable) return @@ -1402,15 +1405,16 @@ func (s *Redis) ZrevrangebyscoreWithScores(key string, start, stop int64) (val [ return err } - if v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{ + v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{ Min: strconv.FormatInt(start, 10), Max: strconv.FormatInt(stop, 10), - }).Result(); err != nil { + }).Result() + if err != nil { return err - } else { - val = toPairs(v) - return nil } + + val = toPairs(v) + return nil }, acceptable) return @@ -1428,17 +1432,18 @@ func (s *Redis) ZrevrangebyscoreWithScoresAndLimit(key string, start, stop int64 return err } - if v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{ + v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{ Min: strconv.FormatInt(start, 10), Max: strconv.FormatInt(stop, 10), Offset: int64(page * size), Count: int64(size), - }).Result(); err != nil { + }).Result() + if err != nil { return err - } else { - val = toPairs(v) - return nil } + + val = toPairs(v) + return nil }, acceptable) return diff --git a/core/stores/redis/redislock.go b/core/stores/redis/redislock.go index 17db7055..bb059e79 100644 --- a/core/stores/redis/redislock.go +++ b/core/stores/redis/redislock.go @@ -63,10 +63,10 @@ func (rl *RedisLock) Acquire() (bool, error) { reply, ok := resp.(string) if ok && reply == "OK" { return true, nil - } else { - logx.Errorf("Unknown reply when acquiring lock for %s: %v", rl.key, resp) - return false, nil } + + logx.Errorf("Unknown reply when acquiring lock for %s: %v", rl.key, resp) + return false, nil } func (rl *RedisLock) Release() (bool, error) { @@ -75,11 +75,12 @@ func (rl *RedisLock) Release() (bool, error) { return false, err } - if reply, ok := resp.(int64); !ok { + reply, ok := resp.(int64) + if !ok { return false, nil - } else { - return reply == 1, nil } + + return reply == 1, nil } func (rl *RedisLock) SetExpire(seconds int) { diff --git a/core/stores/sqlx/orm.go b/core/stores/sqlx/orm.go index d8a3127c..2f17fe4f 100644 --- a/core/stores/sqlx/orm.go +++ b/core/stores/sqlx/orm.go @@ -107,10 +107,10 @@ func parseTagName(field reflect.StructField) string { key := field.Tag.Get(tagName) if len(key) == 0 { return "" - } else { - options := strings.Split(key, ",") - return options[0] } + + options := strings.Split(key, ",") + return options[0] } func unmarshalRow(v interface{}, scanner rowsScanner, strict bool) error { @@ -136,19 +136,21 @@ func unmarshalRow(v interface{}, scanner rowsScanner, strict bool) error { reflect.String: if rve.CanSet() { return scanner.Scan(v) - } else { - return ErrNotSettable } + + return ErrNotSettable case reflect.Struct: columns, err := scanner.Columns() if err != nil { return err } - if values, err := mapStructFieldsIntoSlice(rve, columns, strict); err != nil { + + values, err := mapStructFieldsIntoSlice(rve, columns, strict) + if err != nil { return err - } else { - return scanner.Scan(values...) } + + return scanner.Scan(values...) default: return ErrUnsupportedValueType } @@ -178,10 +180,10 @@ func unmarshalRows(v interface{}, scanner rowsScanner, strict bool) error { if rve.CanSet() { if err := scanner.Scan(value); err != nil { return err - } else { - appendFn(reflect.ValueOf(value)) - return nil } + + appendFn(reflect.ValueOf(value)) + return nil } return ErrNotSettable } @@ -207,14 +209,15 @@ func unmarshalRows(v interface{}, scanner rowsScanner, strict bool) error { for scanner.Next() { value := reflect.New(base) - if values, err := mapStructFieldsIntoSlice(value, columns, strict); err != nil { + values, err := mapStructFieldsIntoSlice(value, columns, strict) + if err != nil { + return err + } + + if err := scanner.Scan(values...); err != nil { return err } else { - if err := scanner.Scan(values...); err != nil { - return err - } else { - appendFn(value) - } + appendFn(value) } } default: diff --git a/core/stores/sqlx/sqlconn.go b/core/stores/sqlx/sqlconn.go index 4c0acbd3..c85a950b 100644 --- a/core/stores/sqlx/sqlconn.go +++ b/core/stores/sqlx/sqlconn.go @@ -101,14 +101,15 @@ func (db *commonSqlConn) Prepare(query string) (stmt StmtSession, err error) { return err } - if st, err := conn.Prepare(query); err != nil { + st, err := conn.Prepare(query) + if err != nil { return err - } else { - stmt = statement{ - stmt: st, - } - return nil } + + stmt = statement{ + stmt: st, + } + return nil }, db.acceptable) return @@ -148,9 +149,9 @@ func (db *commonSqlConn) acceptable(err error) bool { ok := err == nil || err == sql.ErrNoRows || err == sql.ErrTxDone if db.accept == nil { return ok - } else { - return ok || db.accept(err) } + + return ok || db.accept(err) } func (db *commonSqlConn) queryRows(scanner func(*sql.Rows) error, q string, args ...interface{}) error { diff --git a/core/stores/sqlx/tx.go b/core/stores/sqlx/tx.go index 4fe231d0..2fb71f88 100644 --- a/core/stores/sqlx/tx.go +++ b/core/stores/sqlx/tx.go @@ -24,13 +24,14 @@ func (t txSession) Exec(q string, args ...interface{}) (sql.Result, error) { } func (t txSession) Prepare(q string) (StmtSession, error) { - if stmt, err := t.Tx.Prepare(q); err != nil { + stmt, err := t.Tx.Prepare(q) + if err != nil { return nil, err - } else { - return statement{ - stmt: stmt, - }, nil } + + return statement{ + stmt: stmt, + }, nil } func (t txSession) QueryRow(v interface{}, q string, args ...interface{}) error { @@ -58,13 +59,14 @@ func (t txSession) QueryRowsPartial(v interface{}, q string, args ...interface{} } func begin(db *sql.DB) (trans, error) { - if tx, err := db.Begin(); err != nil { + tx, err := db.Begin() + if err != nil { return nil, err - } else { - return txSession{ - Tx: tx, - }, nil } + + return txSession{ + Tx: tx, + }, nil } func transact(db *commonSqlConn, b beginnable, fn func(Session) error) (err error) { @@ -83,6 +85,7 @@ func transactOnConn(conn *sql.DB, b beginnable, fn func(Session) error) (err err if err != nil { return } + defer func() { if p := recover(); p != nil { if e := tx.Rollback(); e != nil { diff --git a/core/stringx/strings.go b/core/stringx/strings.go index 11a6c732..d28a71c8 100644 --- a/core/stringx/strings.go +++ b/core/stringx/strings.go @@ -96,9 +96,9 @@ func Substr(str string, start int, stop int) (string, error) { func TakeOne(valid, or string) string { if len(valid) > 0 { return valid - } else { - return or } + + return or } func TakeWithPriority(fns ...func() string) string { diff --git a/core/syncx/immutableresource.go b/core/syncx/immutableresource.go index 1f9a076a..50339784 100644 --- a/core/syncx/immutableresource.go +++ b/core/syncx/immutableresource.go @@ -69,7 +69,8 @@ func (ir *ImmutableResource) maybeRefresh(execute func()) { } } -// Set interval to 0 to enforce refresh every time if not succeeded. default is time.Second. +// WithRefreshIntervalOnFailure sets refresh interval on failure. +// Set interval to 0 to enforce refresh every time if not succeeded, default is time.Second. func WithRefreshIntervalOnFailure(interval time.Duration) ImmutableResourceOption { return func(resource *ImmutableResource) { resource.refreshInterval = interval diff --git a/core/threading/routinegroup.go b/core/threading/routinegroup.go index 07ca61f9..b71aebf9 100644 --- a/core/threading/routinegroup.go +++ b/core/threading/routinegroup.go @@ -10,6 +10,7 @@ func NewRoutineGroup() *RoutineGroup { return new(RoutineGroup) } +// Run runs the given fn in RoutineGroup. // Don't reference the variables from outside, // because outside variables can be changed by other goroutines func (g *RoutineGroup) Run(fn func()) { @@ -21,6 +22,7 @@ func (g *RoutineGroup) Run(fn func()) { }() } +// RunSafe runs the given fn in RoutineGroup, and avoid panics. // Don't reference the variables from outside, // because outside variables can be changed by other goroutines func (g *RoutineGroup) RunSafe(fn func()) { @@ -32,6 +34,7 @@ func (g *RoutineGroup) RunSafe(fn func()) { }) } +// Wait waits all running functions to be done. func (g *RoutineGroup) Wait() { g.waitGroup.Wait() } diff --git a/core/trace/tracespec/keys.go b/core/trace/tracespec/keys.go index 4b935558..c6da8c79 100644 --- a/core/trace/tracespec/keys.go +++ b/core/trace/tracespec/keys.go @@ -6,7 +6,7 @@ var TracingKey = contextKey("X-Trace") // contextKey a type for context key type contextKey string -// Printing a context will reveal a fair amount of information about it. +// String returns a context will reveal a fair amount of information about it. func (c contextKey) String() string { return "trace/tracespec context key " + string(c) } diff --git a/rest/handler/contentsecurityhandler_test.go b/rest/handler/contentsecurityhandler_test.go index facf53cb..ca3e9aaf 100644 --- a/rest/handler/contentsecurityhandler_test.go +++ b/rest/handler/contentsecurityhandler_test.go @@ -315,12 +315,13 @@ func buildRequest(rs requestSettings) (*http.Request, error) { var path string var query string if len(rs.requestUri) > 0 { - if u, err := url.Parse(rs.requestUri); err != nil { + u, err := url.Parse(rs.requestUri) + if err != nil { return nil, err - } else { - path = u.Path - query = u.RawQuery } + + path = u.Path + query = u.RawQuery } else { path = r.URL.Path query = r.URL.RawQuery @@ -377,10 +378,9 @@ func createTempFile(body []byte) (string, error) { tmpFile, err := ioutil.TempFile(os.TempDir(), "go-unit-*.tmp") if err != nil { return "", err - } else { - tmpFile.Close() } + tmpFile.Close() err = ioutil.WriteFile(tmpFile.Name(), body, os.ModePerm) if err != nil { return "", err diff --git a/rest/handler/loghandler.go b/rest/handler/loghandler.go index 3625481d..93e3a8b4 100644 --- a/rest/handler/loghandler.go +++ b/rest/handler/loghandler.go @@ -114,9 +114,9 @@ func dumpRequest(r *http.Request) string { reqContent, err := httputil.DumpRequest(r, true) if err != nil { return err.Error() - } else { - return string(reqContent) } + + return string(reqContent) } func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) { diff --git a/rest/handler/sheddinghandler_test.go b/rest/handler/sheddinghandler_test.go index 7383068e..9a10bf81 100644 --- a/rest/handler/sheddinghandler_test.go +++ b/rest/handler/sheddinghandler_test.go @@ -89,9 +89,9 @@ type mockShedder struct { func (s mockShedder) Allow() (load.Promise, error) { if s.allow { return mockPromise{}, nil - } else { - return nil, load.ErrServiceOverloaded } + + return nil, load.ErrServiceOverloaded } type mockPromise struct { diff --git a/rest/httpx/requests.go b/rest/httpx/requests.go index 8df8e712..ab5b6d2c 100644 --- a/rest/httpx/requests.go +++ b/rest/httpx/requests.go @@ -24,6 +24,7 @@ var ( pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues()) ) +// Parse parses the request. func Parse(r *http.Request, v interface{}) error { if err := ParsePath(r, v); err != nil { return err @@ -36,7 +37,7 @@ func Parse(r *http.Request, v interface{}) error { return ParseJsonBody(r, v) } -// Parses the form request. +// ParseForm parses the form request. func ParseForm(r *http.Request, v interface{}) error { if err := r.ParseForm(); err != nil { return err @@ -80,7 +81,7 @@ func ParseHeader(headerValue string) map[string]string { return ret } -// Parses the post request which contains json in body. +// ParseJsonBody parses the post request which contains json in body. func ParseJsonBody(r *http.Request, v interface{}) error { var reader io.Reader if withJsonBody(r) { @@ -92,7 +93,7 @@ func ParseJsonBody(r *http.Request, v interface{}) error { return mapping.UnmarshalJsonReader(reader, v) } -// Parses the symbols reside in url path. +// ParsePath parses the symbols reside in url path. // Like http://localhost/bag/:name func ParsePath(r *http.Request, v interface{}) error { vars := context.Vars(r) diff --git a/rest/httpx/util.go b/rest/httpx/util.go index bdf6eaa8..7257092b 100644 --- a/rest/httpx/util.go +++ b/rest/httpx/util.go @@ -4,7 +4,7 @@ import "net/http" const xForwardFor = "X-Forward-For" -// Returns the peer address, supports X-Forward-For +// GetRemoteAddr returns the peer address, supports X-Forward-For. func GetRemoteAddr(r *http.Request) string { v := r.Header.Get(xForwardFor) if len(v) > 0 { diff --git a/rest/router/patrouter.go b/rest/router/patrouter.go index b6fa299b..252b105c 100644 --- a/rest/router/patrouter.go +++ b/rest/router/patrouter.go @@ -43,13 +43,14 @@ func (pr *patRouter) Handle(method, reqPath string, handler http.Handler) error } cleanPath := path.Clean(reqPath) - if tree, ok := pr.trees[method]; ok { - return tree.Add(cleanPath, handler) - } else { - tree = search.NewTree() - pr.trees[method] = tree + tree, ok := pr.trees[method] + if ok { return tree.Add(cleanPath, handler) } + + tree = search.NewTree() + pr.trees[method] = tree + return tree.Add(cleanPath, handler) } func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -110,9 +111,9 @@ func (pr *patRouter) methodsAllowed(method, path string) (string, bool) { if len(allows) > 0 { return strings.Join(allows, allowMethodSeparator), true - } else { - return "", false } + + return "", false } func validMethod(method string) bool { diff --git a/rest/token/tokenparser.go b/rest/token/tokenparser.go index f2927b16..a0aa7fbe 100644 --- a/rest/token/tokenparser.go +++ b/rest/token/tokenparser.go @@ -58,9 +58,9 @@ func (tp *TokenParser) ParseToken(r *http.Request, secret, prevSecret string) (* token, err = tp.doParseToken(r, second) if err != nil { return nil, err - } else { - tp.incrementCount(second) } + + tp.incrementCount(second) } else { tp.incrementCount(first) } diff --git a/tools/goctl/api/docgen/gen.go b/tools/goctl/api/docgen/gen.go index 4d5ce1b7..c0fb8dad 100644 --- a/tools/goctl/api/docgen/gen.go +++ b/tools/goctl/api/docgen/gen.go @@ -21,7 +21,7 @@ func DocCommand(c *cli.Context) error { files, err := filePathWalkDir(dir) if err != nil { - return errors.New(fmt.Sprintf("dir %s not exist", dir)) + return fmt.Errorf("dir %s not exist", dir) } err = os.RemoveAll(dir + "/" + docDir + "/") @@ -31,7 +31,7 @@ func DocCommand(c *cli.Context) error { for _, f := range files { api, err := parser.Parse(f) if err != nil { - return errors.New(fmt.Sprintf("parse file: %s, err: %s", f, err.Error())) + return fmt.Errorf("parse file: %s, err: %s", f, err.Error()) } index := strings.Index(f, dir) diff --git a/tools/goctl/api/gogen/gentypes.go b/tools/goctl/api/gogen/gentypes.go index c109dc7a..b4a123fc 100644 --- a/tools/goctl/api/gogen/gentypes.go +++ b/tools/goctl/api/gogen/gentypes.go @@ -1,7 +1,6 @@ package gogen import ( - "errors" "fmt" "io" "os" @@ -76,7 +75,7 @@ func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error { func writeType(writer io.Writer, tp spec.Type) error { structType, ok := tp.(spec.DefineStruct) if !ok { - return errors.New(fmt.Sprintf("unspport struct type: %s", tp.Name())) + return fmt.Errorf("unspport struct type: %s", tp.Name()) } fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name())) @@ -84,9 +83,9 @@ func writeType(writer io.Writer, tp spec.Type) error { if member.IsInline { if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil { return err - } else { - continue } + + continue } if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil { diff --git a/tools/goctl/api/javagen/gencomponents.go b/tools/goctl/api/javagen/gencomponents.go index 952d4e50..85dd9d4d 100644 --- a/tools/goctl/api/javagen/gencomponents.go +++ b/tools/goctl/api/javagen/gencomponents.go @@ -216,7 +216,7 @@ func (c *componentsContext) writeMembers(writer io.Writer, tp spec.Type, indent if ok { return c.writeMembers(writer, pointType.Type, indent) } - return errors.New(fmt.Sprintf("type %s not supported", tp.Name())) + return fmt.Errorf("type %s not supported", tp.Name()) } for _, member := range definedType.Members { diff --git a/tools/goctl/api/parser/g4/ast/ast.go b/tools/goctl/api/parser/g4/ast/ast.go index fc8c3a63..217eb600 100644 --- a/tools/goctl/api/parser/g4/ast/ast.go +++ b/tools/goctl/api/parser/g4/ast/ast.go @@ -203,41 +203,40 @@ func (e *defaultExpr) IsNotNil() bool { func EqualDoc(spec1, spec2 Spec) bool { if spec1 == nil { - if spec2 != nil { + return spec2 == nil + } + + if spec2 == nil { + return false + } + + var expectDoc, actualDoc []Expr + expectDoc = append(expectDoc, spec2.Doc()...) + actualDoc = append(actualDoc, spec1.Doc()...) + sort.Slice(expectDoc, func(i, j int) bool { + return expectDoc[i].Line() < expectDoc[j].Line() + }) + + for index, each := range actualDoc { + if !each.Equal(actualDoc[index]) { return false } - return true - } else { - if spec2 == nil { + } + + if spec1.Comment() != nil { + if spec2.Comment() == nil { return false } - var expectDoc, actualDoc []Expr - expectDoc = append(expectDoc, spec2.Doc()...) - actualDoc = append(actualDoc, spec1.Doc()...) - sort.Slice(expectDoc, func(i, j int) bool { - return expectDoc[i].Line() < expectDoc[j].Line() - }) - - for index, each := range actualDoc { - if !each.Equal(actualDoc[index]) { - return false - } + if !spec1.Comment().Equal(spec2.Comment()) { + return false } - - if spec1.Comment() != nil { - if spec2.Comment() == nil { - return false - } - if !spec1.Comment().Equal(spec2.Comment()) { - return false - } - } else { - if spec2.Comment() != nil { - return false - } + } else { + if spec2.Comment() != nil { + return false } } + return true } @@ -295,8 +294,10 @@ func (v *ApiVisitor) getHiddenTokensToLeft(t TokenStream, channel int, containsC } } } + list = append(list, v.newExprWithToken(each)) } + return list } @@ -307,6 +308,7 @@ func (v *ApiVisitor) getHiddenTokensToRight(t TokenStream, channel int) []Expr { for _, each := range tokens { list = append(list, v.newExprWithToken(each)) } + return list } @@ -314,6 +316,7 @@ func (v *ApiVisitor) exportCheck(expr Expr) { if expr == nil || !expr.IsNotNil() { return } + if api.IsBasicType(expr.Text()) { return } diff --git a/tools/goctl/api/parser/g4/ast/service.go b/tools/goctl/api/parser/g4/ast/service.go index 8a45e7ca..3795191d 100644 --- a/tools/goctl/api/parser/g4/ast/service.go +++ b/tools/goctl/api/parser/g4/ast/service.go @@ -508,9 +508,9 @@ func (s *ServiceRoute) Format() error { func (s *ServiceRoute) GetHandler() Expr { if s.AtHandler != nil { return s.AtHandler.Name - } else { - return s.AtServer.Kv.Get("handler") } + + return s.AtServer.Kv.Get("handler") } func (a *ServiceApi) Format() error { diff --git a/tools/goctl/api/parser/parser.go b/tools/goctl/api/parser/parser.go index bd7a3330..3940e1d8 100644 --- a/tools/goctl/api/parser/parser.go +++ b/tools/goctl/api/parser/parser.go @@ -1,7 +1,6 @@ package parser import ( - "errors" "fmt" "path/filepath" "unicode" @@ -101,7 +100,7 @@ func (p parser) fillTypes() error { Docs: p.stringExprs(v.Doc()), }) default: - return errors.New(fmt.Sprintf("unknown type %+v", v)) + return fmt.Errorf("unknown type %+v", v) } } @@ -116,16 +115,16 @@ func (p parser) fillTypes() error { tp, err := p.findDefinedType(v.RawName) if err != nil { return err - } else { - member.Type = *tp } + + member.Type = *tp } members = append(members, member) } v.Members = members types = append(types, v) default: - return errors.New(fmt.Sprintf("unknown type %+v", v)) + return fmt.Errorf("unknown type %+v", v) } } p.spec.Types = types @@ -141,7 +140,8 @@ func (p parser) findDefinedType(name string) (*spec.Type, error) { } } } - return nil, errors.New(fmt.Sprintf("type %s not defined", name)) + + return nil, fmt.Errorf("type %s not defined", name) } func (p parser) fieldToMember(field *ast.TypeField) spec.Member { @@ -172,9 +172,9 @@ func (p parser) astTypeToSpec(in ast.DataType) spec.Type { raw := v.Literal.Text() if api.IsBasicType(raw) { return spec.PrimitiveType{RawName: raw} - } else { - return spec.DefineStruct{RawName: raw} } + + return spec.DefineStruct{RawName: raw} case *ast.Interface: return spec.InterfaceType{RawName: v.Literal.Text()} case *ast.Map: @@ -185,9 +185,9 @@ func (p parser) astTypeToSpec(in ast.DataType) spec.Type { raw := v.Name.Text() if api.IsBasicType(raw) { return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.PrimitiveType{RawName: raw}} - } else { - return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}} } + + return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}} } panic(fmt.Sprintf("unspported type %+v", in)) @@ -246,8 +246,8 @@ func (p parser) fillService() error { for _, char := range route.Handler { if !unicode.IsDigit(char) && !unicode.IsLetter(char) { - return errors.New(fmt.Sprintf("route [%s] handler [%s] invalid, handler name should only contains letter or digit", - route.Path, route.Handler)) + return fmt.Errorf("route [%s] handler [%s] invalid, handler name should only contains letter or digit", + route.Path, route.Handler) } } } @@ -278,7 +278,7 @@ func (p parser) fillService() error { name := item.ServiceApi.Name.Text() if len(p.spec.Service.Name) > 0 && p.spec.Service.Name != name { - return errors.New(fmt.Sprintf("mulit service name defined %s and %s", name, p.spec.Service.Name)) + return fmt.Errorf("mulit service name defined %s and %s", name, p.spec.Service.Name) } p.spec.Service.Name = name } diff --git a/tools/goctl/api/tsgen/genpacket.go b/tools/goctl/api/tsgen/genpacket.go index 31830e2d..2965a922 100644 --- a/tools/goctl/api/tsgen/genpacket.go +++ b/tools/goctl/api/tsgen/genpacket.go @@ -160,11 +160,11 @@ func pathForRoute(route spec.Route, group spec.Group) string { prefix := group.GetAnnotation("pathPrefix") if len(prefix) == 0 { return "\"" + route.Path + "\"" - } else { - prefix = strings.TrimPrefix(prefix, `"`) - prefix = strings.TrimSuffix(prefix, `"`) - return fmt.Sprintf(`"%s/%s"`, prefix, strings.TrimPrefix(route.Path, "/")) } + + prefix = strings.TrimPrefix(prefix, `"`) + prefix = strings.TrimSuffix(prefix, `"`) + return fmt.Sprintf(`"%s/%s"`, prefix, strings.TrimPrefix(route.Path, "/")) } func pathHasParams(route spec.Route) bool { diff --git a/tools/goctl/api/tsgen/util.go b/tools/goctl/api/tsgen/util.go index 799a8a1d..8e01498c 100644 --- a/tools/goctl/api/tsgen/util.go +++ b/tools/goctl/api/tsgen/util.go @@ -146,7 +146,8 @@ func writeMembers(writer io.Writer, tp spec.Type, isParam bool) error { if ok { return writeMembers(writer, pointType.Type, isParam) } - return errors.New(fmt.Sprintf("type %s not supported", tp.Name())) + + return fmt.Errorf("type %s not supported", tp.Name()) } members := definedType.GetBodyMembers() diff --git a/tools/goctl/model/sql/gen/imports.go b/tools/goctl/model/sql/gen/imports.go index 95ae514b..1916113b 100644 --- a/tools/goctl/model/sql/gen/imports.go +++ b/tools/goctl/model/sql/gen/imports.go @@ -20,19 +20,19 @@ func genImports(withCache, timeImport bool) (string, error) { } return buffer.String(), nil - } else { - text, err := util.LoadTemplate(category, importsWithNoCacheTemplateFile, template.ImportsNoCache) - if err != nil { - return "", err - } + } - buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{ - "time": timeImport, - }) - if err != nil { - return "", err - } + text, err := util.LoadTemplate(category, importsWithNoCacheTemplateFile, template.ImportsNoCache) + if err != nil { + return "", err + } - return buffer.String(), nil + buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{ + "time": timeImport, + }) + if err != nil { + return "", err } + + return buffer.String(), nil } diff --git a/tools/goctl/model/sql/parser/error.go b/tools/goctl/model/sql/parser/error.go index 8d34dce7..301be6c0 100644 --- a/tools/goctl/model/sql/parser/error.go +++ b/tools/goctl/model/sql/parser/error.go @@ -5,7 +5,7 @@ import ( ) var ( - unSupportDDL = errors.New("unexpected type") - tableBodyIsNotFound = errors.New("create table spec not found") - errPrimaryKey = errors.New("unexpected join primary key") + errUnsupportDDL = errors.New("unexpected type") + errTableBodyNotFound = errors.New("create table spec not found") + errPrimaryKey = errors.New("unexpected join primary key") ) diff --git a/tools/goctl/model/sql/parser/parser.go b/tools/goctl/model/sql/parser/parser.go index 450c6047..85bd9bfd 100644 --- a/tools/goctl/model/sql/parser/parser.go +++ b/tools/goctl/model/sql/parser/parser.go @@ -52,7 +52,7 @@ func Parse(ddl string) (*Table, error) { ddlStmt, ok := stmt.(*sqlparser.DDL) if !ok { - return nil, unSupportDDL + return nil, errUnsupportDDL } action := ddlStmt.Action @@ -63,7 +63,7 @@ func Parse(ddl string) (*Table, error) { tableName := ddlStmt.NewName.Name.String() tableSpec := ddlStmt.TableSpec if tableSpec == nil { - return nil, tableBodyIsNotFound + return nil, errTableBodyNotFound } columns := tableSpec.Columns diff --git a/tools/goctl/model/sql/parser/parser_test.go b/tools/goctl/model/sql/parser/parser_test.go index e8fd7689..def99a15 100644 --- a/tools/goctl/model/sql/parser/parser_test.go +++ b/tools/goctl/model/sql/parser/parser_test.go @@ -14,7 +14,7 @@ func TestParsePlainText(t *testing.T) { func TestParseSelect(t *testing.T) { _, err := Parse("select * from user") - assert.Equal(t, unSupportDDL, err) + assert.Equal(t, errUnsupportDDL, err) } func TestParseCreateTable(t *testing.T) { diff --git a/tools/goctl/update/update.go b/tools/goctl/update/update.go index 5b1e42b3..a1b2d95e 100644 --- a/tools/goctl/update/update.go +++ b/tools/goctl/update/update.go @@ -39,10 +39,9 @@ func forChksumHandler(file string, next http.Handler) http.Handler { if chksum == r.Header.Get(contentMd5Header) { w.WriteHeader(http.StatusNotModified) return - } else { - w.Header().Set(contentMd5Header, chksum) } + w.Header().Set(contentMd5Header, chksum) next.ServeHTTP(w, r) }) } diff --git a/tools/goctl/util/ctx/context.go b/tools/goctl/util/ctx/context.go index c41b1cf8..68ebc2c4 100644 --- a/tools/goctl/util/ctx/context.go +++ b/tools/goctl/util/ctx/context.go @@ -7,21 +7,19 @@ import ( "github.com/tal-tech/go-zero/tools/goctl/rpc/execx" ) -var moduleCheckErr = errors.New("the work directory must be found in the go mod or the $GOPATH") - -type ( - ProjectContext struct { - WorkDir string - // Name is the root name of the project - // eg: go-zero、greet - Name string - // Path identifies which module a project belongs to, which is module value if it's a go mod project, - // or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet - Path string - // Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet - Dir string - } -) +var errModuleCheck = errors.New("the work directory must be found in the go mod or the $GOPATH") + +type ProjectContext struct { + WorkDir string + // Name is the root name of the project + // eg: go-zero、greet + Name string + // Path identifies which module a project belongs to, which is module value if it's a go mod project, + // or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet + Path string + // Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet + Dir string +} // Prepare checks the project which module belongs to,and returns the path and module. // workDir parameter is the directory of the source of generating code, diff --git a/tools/goctl/util/ctx/gopath.go b/tools/goctl/util/ctx/gopath.go index ec44ef2b..bd94d7fa 100644 --- a/tools/goctl/util/ctx/gopath.go +++ b/tools/goctl/util/ctx/gopath.go @@ -25,7 +25,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) { goPath := buildContext.GOPATH goSrc := filepath.Join(goPath, "src") if !util.FileExists(goSrc) { - return nil, moduleCheckErr + return nil, errModuleCheck } wd, err := filepath.Abs(workDir) @@ -34,7 +34,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) { } if !strings.HasPrefix(wd, goSrc) { - return nil, moduleCheckErr + return nil, errModuleCheck } projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator)) diff --git a/zrpc/internal/balancer/p2c/p2c.go b/zrpc/internal/balancer/p2c/p2c.go index 7cbbaabd..8125b605 100644 --- a/zrpc/internal/balancer/p2c/p2c.go +++ b/zrpc/internal/balancer/p2c/p2c.go @@ -155,10 +155,10 @@ func (p *p2cPicker) choose(c1, c2 *subConn) *subConn { pick := atomic.LoadInt64(&c2.pick) if start-pick > forcePick && atomic.CompareAndSwapInt64(&c2.pick, pick, start) { return c2 - } else { - atomic.StoreInt64(&c1.pick, start) - return c1 } + + atomic.StoreInt64(&c1.pick, start) + return c1 } func (p *p2cPicker) logStats() { @@ -196,7 +196,7 @@ func (c *subConn) load() int64 { load := lag * (atomic.LoadInt64(&c.inflight) + 1) if load == 0 { return penalty - } else { - return load } + + return load } diff --git a/zrpc/internal/resolver/subset.go b/zrpc/internal/resolver/subset.go index 3c6c8f06..63a25fbe 100644 --- a/zrpc/internal/resolver/subset.go +++ b/zrpc/internal/resolver/subset.go @@ -8,7 +8,7 @@ func subset(set []string, sub int) []string { }) if len(set) <= sub { return set - } else { - return set[:sub] } + + return set[:sub] } diff --git a/zrpc/internal/serverinterceptors/sheddinginterceptor_test.go b/zrpc/internal/serverinterceptors/sheddinginterceptor_test.go index 7b64002e..55ac22c1 100644 --- a/zrpc/internal/serverinterceptors/sheddinginterceptor_test.go +++ b/zrpc/internal/serverinterceptors/sheddinginterceptor_test.go @@ -62,9 +62,9 @@ type mockedShedder struct { func (m mockedShedder) Allow() (load.Promise, error) { if m.allow { return mockedPromise{}, nil - } else { - return nil, load.ErrServiceOverloaded } + + return nil, load.ErrServiceOverloaded } type mockedPromise struct { diff --git a/zrpc/server.go b/zrpc/server.go index a883d682..a6f8b0e1 100644 --- a/zrpc/server.go +++ b/zrpc/server.go @@ -109,9 +109,9 @@ func figureOutListenOn(listenOn string) string { } if len(ip) == 0 { return listenOn - } else { - return strings.Join(append([]string{ip}, fields[1:]...), ":") } + + return strings.Join(append([]string{ip}, fields[1:]...), ":") } func setupInterceptors(server internal.Server, c RpcServerConf, metrics *stat.Metrics) error {