1. 输出json和protobuf

新建user.proto文件

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. message Teacher {
  4. string name = 1;
  5. repeated string course = 2;
  6. }
  7. package main
  8. import (
  9. "github.com/gin-gonic/gin"
  10. "net/http"
  11. "start/gin_t/proto"
  12. )
  13. func main() {
  14. r := gin.Default()
  15. // gin.H is a shortcut for map[string]interface{}
  16. r.GET("/someJSON", func(c *gin.Context) {
  17. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  18. })
  19. r.GET("/moreJSON", func(c *gin.Context) {
  20. // You also can use a struct
  21. var msg struct {
  22. Name string `json:"user"`
  23. Message string
  24. Number int
  25. }
  26. msg.Name = "Lena"
  27. msg.Message = "hey"
  28. msg.Number = 123
  29. // Note that msg.Name becomes "user" in the JSON
  30. // Will output : {"user": "Lena", "Message": "hey", "Number": 123}
  31. c.JSON(http.StatusOK, msg)
  32. })
  33. r.GET("/someProtoBuf", func(c *gin.Context) {
  34. courses := []string{"python", "django", "go"}
  35. // The specific definition of protobuf is written in the testdata/protoexample file.
  36. data := &proto.Teacher{
  37. Name: "bobby",
  38. Course: courses,
  39. }
  40. // Note that data becomes binary data in the response
  41. // Will output protoexample.Test protobuf serialized data
  42. c.ProtoBuf(http.StatusOK, data)
  43. })
  44. // Listen and serve on 0.0.0.0:8080
  45. r.Run(":8083")
  46. }

2. PureJSON

通常情况下,JSON会将特殊的HTML字符替换为对应的unicode字符,比如<替换为\u003c,如果想原样输出html,则使用PureJSON

  1. func main() {
  2. r := gin.Default()
  3. // Serves unicode entities
  4. r.GET("/json", func(c *gin.Context) {
  5. c.JSON(200, gin.H{
  6. "html": "<b>Hello, world!</b>",
  7. })
  8. })
  9. // Serves literal characters
  10. r.GET("/purejson", func(c *gin.Context) {
  11. c.PureJSON(200, gin.H{
  12. "html": "<b>Hello, world!</b>",
  13. })
  14. })
  15. // listen and serve on 0.0.0.0:8080
  16. r.Run(":8080")
  17. }