学习记录,在swagger页面,展示测试参数样例功能。

1.需要在函数外部定义请求参数结构体,之后在Handler方法的注释中进行设置。
2.此样例中,”BatchesRequest “为请求参数结构体名称。
3.具体代码内容:// @Param data body BatchesRequest true “要插入的数据对象”
4.如果内容只有“{}”,没有正确显示,可以核对下参数类型,比如参数类型是int,但是example设置了非int值“”,就会导致无法正常显示。
以下为代码内容
package http_handle_funcs
import (
"HTTPServices/db_entities"
"HTTPServices/defines"
"HTTPServices/tools"
"context"
"encoding/json"
"net/http"
"time"
)
// BatchesRequest 添加批次信息请求参数
// 需要定义在外部,否则swagger无法识别
// @Description 添加批次信息请求参数
type BatchesRequest struct {
SectionCode string `json:"section_code" validate:"required" example:""` //"编号"
Code string `json:"code" validate:"required" example:"编号样例"` //"批次号"
Weight float64 `json:"weight" validate:"required" example:"0"` //"重量"
Describe string `json:"describe" validate:"required" example:"描述样例"` //"描述"
Color string `json:"color" validate:"required" example:"#ffffff"` //"颜色"
PosX float64 `json:"pos_x" validate:"required" example:"0"` //"x坐标位置"
PosY float64 `json:"pos_y" validate:"required" example:"0"` //"y坐标位置"
HeightMin float64 `json:"height_min" validate:"required" example:"0"` //"最低高度"
HeightMax float64 `json:"height_max" validate:"required" example:"0"` //"最大高度"
}
// @Summary 添加批次信息
// @Description 根据提供的json数据。
// @Tags tags1
// @Produce json
// @Param data body BatchesRequest true "要插入的数据对象"
// @Router /addBatchs [post]
func AddBatchsHandler(w http.ResponseWriter, r *http.Request) {
// 解析请求参数
var data BatchesRequest
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, "解析请求参数失败: "+err.Error(), http.StatusBadRequest)
return
}
createTime := time.Now()
createUser := r.RemoteAddr
updateTime := createTime
updateUser := createUser
// 使用结构体插入数据
batch := db_entities.Batches{
CreateTime: createTime,
CreateUser: createUser,
UpdateTime: updateTime,
UpdateUser: updateUser,
SectionCode: data.SectionCode,
Code: data.Code,
Weight: data.Weight,
Describe: data.Describe,
Color: data.Color,
PosX: data.PosX,
PosY: data.PosY,
HeightMin: data.HeightMin,
HeightMax: data.HeightMax,
}
_, err = tools.InsertModel(context.Background(), defines.Db, "batches", &batch)
if err != nil {
http.Error(w, "插入数据失败: "+err.Error(), http.StatusInternalServerError)
return
}
//清理指定表的redis缓存
defines.ClearRedisCacheTables("batches")
tools.SendJSONResponse(w, true, http.StatusOK, "成功", "数据已插入")
}

2999

被折叠的 条评论
为什么被折叠?



