You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
133 lines
2.4 KiB
133 lines
2.4 KiB
package types |
|
|
|
import ( |
|
"fmt" |
|
|
|
"github.com/spf13/cast" |
|
) |
|
|
|
const ( |
|
inputCacheKey = "__$cache__" |
|
) |
|
|
|
type Input map[string]any |
|
|
|
// getCache 避免多线程读写cache map |
|
func (in Input) getCache(k string) (r any, ok bool) { |
|
if in == nil { |
|
return |
|
} |
|
c, ok := in[inputCacheKey] |
|
if !ok { |
|
return |
|
} |
|
r, ok = c.(map[string]any)[k] |
|
return |
|
} |
|
|
|
func (in Input) setCache(k string, v any) { |
|
if in == nil { |
|
return |
|
} |
|
c, ok := in[inputCacheKey] |
|
if !ok { |
|
c = make(map[string]any, 4) |
|
in[inputCacheKey] = c |
|
} |
|
c.(map[string]any)[k] = v |
|
} |
|
|
|
func (in Input) get(k string, t string) (r any) { |
|
if in == nil { |
|
panic(fmt.Errorf("input %s type %s not provide", k, t)) |
|
} |
|
r, ok := in[k] |
|
if !ok { |
|
panic(fmt.Errorf("input %s type %s not provide", k, t)) |
|
} |
|
return |
|
} |
|
|
|
func (in Input) Float(k string) (v float64) { |
|
if r, ok := in.getCache(k); ok { |
|
if v, ok = r.(float64); ok { |
|
return |
|
} |
|
} |
|
v, err := cast.ToFloat64E(in.get(k, "float")) |
|
if err != nil { |
|
panic(fmt.Errorf("input float parse error: %s", k)) |
|
} |
|
in.setCache(k, v) |
|
return |
|
} |
|
|
|
func (in Input) Int(k string) (v int) { |
|
if r, ok := in.getCache(k); ok { |
|
if v, ok = r.(int); ok { |
|
return |
|
} |
|
} |
|
v, err := cast.ToIntE(in.get(k, "int")) |
|
if err != nil { |
|
panic(fmt.Errorf("input int parse error: %s", k)) |
|
} |
|
in.setCache(k, v) |
|
return |
|
} |
|
|
|
func (in Input) Int16(k string) (v int16) { |
|
if r, ok := in.getCache(k); ok { |
|
if v, ok = r.(int16); ok { |
|
return |
|
} |
|
} |
|
v, err := cast.ToInt16E(in.get(k, "int16")) |
|
if err != nil { |
|
panic(fmt.Errorf("input int16 parse error: %s", k)) |
|
} |
|
in.setCache(k, v) |
|
return |
|
} |
|
|
|
func (in Input) String(k string) (v string) { |
|
// cacheK := "str:" + k |
|
// if r, ok := in.getCache(cacheK); ok { |
|
// if v, ok = r.(string); ok { |
|
// return |
|
// } |
|
// } |
|
v, err := cast.ToStringE(in.get(k, "string")) |
|
if err != nil { |
|
panic(fmt.Errorf("input string parse error: %s", k)) |
|
} |
|
// in.setCache(cacheK, v) |
|
return |
|
} |
|
|
|
// 参数类型 |
|
type InputType int8 |
|
|
|
const ( |
|
_ InputType = iota |
|
InputTypeBool |
|
InputTypeFloat |
|
InputTypeUFloat |
|
InputTypeInt |
|
InputTypeUInt |
|
InputTypeString |
|
InputTypeSelect // 单选 |
|
InputTypeCheckBox // 多选 |
|
) |
|
|
|
type InputArg struct { |
|
Name string `json:"name"` |
|
Desc string `json:"desc"` |
|
Type InputType `json:"type"` // 参数类型 |
|
Options []InputOption `json:"options"` // 单选/多选选项列表 |
|
} |
|
|
|
type InputOption struct { |
|
Name string `json:"name"` |
|
Desc string `json:"desc"` |
|
}
|
|
|