Documentation ¶
Index ¶
- Variables
- func HandlePanic(fn func() error) (err error)
- func RunCommand(command *cobra.Command) int
- func ShowError(err error)
- func UnmarshalJSONInterface(js []byte, fn func(typeName string) (concrete interface{}, err error)) error
- func UnmarshalYAMLInterface(unmarshal func(interface{}) error, ...) error
- type ExitCode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var InvalidArgument = ExitCode{ Code: 128, // contains filtered or unexported fields }
Functions ¶
func HandlePanic ¶
func RunCommand ¶
func UnmarshalJSONInterface ¶
func UnmarshalJSONInterface(js []byte, fn func(typeName string) (concrete interface{}, err error)) error
UnmarshalJSONInterface unmarshal abstract data with concrete type. Input json MUST contain "type" field. The concrete object creates in according to the specified type.
Input: {"type": "foo", "extra-keys": "..."} Output: &FooType{...} if type is "foo". &BarType{...} if type is "bar". ... Usage: var data AbstractType = UnmarshalJSONInterface(js, initializer)
This method needs when you want to unmarshal a struct contains interfaces. For example, following code will raise an error because encoding/json package can not unmarshal interface type. UnmarshalJSONInterface() provides a way to solve this problem. For details, see example_json_test.go.
type AbstractType interface { SomeMethods() } type Config struct { Type string Data AbstractType } func main() { js := []byte(`{"type":"foo", "data":{"a":1,"b":"2"}}`) conf := &Config{} // json: cannot unmarshal object into Go struct field Config.Data of type main.AbstractType err := json.Unmarshal(js, conf) if err != nil { panic(err) } }
Example ¶
package main import ( "encoding/json" "errors" "fmt" "reflect" ) type Foo struct { // NOTE: json.Unmarshal() can not unmarshal the Abstract interface directly. Bar AbstractUnmarshaller } type Abstract interface{ Method() } type Concrete1 struct{ C1 string } type Concrete2 struct{ C2 string } func (c *Concrete1) Method() {} func (c *Concrete2) Method() {} type AbstractUnmarshaller struct { Data Abstract } func (a *AbstractUnmarshaller) UnmarshalJSON(js []byte) error { return UnmarshalJSONInterface(js, func(typeName string) (interface{}, error) { switch typeName { case "concrete1": a.Data = &Concrete1{} case "concrete2": a.Data = &Concrete2{} default: return nil, errors.New("invalid type") } return a.Data, nil }) } func main() { var foo Foo js := []byte(`{"bar": {"type": "concrete1", "c1": "ok"}}`) err := json.Unmarshal(js, &foo) if err != nil { panic(err) } fmt.Println(reflect.TypeOf(foo.Bar.Data)) fmt.Printf("%+v\n", foo.Bar.Data) }
Output: *cmdutils.Concrete1 &{C1:ok}
Types ¶
Click to show internal directories.
Click to hide internal directories.