55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
![]() |
// Copyright 2014 The Go Authors. All rights reserved.
|
||
|
// Use of this source code is governed by a BSD-style
|
||
|
// license that can be found in the LICENSE file.
|
||
|
|
||
|
// Added as a .go file to avoid embedding issues of the template.
|
||
|
|
||
|
package main
|
||
|
|
||
|
import "text/template"
|
||
|
|
||
|
var generatedTmpl = template.Must(template.New("generated").Parse(`
|
||
|
// generated by jsonenums {{.Command}}; DO NOT EDIT
|
||
|
|
||
|
package {{.PackageName}}
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
{{range $typename, $values := .TypesAndValues}}
|
||
|
func (r {{$typename}}) String() string {
|
||
|
switch r {
|
||
|
{{range $values}}
|
||
|
case {{.}}:
|
||
|
return "{{.}}"
|
||
|
{{end}}
|
||
|
default:
|
||
|
return "unknown {{$typename}}"
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (r {{$typename}}) MarshalJSON() ([]byte, error) {
|
||
|
return json.Marshal(r.String())
|
||
|
}
|
||
|
|
||
|
func (r *{{$typename}}) UnmarshalJSON(data []byte) error {
|
||
|
var s string
|
||
|
if err := json.Unmarshal(data, &s); err != nil {
|
||
|
return fmt.Errorf("{{$typename}} should be a string, got %s", data)
|
||
|
}
|
||
|
switch s {
|
||
|
{{range $values}}
|
||
|
case "{{.}}":
|
||
|
*r = {{.}}
|
||
|
{{end}}
|
||
|
default:
|
||
|
return fmt.Errorf("invalid {{$typename}} %q", s)
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
{{end}}
|
||
|
`))
|