首页 > 其他分享 >Gin-JSON,ProtoBuf渲染

Gin-JSON,ProtoBuf渲染

时间:2022-10-25 11:55:52浏览次数:44  
标签:ProtoBuf JSON user func gin msg Gin string

1. 输出json和protobuf

新建user.proto文件

 
syntax = "proto3";
option go_package = ".;proto";

message Teacher {
    string name = 1;
    repeated string course = 2;
}

 go代码,启动Gin

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "start/gin_t/proto"
)

func main() {
    r := gin.Default()
    // gin.H is a shortcut for map[string]interface{}
    r.GET("/someJSON", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })
    r.GET("/moreJSON", func(c *gin.Context) {
        // You also can use a struct
        var msg struct {
            Name    string `json:"user"`
            Message string
            Number  int
        }
        msg.Name = "Lena"
        msg.Message = "hey"
        msg.Number = 123
        // Note that msg.Name becomes "user" in the JSON
        // Will output  :   {"user": "Lena", "Message": "hey", "Number": 123}
        c.JSON(http.StatusOK, msg)
    })

    r.GET("/someProtoBuf", func(c *gin.Context) {
        courses := []string{"python", "django", "go"}
        // The specific definition of protobuf is written in the testdata/protoexample file.
        data := &proto.Teacher{
            Name: "bobby",
            Course:  courses,
        }
        // Note that data becomes binary data in the response
        // Will output protoexample.Test protobuf serialized data
        c.ProtoBuf(http.StatusOK, data)
    })
    // Listen and serve on 0.0.0.0:8080
    r.Run(":8083")
}

 如何解析,拿python代码作为示例

import requests
# from requests_test.proto import user_pb2
#
# user = user_pb2.Teacher()
#
# rsp = requests.get("http://127.0.0.1:8083/someProtoBuf")
# user.ParseFromString(rsp.content)
# print(user.name, user.course)

  

2. PureJSON

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

 
func main() {
    r := gin.Default()
    
    // Serves unicode entities
    r.GET("/json", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "html": "<b>Hello, world!</b>",
        })
    })
    
    // Serves literal characters
    r.GET("/purejson", func(c *gin.Context) {
        c.PureJSON(200, gin.H{
            "html": "<b>Hello, world!</b>",
        })
    })
    
    // listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}

  

 

标签:ProtoBuf,JSON,user,func,gin,msg,Gin,string
From: https://www.cnblogs.com/wlike/p/16824384.html

相关文章