Files
Cyrene_v2/plugins/tools/io/args.go
T

71 lines
1.5 KiB
Go

package io
import (
"encoding/json"
)
// argString returns the string value of args[key], or "" when absent or of
// another type.
func argString(args map[string]any, key string) string {
if args == nil {
return ""
}
s, _ := args[key].(string)
return s
}
// argInt returns the integer value of args[key] and whether it was a number.
func argInt(args map[string]any, key string) (int, bool) {
if args == nil {
return 0, false
}
return toInt(args[key])
}
// argStringMap coerces a JSON object argument to a string map, accepting both
// map[string]any and map[string]string inputs, dropping non-string values.
func argStringMap(args map[string]any, key string) map[string]string {
out := map[string]string{}
if args == nil {
return out
}
switch v := args[key].(type) {
case map[string]any:
for k, val := range v {
if s, ok := val.(string); ok {
out[k] = s
}
}
case map[string]string:
for k, val := range v {
out[k] = val
}
}
return out
}
// toInt converts a decoded-JSON number (float64 / json.Number) or a Go integer
// to an int, reporting whether the conversion succeeded.
func toInt(v any) (int, bool) {
switch x := v.(type) {
case int:
return x, true
case int32:
return int(x), true
case int64:
return int(x), true
case float32:
return int(x), true
case float64:
return int(x), true
case json.Number:
n, err := x.Int64()
if err != nil {
return 0, false
}
return int(n), true
default:
return 0, false
}
}