fix golint issues, else blocks (#457)

master
Kevin Wan 4 years ago committed by GitHub
parent 42883d0899
commit 5e969cbef0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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
}

@ -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() {

@ -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 {

@ -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
}

@ -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() {

@ -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{}) {

@ -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 {

@ -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),

@ -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()) {

@ -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.

@ -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 {

@ -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) {

@ -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 {

@ -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 {

@ -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
}

@ -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)

@ -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
}
}

@ -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 {

@ -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
}

@ -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 {

@ -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() {

@ -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 {

@ -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

@ -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() {

@ -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) {

@ -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) {

@ -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.

@ -1,6 +1,7 @@
package clickhouse
import (
// imports the driver.
_ "github.com/ClickHouse/clickhouse-go"
"github.com/tal-tech/go-zero/core/stores/sqlx"
)

@ -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
}

@ -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
}

@ -1,6 +1,7 @@
package postgres
import (
// imports the driver.
_ "github.com/lib/pq"
"github.com/tal-tech/go-zero/core/stores/sqlx"
)

@ -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

@ -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) {

@ -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:

@ -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 {

@ -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 {

@ -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 {

@ -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

@ -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()
}

@ -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)
}

@ -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

@ -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) {

@ -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 {

@ -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)

@ -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 {

@ -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 {

@ -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)
}

@ -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)

@ -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 {

@ -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 {

@ -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
}

@ -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 {

@ -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
}

@ -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 {

@ -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()

@ -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
}

@ -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")
)

@ -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

@ -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) {

@ -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)
})
}

@ -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,

@ -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))

@ -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
}

@ -8,7 +8,7 @@ func subset(set []string, sub int) []string {
})
if len(set) <= sub {
return set
} else {
return set[:sub]
}
return set[:sub]
}

@ -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 {

@ -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 {

Loading…
Cancel
Save