Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "log"
- )
- // Event to record
- type Event struct {
- ID string `json:"id"`
- Priority int `json:"priority"`
- Type string `json:"event_type,omitempty"`
- Tags []string `json:"tags,omitempty"`
- Extra map[string]string `json:"extra,omitempty"`
- }
- // User of the system
- type User struct {
- ID string `json:"id"`
- Name string `json:"name"`
- }
- func marshalEvent(e Event) ([]byte, error) {
- bin, err := json.MarshalIndent(&e, "", " ")
- if err != nil {
- return nil, err
- }
- return bin, nil
- }
- func marshalAndPrintEvent(e Event) error {
- bin, err := marshalEvent(e)
- if err != nil {
- return err
- }
- fmt.Println("Event data from object:")
- fmt.Println(string(bin))
- fmt.Println("")
- return nil
- }
- func unmarshalUser(user []byte) (User, error) {
- var u User
- err := json.Unmarshal(user, &u)
- return u, err
- }
- func unmarshalUserAndPrintName(userJSON string) error {
- var user, err = unmarshalUser([]byte(userJSON))
- if err != nil {
- return err
- }
- fmt.Printf("User name: %s\n", user.Name)
- return nil
- }
- var example = Event{
- ID: "shutdown",
- Priority: 4,
- Tags: []string{
- "forced",
- "remote",
- },
- Extra: map[string]string{
- "user": "henrique",
- },
- }
- var userJSON = `{
- "id": "abcd",
- "name": "Bruna"
- }`
- func main() {
- if err := marshalAndPrintEvent(example); err != nil {
- log.Fatal(err)
- }
- if err := unmarshalUserAndPrintName(userJSON); err != nil {
- log.Fatal(err)
- }
- }
Add Comment
Please, Sign In to add comment