fix golint issues, else blocks (#457)

This commit is contained in:
Kevin Wan
2021-02-09 13:50:21 +08:00
committed by GitHub
parent 42883d0899
commit 5e969cbef0
66 changed files with 341 additions and 311 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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