XML/JSON/YAML/ProtoBuf rendering

  1. func main() {
  2. r := gin.Default()
  3. // gin.H is a shortcut for map[string]interface{}
  4. r.GET("/someJSON", func(c *gin.Context) {
  5. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  6. })
  7. r.GET("/moreJSON", func(c *gin.Context) {
  8. // You also can use a struct
  9. var msg struct {
  10. Name string `json:"user"`
  11. Message string
  12. Number int
  13. }
  14. msg.Name = "Lena"
  15. msg.Message = "hey"
  16. msg.Number = 123
  17. // Note that msg.Name becomes "user" in the JSON
  18. // Will output : {"user": "Lena", "Message": "hey", "Number": 123}
  19. c.JSON(http.StatusOK, msg)
  20. })
  21. r.GET("/someXML", func(c *gin.Context) {
  22. c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  23. })
  24. r.GET("/someYAML", func(c *gin.Context) {
  25. c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  26. })
  27. r.GET("/someProtoBuf", func(c *gin.Context) {
  28. reps := []int64{int64(1), int64(2)}
  29. label := "test"
  30. // The specific definition of protobuf is written in the testdata/protoexample file.
  31. data := &protoexample.Test{
  32. Label: &label,
  33. Reps: reps,
  34. }
  35. // Note that data becomes binary data in the response
  36. // Will output protoexample.Test protobuf serialized data
  37. c.ProtoBuf(http.StatusOK, data)
  38. })
  39. // Listen and serve on 0.0.0.0:8080
  40. r.Run(":8080")
  41. }

Last modified March 7, 2020 : add blog dir (#115) (f46734b)