Guest User

Untitled

a guest
Oct 17th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. )
  8.  
  9. // Event to record
  10. type Event struct {
  11. ID string `json:"id"`
  12. Priority int `json:"priority"`
  13. Type string `json:"event_type,omitempty"`
  14. Tags []string `json:"tags,omitempty"`
  15. Extra map[string]string `json:"extra,omitempty"`
  16. }
  17.  
  18. // User of the system
  19. type User struct {
  20. ID string `json:"id"`
  21. Name string `json:"name"`
  22. }
  23.  
  24. func marshalEvent(e Event) ([]byte, error) {
  25. bin, err := json.MarshalIndent(&e, "", " ")
  26.  
  27. if err != nil {
  28. return nil, err
  29. }
  30.  
  31. return bin, nil
  32. }
  33.  
  34. func marshalAndPrintEvent(e Event) error {
  35. bin, err := marshalEvent(e)
  36.  
  37. if err != nil {
  38. return err
  39. }
  40.  
  41. fmt.Println("Event data from object:")
  42. fmt.Println(string(bin))
  43. fmt.Println("")
  44. return nil
  45. }
  46. func unmarshalUser(user []byte) (User, error) {
  47. var u User
  48. err := json.Unmarshal(user, &u)
  49. return u, err
  50. }
  51.  
  52. func unmarshalUserAndPrintName(userJSON string) error {
  53. var user, err = unmarshalUser([]byte(userJSON))
  54.  
  55. if err != nil {
  56. return err
  57. }
  58.  
  59. fmt.Printf("User name: %s\n", user.Name)
  60. return nil
  61. }
  62.  
  63. var example = Event{
  64. ID: "shutdown",
  65. Priority: 4,
  66. Tags: []string{
  67. "forced",
  68. "remote",
  69. },
  70. Extra: map[string]string{
  71. "user": "henrique",
  72. },
  73. }
  74.  
  75. var userJSON = `{
  76. "id": "abcd",
  77. "name": "Bruna"
  78. }`
  79.  
  80. func main() {
  81. if err := marshalAndPrintEvent(example); err != nil {
  82. log.Fatal(err)
  83. }
  84.  
  85. if err := unmarshalUserAndPrintName(userJSON); err != nil {
  86. log.Fatal(err)
  87. }
  88. }
Add Comment
Please, Sign In to add comment