fix golint issues, else blocks (#457)
This commit is contained in:
@@ -127,11 +127,12 @@ func (r *redisBitSet) check(offsets []uint) (bool, error) {
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if exists, ok := resp.(int64); !ok {
|
exists, ok := resp.(int64)
|
||||||
|
if !ok {
|
||||||
return false, nil
|
return false, nil
|
||||||
} else {
|
|
||||||
return exists == 1, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return exists == 1, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *redisBitSet) del() error {
|
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)
|
_, err = r.store.Eval(setScript, []string{r.key}, args)
|
||||||
if err == redis.Nil {
|
if err == redis.Nil {
|
||||||
return 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 err := b.accept(); err != nil {
|
||||||
if fallback != nil {
|
if fallback != nil {
|
||||||
return fallback(err)
|
return fallback(err)
|
||||||
} else {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|||||||
@@ -150,11 +150,12 @@ func getKeyBytes(key string) ([]byte, error) {
|
|||||||
return []byte(key), nil
|
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
|
return nil, err
|
||||||
} else {
|
|
||||||
return keyBytes, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return keyBytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
|
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
|
||||||
|
|||||||
@@ -136,11 +136,10 @@ func (c *Cache) Take(key string, fetch func() (interface{}, error)) (interface{}
|
|||||||
if fresh {
|
if fresh {
|
||||||
c.stats.IncrementMiss()
|
c.stats.IncrementMiss()
|
||||||
return val, nil
|
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
|
return val, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -73,9 +73,9 @@ func (rw *RollingWindow) span() int {
|
|||||||
offset := int(timex.Since(rw.lastTime) / rw.interval)
|
offset := int(timex.Since(rw.lastTime) / rw.interval)
|
||||||
if 0 <= offset && offset < rw.size {
|
if 0 <= offset && offset < rw.size {
|
||||||
return offset
|
return offset
|
||||||
} else {
|
|
||||||
return rw.size
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return rw.size
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw *RollingWindow) updateOffset() {
|
func (rw *RollingWindow) updateOffset() {
|
||||||
|
|||||||
@@ -59,10 +59,10 @@ func (m *SafeMap) Get(key interface{}) (interface{}, bool) {
|
|||||||
|
|
||||||
if val, ok := m.dirtyOld[key]; ok {
|
if val, ok := m.dirtyOld[key]; ok {
|
||||||
return val, true
|
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{}) {
|
func (m *SafeMap) Set(key, value interface{}) {
|
||||||
|
|||||||
@@ -34,9 +34,9 @@ func LoadConfig(file string, v interface{}, opts ...Option) error {
|
|||||||
|
|
||||||
if opt.env {
|
if opt.env {
|
||||||
return loader([]byte(os.ExpandEnv(string(content))), v)
|
return loader([]byte(os.ExpandEnv(string(content))), v)
|
||||||
} else {
|
|
||||||
return loader(content, v)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return loader(content, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
|
func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ type mapBasedProperties struct {
|
|||||||
lock sync.RWMutex
|
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.
|
// Returns an error that indicates if there was a problem loading the configuration.
|
||||||
func LoadProperties(filename string, opts ...Option) (Properties, error) {
|
func LoadProperties(filename string, opts ...Option) (Properties, error) {
|
||||||
lines, err := iox.ReadTextLines(filename, iox.WithoutBlank(), iox.OmitWithPrefix("#"))
|
lines, err := iox.ReadTextLines(filename, iox.WithoutBlank(), iox.OmitWithPrefix("#"))
|
||||||
@@ -97,7 +97,7 @@ func (config *mapBasedProperties) SetInt(key string, value int) {
|
|||||||
config.lock.Unlock()
|
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 {
|
func (config *mapBasedProperties) ToString() string {
|
||||||
config.lock.RLock()
|
config.lock.RLock()
|
||||||
ret := fmt.Sprintf("%s", config.properties)
|
ret := fmt.Sprintf("%s", config.properties)
|
||||||
@@ -106,12 +106,12 @@ func (config *mapBasedProperties) ToString() string {
|
|||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the error message.
|
// Error returns the error message.
|
||||||
func (configError *PropertyError) Error() string {
|
func (configError *PropertyError) Error() string {
|
||||||
return configError.message
|
return configError.message
|
||||||
}
|
}
|
||||||
|
|
||||||
// Builds a new properties configuration structure
|
// NewProperties builds a new properties configuration structure.
|
||||||
func NewProperties() Properties {
|
func NewProperties() Properties {
|
||||||
return &mapBasedProperties{
|
return &mapBasedProperties{
|
||||||
properties: make(map[string]string),
|
properties: make(map[string]string),
|
||||||
|
|||||||
@@ -100,9 +100,9 @@ func (c *container) addKv(key, value string) ([]string, bool) {
|
|||||||
|
|
||||||
if early {
|
if early {
|
||||||
return previous, true
|
return previous, true
|
||||||
} else {
|
|
||||||
return nil, false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *container) addListener(listener func()) {
|
func (c *container) addListener(listener func()) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
const idleRound = 10
|
const idleRound = 10
|
||||||
|
|
||||||
type (
|
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.
|
// container that used to do periodical executions.
|
||||||
TaskContainer interface {
|
TaskContainer interface {
|
||||||
// AddTask adds the task into the container.
|
// AddTask adds the task into the container.
|
||||||
|
|||||||
@@ -300,9 +300,9 @@ func (p Stream) Walk(fn WalkFunc, opts ...Option) Stream {
|
|||||||
option := buildOptions(opts...)
|
option := buildOptions(opts...)
|
||||||
if option.unlimitedWorkers {
|
if option.unlimitedWorkers {
|
||||||
return p.walkUnlimited(fn, option)
|
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 {
|
func (p Stream) walkLimited(fn WalkFunc, option *rxOptions) Stream {
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ func (mt *MilliTime) UnmarshalJSON(data []byte) error {
|
|||||||
var milli int64
|
var milli int64
|
||||||
if err := json.Unmarshal(data, &milli); err != nil {
|
if err := json.Unmarshal(data, &milli); err != nil {
|
||||||
return err
|
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) {
|
func (mt MilliTime) GetBSON() (interface{}, error) {
|
||||||
|
|||||||
@@ -97,9 +97,9 @@ func (h *PeriodLimit) calcExpireSeconds() int {
|
|||||||
if h.align {
|
if h.align {
|
||||||
unix := time.Now().Unix() + zoneDiff
|
unix := time.Now().Unix() + zoneDiff
|
||||||
return h.period - int(unix%int64(h.period))
|
return h.period - int(unix%int64(h.period))
|
||||||
} else {
|
|
||||||
return h.period
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return h.period
|
||||||
}
|
}
|
||||||
|
|
||||||
func Align() LimitOption {
|
func Align() LimitOption {
|
||||||
|
|||||||
@@ -163,9 +163,9 @@ func (l *RotateLogger) Write(data []byte) (int, error) {
|
|||||||
func (l *RotateLogger) getBackupFilename() string {
|
func (l *RotateLogger) getBackupFilename() string {
|
||||||
if len(l.backup) == 0 {
|
if len(l.backup) == 0 {
|
||||||
return l.rule.BackupFileName()
|
return l.rule.BackupFileName()
|
||||||
} else {
|
|
||||||
return l.backup
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return l.backup
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *RotateLogger) init() error {
|
func (l *RotateLogger) init() error {
|
||||||
|
|||||||
@@ -35,9 +35,9 @@ func (o *fieldOptionsWithContext) fromString() bool {
|
|||||||
func (o *fieldOptionsWithContext) getDefault() (string, bool) {
|
func (o *fieldOptionsWithContext) getDefault() (string, bool) {
|
||||||
if o == nil {
|
if o == nil {
|
||||||
return "", false
|
return "", false
|
||||||
} else {
|
|
||||||
return o.Default, len(o.Default) > 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return o.Default, len(o.Default) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *fieldOptionsWithContext) optional() bool {
|
func (o *fieldOptionsWithContext) optional() bool {
|
||||||
@@ -55,9 +55,9 @@ func (o *fieldOptionsWithContext) options() []string {
|
|||||||
func (o *fieldOptions) optionalDep() string {
|
func (o *fieldOptions) optionalDep() string {
|
||||||
if o == nil {
|
if o == nil {
|
||||||
return ""
|
return ""
|
||||||
} else {
|
|
||||||
return o.OptionalDep
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return o.OptionalDep
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) (
|
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)
|
_, selfOn := m.Value(key)
|
||||||
if baseOn == selfOn {
|
if baseOn == selfOn {
|
||||||
return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
|
return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
|
||||||
} else {
|
|
||||||
optional = baseOn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
optional = baseOn
|
||||||
} else {
|
} else {
|
||||||
_, baseOn := m.Value(dep)
|
_, baseOn := m.Value(dep)
|
||||||
_, selfOn := m.Value(key)
|
_, selfOn := m.Value(key)
|
||||||
if baseOn != selfOn {
|
if baseOn != selfOn {
|
||||||
return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
|
return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
|
||||||
dep, key, fullName)
|
dep, key, fullName)
|
||||||
} else {
|
|
||||||
optional = !baseOn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
optional = !baseOn
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if o.fieldOptionsWithContext.Optional == optional {
|
if o.fieldOptionsWithContext.Optional == optional {
|
||||||
return &o.fieldOptionsWithContext, nil
|
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() {
|
if options.optional() {
|
||||||
return u.processAnonymousFieldOptional(field, value, key, m, fullName)
|
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,
|
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 {
|
if field.Anonymous {
|
||||||
return u.processAnonymousField(field, value, m, fullName)
|
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,
|
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)
|
mapValue, hasValue := getValue(m, key)
|
||||||
if hasValue {
|
if hasValue {
|
||||||
return u.processNamedFieldWithValue(field, value, mapValue, key, opts, fullName)
|
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,
|
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 mapValue == nil {
|
||||||
if opts.optional() {
|
if opts.optional() {
|
||||||
return nil
|
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)
|
maybeNewValue(field, value)
|
||||||
|
|||||||
@@ -124,23 +124,26 @@ func convertType(kind reflect.Kind, str string) (interface{}, error) {
|
|||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
return str == "1" || strings.ToLower(str) == "true", nil
|
return str == "1" || strings.ToLower(str) == "true", nil
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
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)
|
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:
|
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)
|
return 0, fmt.Errorf("the value %q cannot parsed as uint", str)
|
||||||
} else {
|
|
||||||
return uintValue, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return uintValue, nil
|
||||||
case reflect.Float32, reflect.Float64:
|
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)
|
return 0, fmt.Errorf("the value %q cannot parsed as float", str)
|
||||||
} else {
|
|
||||||
return floatValue, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return floatValue, nil
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
return str, nil
|
return str, nil
|
||||||
default:
|
default:
|
||||||
@@ -180,26 +183,28 @@ func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fie
|
|||||||
segs := strings.Split(option, equalToken)
|
segs := strings.Split(option, equalToken)
|
||||||
if len(segs) != 2 {
|
if len(segs) != 2 {
|
||||||
return "", nil, fmt.Errorf("field %s has wrong options", field.Name)
|
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):
|
case strings.HasPrefix(option, defaultOption):
|
||||||
segs := strings.Split(option, equalToken)
|
segs := strings.Split(option, equalToken)
|
||||||
if len(segs) != 2 {
|
if len(segs) != 2 {
|
||||||
return "", nil, fmt.Errorf("field %s has wrong default option", field.Name)
|
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):
|
case strings.HasPrefix(option, rangeOption):
|
||||||
segs := strings.Split(option, equalToken)
|
segs := strings.Split(option, equalToken)
|
||||||
if len(segs) != 2 {
|
if len(segs) != 2 {
|
||||||
return "", nil, fmt.Errorf("field %s has wrong range", field.Name)
|
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
|
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 {
|
if m, ok := o.(map[string]interface{}); ok {
|
||||||
return unmarshaler.Unmarshal(m, v)
|
return unmarshaler.Unmarshal(m, v)
|
||||||
} else {
|
|
||||||
return ErrUnsupportedType
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ErrUnsupportedType
|
||||||
}
|
}
|
||||||
|
|
||||||
func unmarshalYamlReader(reader io.Reader, v interface{}, unmarshaler *Unmarshaler) error {
|
func unmarshalYamlReader(reader io.Reader, v interface{}, unmarshaler *Unmarshaler) error {
|
||||||
|
|||||||
@@ -3,15 +3,15 @@ package mathx
|
|||||||
func MaxInt(a, b int) int {
|
func MaxInt(a, b int) int {
|
||||||
if a > b {
|
if a > b {
|
||||||
return a
|
return a
|
||||||
} else {
|
|
||||||
return b
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
func MinInt(a, b int) int {
|
func MinInt(a, b int) int {
|
||||||
if a < b {
|
if a < b {
|
||||||
return a
|
return a
|
||||||
} else {
|
|
||||||
return b
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ func (p *Profile) Stop() {
|
|||||||
atomic.StoreUint32(&started, 0)
|
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
|
// The caller should call the Stop method on the value returned
|
||||||
// to cleanly stop profiling.
|
// to cleanly stop profiling.
|
||||||
func StartProfile() Stopper {
|
func StartProfile() Stopper {
|
||||||
|
|||||||
@@ -83,9 +83,9 @@ func generateReport() string {
|
|||||||
calcFn := func(total, count int64) string {
|
calcFn := func(total, count int64) string {
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
return "-"
|
return "-"
|
||||||
} else {
|
|
||||||
return (time.Duration(total) / time.Duration(count)).String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return (time.Duration(total) / time.Duration(count)).String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func() {
|
func() {
|
||||||
|
|||||||
@@ -78,10 +78,10 @@ func (p *mockedProducer) Produce() (string, bool) {
|
|||||||
if atomic.AddInt32(&p.count, 1) <= p.total {
|
if atomic.AddInt32(&p.count, 1) <= p.total {
|
||||||
p.wait.Done()
|
p.wait.Done()
|
||||||
return "item", true
|
return "item", true
|
||||||
} else {
|
|
||||||
time.Sleep(time.Second)
|
|
||||||
return "", false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
type mockedListener struct {
|
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 {
|
func (nd *node) getChildren(route string) map[string]*node {
|
||||||
if len(route) > 0 && route[0] == colon {
|
if len(route) > 0 && route[0] == colon {
|
||||||
return nd.children[1]
|
return nd.children[1]
|
||||||
} else {
|
|
||||||
return nd.children[0]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nd.children[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func add(nd *node, route string, item interface{}) error {
|
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, ok := children[token]; ok {
|
||||||
if child != nil {
|
if child != nil {
|
||||||
return add(child, route[i+1:], item)
|
return add(child, route[i+1:], item)
|
||||||
} else {
|
|
||||||
return ErrInvalidState
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ErrInvalidState
|
||||||
} else {
|
} else {
|
||||||
child := newNode(nil)
|
child := newNode(nil)
|
||||||
children[token] = child
|
children[token] = child
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ func (sg *ServiceGroup) Add(service Service) {
|
|||||||
sg.services = append(sg.services, 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.
|
// 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.
|
// Also, quitting this method will close the logx output.
|
||||||
func (sg *ServiceGroup) Start() {
|
func (sg *ServiceGroup) Start() {
|
||||||
|
|||||||
@@ -110,16 +110,16 @@ func parseUint(s string) (uint64, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
if err.(*strconv.NumError).Err == strconv.ErrRange {
|
if err.(*strconv.NumError).Err == strconv.ErrRange {
|
||||||
return 0, nil
|
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) {
|
func parseUints(val string) ([]uint64, error) {
|
||||||
|
|||||||
@@ -185,9 +185,9 @@ func getTopDuration(tasks []Task) float32 {
|
|||||||
top := topK(tasks, 1)
|
top := topK(tasks, 1)
|
||||||
if len(top) < 1 {
|
if len(top) < 1 {
|
||||||
return 0
|
return 0
|
||||||
} else {
|
|
||||||
return float32(top[0].Duration) / float32(time.Millisecond)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return float32(top[0].Duration) / float32(time.Millisecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
func log(report *StatReport) {
|
func log(report *StatReport) {
|
||||||
|
|||||||
7
core/stores/cache/cachenode.go
vendored
7
core/stores/cache/cachenode.go
vendored
@@ -75,11 +75,12 @@ func (c cacheNode) DelCache(keys ...string) error {
|
|||||||
|
|
||||||
// GetCache gets the cache with key and fills into v.
|
// GetCache gets the cache with key and fills into v.
|
||||||
func (c cacheNode) GetCache(key string, v interface{}) error {
|
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
|
return c.errNotFound
|
||||||
} else {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsNotFound checks if the given error is the defined errNotFound.
|
// IsNotFound checks if the given error is the defined errNotFound.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package clickhouse
|
package clickhouse
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
// imports the driver.
|
||||||
_ "github.com/ClickHouse/clickhouse-go"
|
_ "github.com/ClickHouse/clickhouse-go"
|
||||||
"github.com/tal-tech/go-zero/core/stores/sqlx"
|
"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) {
|
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
|
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 {
|
if err := cs.limit.Borrow(o.timeout); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
|
||||||
return cs.Copy(), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return cs.Copy(), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package postgres
|
package postgres
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
// imports the driver.
|
||||||
_ "github.com/lib/pq"
|
_ "github.com/lib/pq"
|
||||||
"github.com/tal-tech/go-zero/core/stores/sqlx"
|
"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
|
// Doesn't benefit from pooling redis connections of blocking queries
|
||||||
func (s *Redis) Blpop(redisNode RedisNode, key string) (string, error) {
|
func (s *Redis) Blpop(redisNode RedisNode, key string) (string, error) {
|
||||||
if redisNode == nil {
|
if redisNode == nil {
|
||||||
@@ -1093,15 +1093,16 @@ func (s *Redis) Zadd(key string, score int64, value string) (val bool, err error
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v, err := conn.ZAdd(key, red.Z{
|
v, err := conn.ZAdd(key, red.Z{
|
||||||
Score: float64(score),
|
Score: float64(score),
|
||||||
Member: value,
|
Member: value,
|
||||||
}).Result(); err != nil {
|
}).Result()
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
val = v == 1
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = v == 1
|
||||||
|
return nil
|
||||||
}, acceptable)
|
}, acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -1339,15 +1340,16 @@ func (s *Redis) ZrangebyscoreWithScores(key string, start, stop int64) (val []Pa
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{
|
v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{
|
||||||
Min: strconv.FormatInt(start, 10),
|
Min: strconv.FormatInt(start, 10),
|
||||||
Max: strconv.FormatInt(stop, 10),
|
Max: strconv.FormatInt(stop, 10),
|
||||||
}).Result(); err != nil {
|
}).Result()
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
val = toPairs(v)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = toPairs(v)
|
||||||
|
return nil
|
||||||
}, acceptable)
|
}, acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -1365,17 +1367,18 @@ func (s *Redis) ZrangebyscoreWithScoresAndLimit(key string, start, stop int64, p
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{
|
v, err := conn.ZRangeByScoreWithScores(key, red.ZRangeBy{
|
||||||
Min: strconv.FormatInt(start, 10),
|
Min: strconv.FormatInt(start, 10),
|
||||||
Max: strconv.FormatInt(stop, 10),
|
Max: strconv.FormatInt(stop, 10),
|
||||||
Offset: int64(page * size),
|
Offset: int64(page * size),
|
||||||
Count: int64(size),
|
Count: int64(size),
|
||||||
}).Result(); err != nil {
|
}).Result()
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
val = toPairs(v)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = toPairs(v)
|
||||||
|
return nil
|
||||||
}, acceptable)
|
}, acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -1402,15 +1405,16 @@ func (s *Redis) ZrevrangebyscoreWithScores(key string, start, stop int64) (val [
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{
|
v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{
|
||||||
Min: strconv.FormatInt(start, 10),
|
Min: strconv.FormatInt(start, 10),
|
||||||
Max: strconv.FormatInt(stop, 10),
|
Max: strconv.FormatInt(stop, 10),
|
||||||
}).Result(); err != nil {
|
}).Result()
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
val = toPairs(v)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = toPairs(v)
|
||||||
|
return nil
|
||||||
}, acceptable)
|
}, acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -1428,17 +1432,18 @@ func (s *Redis) ZrevrangebyscoreWithScoresAndLimit(key string, start, stop int64
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{
|
v, err := conn.ZRevRangeByScoreWithScores(key, red.ZRangeBy{
|
||||||
Min: strconv.FormatInt(start, 10),
|
Min: strconv.FormatInt(start, 10),
|
||||||
Max: strconv.FormatInt(stop, 10),
|
Max: strconv.FormatInt(stop, 10),
|
||||||
Offset: int64(page * size),
|
Offset: int64(page * size),
|
||||||
Count: int64(size),
|
Count: int64(size),
|
||||||
}).Result(); err != nil {
|
}).Result()
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
val = toPairs(v)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = toPairs(v)
|
||||||
|
return nil
|
||||||
}, acceptable)
|
}, acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -63,10 +63,10 @@ func (rl *RedisLock) Acquire() (bool, error) {
|
|||||||
reply, ok := resp.(string)
|
reply, ok := resp.(string)
|
||||||
if ok && reply == "OK" {
|
if ok && reply == "OK" {
|
||||||
return true, nil
|
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) {
|
func (rl *RedisLock) Release() (bool, error) {
|
||||||
@@ -75,11 +75,12 @@ func (rl *RedisLock) Release() (bool, error) {
|
|||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if reply, ok := resp.(int64); !ok {
|
reply, ok := resp.(int64)
|
||||||
|
if !ok {
|
||||||
return false, nil
|
return false, nil
|
||||||
} else {
|
|
||||||
return reply == 1, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return reply == 1, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rl *RedisLock) SetExpire(seconds int) {
|
func (rl *RedisLock) SetExpire(seconds int) {
|
||||||
|
|||||||
@@ -107,10 +107,10 @@ func parseTagName(field reflect.StructField) string {
|
|||||||
key := field.Tag.Get(tagName)
|
key := field.Tag.Get(tagName)
|
||||||
if len(key) == 0 {
|
if len(key) == 0 {
|
||||||
return ""
|
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 {
|
func unmarshalRow(v interface{}, scanner rowsScanner, strict bool) error {
|
||||||
@@ -136,19 +136,21 @@ func unmarshalRow(v interface{}, scanner rowsScanner, strict bool) error {
|
|||||||
reflect.String:
|
reflect.String:
|
||||||
if rve.CanSet() {
|
if rve.CanSet() {
|
||||||
return scanner.Scan(v)
|
return scanner.Scan(v)
|
||||||
} else {
|
|
||||||
return ErrNotSettable
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ErrNotSettable
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
columns, err := scanner.Columns()
|
columns, err := scanner.Columns()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if values, err := mapStructFieldsIntoSlice(rve, columns, strict); err != nil {
|
|
||||||
|
values, err := mapStructFieldsIntoSlice(rve, columns, strict)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
return scanner.Scan(values...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return scanner.Scan(values...)
|
||||||
default:
|
default:
|
||||||
return ErrUnsupportedValueType
|
return ErrUnsupportedValueType
|
||||||
}
|
}
|
||||||
@@ -178,10 +180,10 @@ func unmarshalRows(v interface{}, scanner rowsScanner, strict bool) error {
|
|||||||
if rve.CanSet() {
|
if rve.CanSet() {
|
||||||
if err := scanner.Scan(value); err != nil {
|
if err := scanner.Scan(value); err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
appendFn(reflect.ValueOf(value))
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendFn(reflect.ValueOf(value))
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
return ErrNotSettable
|
return ErrNotSettable
|
||||||
}
|
}
|
||||||
@@ -207,14 +209,15 @@ func unmarshalRows(v interface{}, scanner rowsScanner, strict bool) error {
|
|||||||
|
|
||||||
for scanner.Next() {
|
for scanner.Next() {
|
||||||
value := reflect.New(base)
|
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
|
return err
|
||||||
} else {
|
} else {
|
||||||
if err := scanner.Scan(values...); err != nil {
|
appendFn(value)
|
||||||
return err
|
|
||||||
} else {
|
|
||||||
appendFn(value)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -101,14 +101,15 @@ func (db *commonSqlConn) Prepare(query string) (stmt StmtSession, err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if st, err := conn.Prepare(query); err != nil {
|
st, err := conn.Prepare(query)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
stmt = statement{
|
|
||||||
stmt: st,
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
stmt = statement{
|
||||||
|
stmt: st,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}, db.acceptable)
|
}, db.acceptable)
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -148,9 +149,9 @@ func (db *commonSqlConn) acceptable(err error) bool {
|
|||||||
ok := err == nil || err == sql.ErrNoRows || err == sql.ErrTxDone
|
ok := err == nil || err == sql.ErrNoRows || err == sql.ErrTxDone
|
||||||
if db.accept == nil {
|
if db.accept == nil {
|
||||||
return ok
|
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 {
|
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) {
|
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
|
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 {
|
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) {
|
func begin(db *sql.DB) (trans, error) {
|
||||||
if tx, err := db.Begin(); err != nil {
|
tx, err := db.Begin()
|
||||||
|
if err != nil {
|
||||||
return nil, err
|
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) {
|
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 {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if p := recover(); p != nil {
|
if p := recover(); p != nil {
|
||||||
if e := tx.Rollback(); e != 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 {
|
func TakeOne(valid, or string) string {
|
||||||
if len(valid) > 0 {
|
if len(valid) > 0 {
|
||||||
return valid
|
return valid
|
||||||
} else {
|
|
||||||
return or
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return or
|
||||||
}
|
}
|
||||||
|
|
||||||
func TakeWithPriority(fns ...func() string) string {
|
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 {
|
func WithRefreshIntervalOnFailure(interval time.Duration) ImmutableResourceOption {
|
||||||
return func(resource *ImmutableResource) {
|
return func(resource *ImmutableResource) {
|
||||||
resource.refreshInterval = interval
|
resource.refreshInterval = interval
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ func NewRoutineGroup() *RoutineGroup {
|
|||||||
return new(RoutineGroup)
|
return new(RoutineGroup)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Run runs the given fn in RoutineGroup.
|
||||||
// Don't reference the variables from outside,
|
// Don't reference the variables from outside,
|
||||||
// because outside variables can be changed by other goroutines
|
// because outside variables can be changed by other goroutines
|
||||||
func (g *RoutineGroup) Run(fn func()) {
|
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,
|
// Don't reference the variables from outside,
|
||||||
// because outside variables can be changed by other goroutines
|
// because outside variables can be changed by other goroutines
|
||||||
func (g *RoutineGroup) RunSafe(fn func()) {
|
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() {
|
func (g *RoutineGroup) Wait() {
|
||||||
g.waitGroup.Wait()
|
g.waitGroup.Wait()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ var TracingKey = contextKey("X-Trace")
|
|||||||
// contextKey a type for context key
|
// contextKey a type for context key
|
||||||
type contextKey string
|
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 {
|
func (c contextKey) String() string {
|
||||||
return "trace/tracespec context key " + string(c)
|
return "trace/tracespec context key " + string(c)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -315,12 +315,13 @@ func buildRequest(rs requestSettings) (*http.Request, error) {
|
|||||||
var path string
|
var path string
|
||||||
var query string
|
var query string
|
||||||
if len(rs.requestUri) > 0 {
|
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
|
return nil, err
|
||||||
} else {
|
|
||||||
path = u.Path
|
|
||||||
query = u.RawQuery
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
path = u.Path
|
||||||
|
query = u.RawQuery
|
||||||
} else {
|
} else {
|
||||||
path = r.URL.Path
|
path = r.URL.Path
|
||||||
query = r.URL.RawQuery
|
query = r.URL.RawQuery
|
||||||
@@ -377,10 +378,9 @@ func createTempFile(body []byte) (string, error) {
|
|||||||
tmpFile, err := ioutil.TempFile(os.TempDir(), "go-unit-*.tmp")
|
tmpFile, err := ioutil.TempFile(os.TempDir(), "go-unit-*.tmp")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
} else {
|
|
||||||
tmpFile.Close()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tmpFile.Close()
|
||||||
err = ioutil.WriteFile(tmpFile.Name(), body, os.ModePerm)
|
err = ioutil.WriteFile(tmpFile.Name(), body, os.ModePerm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
|||||||
@@ -114,9 +114,9 @@ func dumpRequest(r *http.Request) string {
|
|||||||
reqContent, err := httputil.DumpRequest(r, true)
|
reqContent, err := httputil.DumpRequest(r, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error()
|
return err.Error()
|
||||||
} else {
|
|
||||||
return string(reqContent)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return string(reqContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
|
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) {
|
func (s mockShedder) Allow() (load.Promise, error) {
|
||||||
if s.allow {
|
if s.allow {
|
||||||
return mockPromise{}, nil
|
return mockPromise{}, nil
|
||||||
} else {
|
|
||||||
return nil, load.ErrServiceOverloaded
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nil, load.ErrServiceOverloaded
|
||||||
}
|
}
|
||||||
|
|
||||||
type mockPromise struct {
|
type mockPromise struct {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ var (
|
|||||||
pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
|
pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Parse parses the request.
|
||||||
func Parse(r *http.Request, v interface{}) error {
|
func Parse(r *http.Request, v interface{}) error {
|
||||||
if err := ParsePath(r, v); err != nil {
|
if err := ParsePath(r, v); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -36,7 +37,7 @@ func Parse(r *http.Request, v interface{}) error {
|
|||||||
return ParseJsonBody(r, v)
|
return ParseJsonBody(r, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parses the form request.
|
// ParseForm parses the form request.
|
||||||
func ParseForm(r *http.Request, v interface{}) error {
|
func ParseForm(r *http.Request, v interface{}) error {
|
||||||
if err := r.ParseForm(); err != nil {
|
if err := r.ParseForm(); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -80,7 +81,7 @@ func ParseHeader(headerValue string) map[string]string {
|
|||||||
return ret
|
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 {
|
func ParseJsonBody(r *http.Request, v interface{}) error {
|
||||||
var reader io.Reader
|
var reader io.Reader
|
||||||
if withJsonBody(r) {
|
if withJsonBody(r) {
|
||||||
@@ -92,7 +93,7 @@ func ParseJsonBody(r *http.Request, v interface{}) error {
|
|||||||
return mapping.UnmarshalJsonReader(reader, v)
|
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
|
// Like http://localhost/bag/:name
|
||||||
func ParsePath(r *http.Request, v interface{}) error {
|
func ParsePath(r *http.Request, v interface{}) error {
|
||||||
vars := context.Vars(r)
|
vars := context.Vars(r)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import "net/http"
|
|||||||
|
|
||||||
const xForwardFor = "X-Forward-For"
|
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 {
|
func GetRemoteAddr(r *http.Request) string {
|
||||||
v := r.Header.Get(xForwardFor)
|
v := r.Header.Get(xForwardFor)
|
||||||
if len(v) > 0 {
|
if len(v) > 0 {
|
||||||
|
|||||||
@@ -43,13 +43,14 @@ func (pr *patRouter) Handle(method, reqPath string, handler http.Handler) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
cleanPath := path.Clean(reqPath)
|
cleanPath := path.Clean(reqPath)
|
||||||
if tree, ok := pr.trees[method]; ok {
|
tree, ok := pr.trees[method]
|
||||||
return tree.Add(cleanPath, handler)
|
if ok {
|
||||||
} else {
|
|
||||||
tree = search.NewTree()
|
|
||||||
pr.trees[method] = tree
|
|
||||||
return tree.Add(cleanPath, handler)
|
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) {
|
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 {
|
if len(allows) > 0 {
|
||||||
return strings.Join(allows, allowMethodSeparator), true
|
return strings.Join(allows, allowMethodSeparator), true
|
||||||
} else {
|
|
||||||
return "", false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
func validMethod(method string) bool {
|
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)
|
token, err = tp.doParseToken(r, second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
|
||||||
tp.incrementCount(second)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tp.incrementCount(second)
|
||||||
} else {
|
} else {
|
||||||
tp.incrementCount(first)
|
tp.incrementCount(first)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func DocCommand(c *cli.Context) error {
|
|||||||
|
|
||||||
files, err := filePathWalkDir(dir)
|
files, err := filePathWalkDir(dir)
|
||||||
if err != nil {
|
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 + "/")
|
err = os.RemoveAll(dir + "/" + docDir + "/")
|
||||||
@@ -31,7 +31,7 @@ func DocCommand(c *cli.Context) error {
|
|||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
api, err := parser.Parse(f)
|
api, err := parser.Parse(f)
|
||||||
if err != nil {
|
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)
|
index := strings.Index(f, dir)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package gogen
|
package gogen
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"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 {
|
func writeType(writer io.Writer, tp spec.Type) error {
|
||||||
structType, ok := tp.(spec.DefineStruct)
|
structType, ok := tp.(spec.DefineStruct)
|
||||||
if !ok {
|
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()))
|
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 member.IsInline {
|
||||||
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
|
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil {
|
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 {
|
if ok {
|
||||||
return c.writeMembers(writer, pointType.Type, indent)
|
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 {
|
for _, member := range definedType.Members {
|
||||||
|
|||||||
@@ -203,41 +203,40 @@ func (e *defaultExpr) IsNotNil() bool {
|
|||||||
|
|
||||||
func EqualDoc(spec1, spec2 Spec) bool {
|
func EqualDoc(spec1, spec2 Spec) bool {
|
||||||
if spec1 == nil {
|
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 false
|
||||||
}
|
}
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,8 +294,10 @@ func (v *ApiVisitor) getHiddenTokensToLeft(t TokenStream, channel int, containsC
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
list = append(list, v.newExprWithToken(each))
|
list = append(list, v.newExprWithToken(each))
|
||||||
}
|
}
|
||||||
|
|
||||||
return list
|
return list
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,6 +308,7 @@ func (v *ApiVisitor) getHiddenTokensToRight(t TokenStream, channel int) []Expr {
|
|||||||
for _, each := range tokens {
|
for _, each := range tokens {
|
||||||
list = append(list, v.newExprWithToken(each))
|
list = append(list, v.newExprWithToken(each))
|
||||||
}
|
}
|
||||||
|
|
||||||
return list
|
return list
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -314,6 +316,7 @@ func (v *ApiVisitor) exportCheck(expr Expr) {
|
|||||||
if expr == nil || !expr.IsNotNil() {
|
if expr == nil || !expr.IsNotNil() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if api.IsBasicType(expr.Text()) {
|
if api.IsBasicType(expr.Text()) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -508,9 +508,9 @@ func (s *ServiceRoute) Format() error {
|
|||||||
func (s *ServiceRoute) GetHandler() Expr {
|
func (s *ServiceRoute) GetHandler() Expr {
|
||||||
if s.AtHandler != nil {
|
if s.AtHandler != nil {
|
||||||
return s.AtHandler.Name
|
return s.AtHandler.Name
|
||||||
} else {
|
|
||||||
return s.AtServer.Kv.Get("handler")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return s.AtServer.Kv.Get("handler")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ServiceApi) Format() error {
|
func (a *ServiceApi) Format() error {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package parser
|
package parser
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"unicode"
|
"unicode"
|
||||||
@@ -101,7 +100,7 @@ func (p parser) fillTypes() error {
|
|||||||
Docs: p.stringExprs(v.Doc()),
|
Docs: p.stringExprs(v.Doc()),
|
||||||
})
|
})
|
||||||
default:
|
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)
|
tp, err := p.findDefinedType(v.RawName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
member.Type = *tp
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
member.Type = *tp
|
||||||
}
|
}
|
||||||
members = append(members, member)
|
members = append(members, member)
|
||||||
}
|
}
|
||||||
v.Members = members
|
v.Members = members
|
||||||
types = append(types, v)
|
types = append(types, v)
|
||||||
default:
|
default:
|
||||||
return errors.New(fmt.Sprintf("unknown type %+v", v))
|
return fmt.Errorf("unknown type %+v", v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
p.spec.Types = types
|
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 {
|
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()
|
raw := v.Literal.Text()
|
||||||
if api.IsBasicType(raw) {
|
if api.IsBasicType(raw) {
|
||||||
return spec.PrimitiveType{RawName: raw}
|
return spec.PrimitiveType{RawName: raw}
|
||||||
} else {
|
|
||||||
return spec.DefineStruct{RawName: raw}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return spec.DefineStruct{RawName: raw}
|
||||||
case *ast.Interface:
|
case *ast.Interface:
|
||||||
return spec.InterfaceType{RawName: v.Literal.Text()}
|
return spec.InterfaceType{RawName: v.Literal.Text()}
|
||||||
case *ast.Map:
|
case *ast.Map:
|
||||||
@@ -185,9 +185,9 @@ func (p parser) astTypeToSpec(in ast.DataType) spec.Type {
|
|||||||
raw := v.Name.Text()
|
raw := v.Name.Text()
|
||||||
if api.IsBasicType(raw) {
|
if api.IsBasicType(raw) {
|
||||||
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.PrimitiveType{RawName: 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))
|
panic(fmt.Sprintf("unspported type %+v", in))
|
||||||
@@ -246,8 +246,8 @@ func (p parser) fillService() error {
|
|||||||
|
|
||||||
for _, char := range route.Handler {
|
for _, char := range route.Handler {
|
||||||
if !unicode.IsDigit(char) && !unicode.IsLetter(char) {
|
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",
|
return fmt.Errorf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
|
||||||
route.Path, route.Handler))
|
route.Path, route.Handler)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,7 +278,7 @@ func (p parser) fillService() error {
|
|||||||
|
|
||||||
name := item.ServiceApi.Name.Text()
|
name := item.ServiceApi.Name.Text()
|
||||||
if len(p.spec.Service.Name) > 0 && p.spec.Service.Name != name {
|
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
|
p.spec.Service.Name = name
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -160,11 +160,11 @@ func pathForRoute(route spec.Route, group spec.Group) string {
|
|||||||
prefix := group.GetAnnotation("pathPrefix")
|
prefix := group.GetAnnotation("pathPrefix")
|
||||||
if len(prefix) == 0 {
|
if len(prefix) == 0 {
|
||||||
return "\"" + route.Path + "\""
|
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 {
|
func pathHasParams(route spec.Route) bool {
|
||||||
|
|||||||
@@ -146,7 +146,8 @@ func writeMembers(writer io.Writer, tp spec.Type, isParam bool) error {
|
|||||||
if ok {
|
if ok {
|
||||||
return writeMembers(writer, pointType.Type, isParam)
|
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()
|
members := definedType.GetBodyMembers()
|
||||||
|
|||||||
@@ -19,20 +19,20 @@ func genImports(withCache, timeImport bool) (string, error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
return buffer.String(), nil
|
return buffer.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
return buffer.String(), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
unSupportDDL = errors.New("unexpected type")
|
errUnsupportDDL = errors.New("unexpected type")
|
||||||
tableBodyIsNotFound = errors.New("create table spec not found")
|
errTableBodyNotFound = errors.New("create table spec not found")
|
||||||
errPrimaryKey = errors.New("unexpected join primary key")
|
errPrimaryKey = errors.New("unexpected join primary key")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ func Parse(ddl string) (*Table, error) {
|
|||||||
|
|
||||||
ddlStmt, ok := stmt.(*sqlparser.DDL)
|
ddlStmt, ok := stmt.(*sqlparser.DDL)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, unSupportDDL
|
return nil, errUnsupportDDL
|
||||||
}
|
}
|
||||||
|
|
||||||
action := ddlStmt.Action
|
action := ddlStmt.Action
|
||||||
@@ -63,7 +63,7 @@ func Parse(ddl string) (*Table, error) {
|
|||||||
tableName := ddlStmt.NewName.Name.String()
|
tableName := ddlStmt.NewName.Name.String()
|
||||||
tableSpec := ddlStmt.TableSpec
|
tableSpec := ddlStmt.TableSpec
|
||||||
if tableSpec == nil {
|
if tableSpec == nil {
|
||||||
return nil, tableBodyIsNotFound
|
return nil, errTableBodyNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
columns := tableSpec.Columns
|
columns := tableSpec.Columns
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func TestParsePlainText(t *testing.T) {
|
|||||||
|
|
||||||
func TestParseSelect(t *testing.T) {
|
func TestParseSelect(t *testing.T) {
|
||||||
_, err := Parse("select * from user")
|
_, err := Parse("select * from user")
|
||||||
assert.Equal(t, unSupportDDL, err)
|
assert.Equal(t, errUnsupportDDL, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseCreateTable(t *testing.T) {
|
func TestParseCreateTable(t *testing.T) {
|
||||||
|
|||||||
@@ -39,10 +39,9 @@ func forChksumHandler(file string, next http.Handler) http.Handler {
|
|||||||
if chksum == r.Header.Get(contentMd5Header) {
|
if chksum == r.Header.Get(contentMd5Header) {
|
||||||
w.WriteHeader(http.StatusNotModified)
|
w.WriteHeader(http.StatusNotModified)
|
||||||
return
|
return
|
||||||
} else {
|
|
||||||
w.Header().Set(contentMd5Header, chksum)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
w.Header().Set(contentMd5Header, chksum)
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,21 +7,19 @@ import (
|
|||||||
"github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
|
"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")
|
var errModuleCheck = errors.New("the work directory must be found in the go mod or the $GOPATH")
|
||||||
|
|
||||||
type (
|
type ProjectContext struct {
|
||||||
ProjectContext struct {
|
WorkDir string
|
||||||
WorkDir string
|
// Name is the root name of the project
|
||||||
// Name is the root name of the project
|
// eg: go-zero、greet
|
||||||
// eg: go-zero、greet
|
Name string
|
||||||
Name string
|
// Path identifies which module a project belongs to, which is module value if it's a go mod project,
|
||||||
// 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
|
||||||
// or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet
|
Path string
|
||||||
Path string
|
// Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
|
||||||
// Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
|
Dir string
|
||||||
Dir string
|
}
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Prepare checks the project which module belongs to,and returns the path and module.
|
// 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,
|
// workDir parameter is the directory of the source of generating code,
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) {
|
|||||||
goPath := buildContext.GOPATH
|
goPath := buildContext.GOPATH
|
||||||
goSrc := filepath.Join(goPath, "src")
|
goSrc := filepath.Join(goPath, "src")
|
||||||
if !util.FileExists(goSrc) {
|
if !util.FileExists(goSrc) {
|
||||||
return nil, moduleCheckErr
|
return nil, errModuleCheck
|
||||||
}
|
}
|
||||||
|
|
||||||
wd, err := filepath.Abs(workDir)
|
wd, err := filepath.Abs(workDir)
|
||||||
@@ -34,7 +34,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !strings.HasPrefix(wd, goSrc) {
|
if !strings.HasPrefix(wd, goSrc) {
|
||||||
return nil, moduleCheckErr
|
return nil, errModuleCheck
|
||||||
}
|
}
|
||||||
|
|
||||||
projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator))
|
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)
|
pick := atomic.LoadInt64(&c2.pick)
|
||||||
if start-pick > forcePick && atomic.CompareAndSwapInt64(&c2.pick, pick, start) {
|
if start-pick > forcePick && atomic.CompareAndSwapInt64(&c2.pick, pick, start) {
|
||||||
return c2
|
return c2
|
||||||
} else {
|
|
||||||
atomic.StoreInt64(&c1.pick, start)
|
|
||||||
return c1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
atomic.StoreInt64(&c1.pick, start)
|
||||||
|
return c1
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *p2cPicker) logStats() {
|
func (p *p2cPicker) logStats() {
|
||||||
@@ -196,7 +196,7 @@ func (c *subConn) load() int64 {
|
|||||||
load := lag * (atomic.LoadInt64(&c.inflight) + 1)
|
load := lag * (atomic.LoadInt64(&c.inflight) + 1)
|
||||||
if load == 0 {
|
if load == 0 {
|
||||||
return penalty
|
return penalty
|
||||||
} else {
|
|
||||||
return load
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return load
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ func subset(set []string, sub int) []string {
|
|||||||
})
|
})
|
||||||
if len(set) <= sub {
|
if len(set) <= sub {
|
||||||
return set
|
return set
|
||||||
} else {
|
|
||||||
return set[:sub]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return set[:sub]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,9 +62,9 @@ type mockedShedder struct {
|
|||||||
func (m mockedShedder) Allow() (load.Promise, error) {
|
func (m mockedShedder) Allow() (load.Promise, error) {
|
||||||
if m.allow {
|
if m.allow {
|
||||||
return mockedPromise{}, nil
|
return mockedPromise{}, nil
|
||||||
} else {
|
|
||||||
return nil, load.ErrServiceOverloaded
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nil, load.ErrServiceOverloaded
|
||||||
}
|
}
|
||||||
|
|
||||||
type mockedPromise struct {
|
type mockedPromise struct {
|
||||||
|
|||||||
@@ -109,9 +109,9 @@ func figureOutListenOn(listenOn string) string {
|
|||||||
}
|
}
|
||||||
if len(ip) == 0 {
|
if len(ip) == 0 {
|
||||||
return listenOn
|
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 {
|
func setupInterceptors(server internal.Server, c RpcServerConf, metrics *stat.Metrics) error {
|
||||||
|
|||||||
Reference in New Issue
Block a user