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.
85 lines
1.5 KiB
85 lines
1.5 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 { |
|
return r.(float64) |
|
} |
|
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 { |
|
return r.(int) |
|
} |
|
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 { |
|
return r.(int16) |
|
} |
|
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 |
|
}
|
|
|