jsonenums/example/shirtsize.go

86 lines
1.2 KiB
Go
Raw Normal View History

2015-01-29 11:35:15 +01:00
// 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.
2015-01-29 17:00:50 +01:00
package main
import (
"encoding/json"
2015-01-31 12:21:55 +01:00
"fmt"
2015-01-29 17:00:50 +01:00
"log"
"os"
2015-01-31 12:21:55 +01:00
"strings"
2015-01-29 17:00:50 +01:00
)
2015-01-29 11:35:15 +01:00
type TestCasing int
const (
caseMadnessA TestCasing = iota
caseMaDnEEsB
normalCaseExample
)
2015-01-29 11:35:15 +01:00
//go:generate jsonenums -type=ShirtSize
2015-01-29 11:35:15 +01:00
type ShirtSize byte
const (
NA ShirtSize = iota
XS
S
M
L
XL
)
//go:generate jsonenums -type=WeekDay
2015-01-29 11:35:15 +01:00
type WeekDay int
const (
Monday WeekDay = iota
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
)
2015-01-29 17:00:50 +01:00
2015-01-31 12:21:55 +01:00
func (d WeekDay) String() string {
switch d {
case Monday:
return "Dilluns"
case Tuesday:
return "Dimarts"
case Wednesday:
return "Dimecres"
case Thursday:
return "Dijous"
case Friday:
return "Divendres"
case Saturday:
return "Dissabte"
case Sunday:
return "Diumenge"
default:
return "invalid WeekDay"
}
}
2015-01-29 17:00:50 +01:00
func main() {
v := struct {
Size ShirtSize
Day WeekDay
}{M, Friday}
if err := json.NewEncoder(os.Stdout).Encode(v); err != nil {
log.Fatal(err)
}
2015-01-31 12:21:55 +01:00
input := `{"Size":"XL", "Day":"Dimarts"}`
if err := json.NewDecoder(strings.NewReader(input)).Decode(&v); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded %s as %+v\n", input, v)
2015-01-29 17:00:50 +01:00
}