package ProtoController import ( "bytes" "dsAutoCode/Dao/ProtoDao" "dsAutoCode/Model" "dsAutoCode/Service/ProtoService" "dsAutoCode/Utils/CommonUtil" "github.com/gin-gonic/gin" "log" "net/http" "strings" "text/template" ) /** 功能:生成Controller层的操作代码 作者:黄海 时间:2020-04-23 */ func CodeController(c *gin.Context) { var operateType string var tableName string type VarStruct struct { Description string ParameterName string HttpType string IsInt32 bool Parameters string } var VarStructArray []VarStruct var Parameters string interfaceId := c.Query("interfaceId") interfaceName := c.Query("interfaceName") controllerName := c.Query("controllerName") operateType = ProtoService.GetOperateType(interfaceName) tableName = ProtoDao.GetTrueTableNameFromInterfaceId(interfaceId) tableName = strings.Replace(tableName, ".pb.go", "", -1) tableNameDynamic := strings.Replace(controllerName, operateType, "", -1) //根据inerfaceId找出它有哪些参数? structId, _ := ProtoDao.GetStructIdByInterfaceId(interfaceId) //此接口的httpType HttpType, controllerId, _ := ProtoDao.GetControllerInfoByName(controllerName) //此接口,在proto文件中,对应的入参结构体 list := ProtoDao.GetStructParameterInfoById(structId) var _map = make(map[string]string) for i := 0; i < len(list); i++ { _map[CommonUtil.StrFirstToLower(list[i]["struct_parameter_name"].(string))] = list[i]["struct_parameter_type"].(string) } //接口对应的参数 list = ProtoDao.GetControllerInfoById(controllerId) for i := 0; i < len(list); i++ { controllerParameterName := list[i]["controller_parameter_name"].(string) controllerParameterDescription := list[i]["controller_parameter_description"].(string) var IsInt32 bool if _, ok := _map[controllerParameterName]; ok { if _map[controllerParameterName] == "int32" { IsInt32 = true } } var v1 VarStruct if HttpType == "post" { v1.HttpType = "PostForm" } else { v1.HttpType = "Query" } v1.IsInt32 = IsInt32 v1.Description = controllerParameterDescription v1.ParameterName = controllerParameterName VarStructArray = append(VarStructArray, v1) Parameters += controllerParameterName + "," } //调用模板, filesName := CommonUtil.GetCurrentPath()+"/Controller/ProtoController/Template/Controller.template" t, err := template.ParseFiles(filesName) if err != nil { log.Fatalln("parse file err:", err) return } buf := new(bytes.Buffer) if len(Parameters) > 0 { Parameters = Parameters[:len(Parameters)-1] } var IsPage bool if operateType == "Page" { IsPage = true } else { IsPage = false } var p = map[string]interface{}{ "tableName": tableName, "tableNameDynamic": tableNameDynamic, "operateType": operateType, "VarStructArray": VarStructArray, "Parameters": Parameters, "IsPage": IsPage, "interfaceName": interfaceName, } if err := t.Execute(buf, p); err != nil { log.Fatal("There was an error:", err.Error()) } var content = buf.String() content = CommonUtil.DeleteBlankString(content) c.JSON(http.StatusOK, Model.Res{ Data: content, Msg: tableName, CodePath: ProtoService.GetGenereateCodePath("Controller", tableName), }) }