Back-end development summary (1): front-end and back-end data transmission

Json(Javascript object Nantation)It is a data exchange format, often used for front-end and back-end data transmission. Either end converts the data into jsona string, and the other end parses the string into a corresponding data structure, such as string,strcutan object. In actual projects, the data structure encoded into a json string is often a slice type

Article reference: https://blog.csdn.net/zxy_666/article/details/80173288

Go conversion to json format: https://go.dev/blog/json

1 Backend --> Frontend

The go language itself provides us with a json toolkit ”encoding/json”. Reference: https://studyglang.com/articles/6742

1.1 Json Marshal

state := &entity.AddStateoptions{
    
    
   DeviceName:  "d11",
   Lngitude:   100.076690123,
   Latitude:    10.023512345,
   Altitude:    4000.023512345,
   Temperature: 30.123,
   Intensity:   1000.023,
}
bytes, err := json.Marshal(state) // 将struct转化成byte格式
//[]byte类型,转化成string类型便于查看
fmt.Println(string(bytes))

1.2 JSON output rules for front-end and back-end interactions

We need to unify the external jsoninformation output

{
    
    
   "code": 5000,
   "message": "message",
   "data":""
}

The backend needs to use a web framework, such as gin, to output the return result in Json format to the frontend at the controller layer

// gin.H就是一个map用以简化生成 json 的方式
// c.JSON(状态码,message)
c.JSON(http.StatusOK, gin.H{
    
    
            "code": 0,
            "message": "正常",
            "dataset": gin.H{
    
    
                "name": "测试接口"
            },
        })

code, messageMost of the time it is the default value, only when a specific interface returns specific information, the interface can be encapsulated

package httprsp

// gin响应错误消息体封装
type GinErrorRsp struct {
    
    
	Code int64  `json:"code"`
	Msg  string `json:"msg"`
}

const (
	BadRequest int64 = 4000
	UnauthorizedRequest int64 = 4001
	InternalServerError int64 = 5000
)

var (
	// Ok OK
	Ok GinErrorRsp = GinErrorRsp{
    
    2000, "ok"}
	// Unauthorized 未授权请求
	Unauthorized GinErrorRsp = GinErrorRsp{
    
    4001, "unauthorized request"}
	// Forbidden 请求拒绝
	Forbidden GinErrorRsp = GinErrorRsp{
    
    4003, "forbidden"}
)

func NewRequestParamsErrorRsp() GinErrorRsp {
    
    
	return GinErrorRsp{
    
    
		BadRequest, "request params error",
	}
}

1.3 Example of use

func InfoTask(c *gin.Context) {
    
    
  // 接收前端传递参数  
   var req task.InfoTaskReq
  // 将参数与结构体进行绑定  
   if err := c.ShouldBind(&req); err != nil {
    
    
      log.Error(err.Error())
      // 绑定错误,直接返回 
      c.JSON(http.StatusBadRequest, httprsp.ParamsErrorRsp())
      return
   }
    
   res, err := 调用service层的逻辑得到返回
  // 如果后端返回参数与前端不一致,需要dto进一步加工  
   dto := assembler.ToTaskInfoDTO(params)
   if err != nil {
    
    
      c.JSON(http.StatusBadRequest, httprsp.NewBadRequestRsp(err.Error()))
      return
   }

    // 执行正常,将结果从后端传递给前端)
   c.JSON(http.StatusOK, common.NewCommonHttpRsp(dto))
}

2 Front-end ——> Back-end

The front end returns the results, and the results need to be parsed, one is transformed into the corresponding structure through assembler, and the other is directly extracted the required information

// 对应接收通用数据的结构
type ResponseBody struct {
    
    
   Code int         `json:"code"` // 返回code 2000成功
   Msg  string      `json:"msg"`  // 返回提示
   Data interface{
    
    } `json:"data"` // 返回数据
}

func (resp ResponseBody) IsOk() bool {
    
    
   return resp.Code == 2000
}

The specific operation of the conversion

response,err = 前端返回数据
if err := json.Unmarshal(response.Body(), &responseBody); err != nil {
    
    
   return err
}

// Unmarshal 解析 JSON 编码的数据并将结果存储在 v 指向的值中。
// 如果 v 为 nil 或不是指针,则 Unmarshal 返回 InvalidUnmarshalError

Guess you like

Origin blog.csdn.net/qq_42647903/article/details/127612416