business_apiProxy.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. package service
  2. import (
  3. "DataShare/dao"
  4. "DataShare/global"
  5. "DataShare/model"
  6. "DataShare/service/api_proxy"
  7. "DataShare/util/gabs"
  8. "database/sql"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "github.com/sirupsen/logrus"
  13. "reflect"
  14. "regexp"
  15. "strings"
  16. )
  17. func Business2_GetAccessInfo(accessId string) (string,*model.Access_Service_Struct,*model.Access_Data_Struct,error){
  18. key := fmt.Sprintf("access_%s",accessId)
  19. body, err := global.RedisClient.Get(key).Result()
  20. if err != nil {
  21. return "",nil,nil, err
  22. }
  23. var tempMap map[string]interface{}
  24. err = json.Unmarshal([]byte(body), &tempMap)
  25. if err != nil {
  26. //panic(err)
  27. return "",nil,nil,err
  28. }
  29. //for k, values := range tempMap {
  30. // fmt.Printf("%s: %s\n", k, values) // ... and this line
  31. //}
  32. if tempMap["resType"]=="service"{
  33. //接口服务
  34. var accessValue model.Access_Service_Struct
  35. err = json.NewDecoder(strings.NewReader(body)).Decode(&accessValue)
  36. if err != nil{
  37. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("json转结构体出错, err:%s",err.Error()))
  38. return "",nil,nil, err
  39. }
  40. return "Service",&accessValue,nil,nil
  41. }else{
  42. //数据资源
  43. var accessValue model.Access_Data_Struct
  44. err = json.NewDecoder(strings.NewReader(body)).Decode(&accessValue)
  45. if err != nil{
  46. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("json转结构体出错, err:%s",err.Error()))
  47. return "",nil,nil, err
  48. }
  49. return "Data",nil,&accessValue,nil
  50. }
  51. //var accessValue model.AccessInfo
  52. //err = json.NewDecoder(strings.NewReader(body)).Decode(&accessValue)
  53. //if err != nil{
  54. // global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("json转结构体出错, err:%s",err.Error()))
  55. // return nil, err
  56. //}
  57. //
  58. //return &accessValue,nil
  59. //colArry := make([]model.ColNumDet,0)
  60. //
  61. //item := model.ColNumDet{
  62. // Name: "name",
  63. // Type: "varchar",
  64. // IsDesensitization: 0,
  65. // DesensitizationRule: model.DesensitizationRule{
  66. // },
  67. //}
  68. //colArry = append(colArry,item)
  69. //item = model.ColNumDet{
  70. // Name: "identifyId",
  71. // Type: "varchar",
  72. // IsDesensitization: 1,
  73. // //DesensitizationRule: model.DesensitizationRule{
  74. // // Left: 3,
  75. // // Right: 4,
  76. // // Fill: "*******",
  77. // //},
  78. // DesensitizationRule: model.DesensitizationRule{
  79. // RegStr: "^(.{3}).+(.{4})$",
  80. // FillStr: "$1****$2",
  81. // },
  82. //}
  83. //colArry = append(colArry,item)
  84. //
  85. //item = model.ColNumDet{
  86. // Name: "rysj",
  87. // Type: "varchar",
  88. // IsDesensitization: 1,
  89. // DesensitizationRule: model.DesensitizationRule{
  90. // RegStr: "^(.{3}).+(.{4})$",
  91. // FillStr: "$1****$2",
  92. // },
  93. //}
  94. //colArry = append(colArry,item)
  95. //
  96. //info := model.AccessInfo{
  97. // Enable: 1,
  98. // DbId: 1,
  99. // TbName: "inpatient_info",
  100. // Colnum: colArry,
  101. //}
  102. //
  103. //return &info,nil
  104. }
  105. func getSqlQueryParam(req *model.RequestBody)(string) {
  106. orParam := make([]string,0)
  107. for i:=0; i<len(req.Search.OR);i++{
  108. item := req.Search.OR[i]
  109. keySplit := strings.Split(item.KeyStr,".")
  110. if len(keySplit) < 2 {
  111. continue
  112. }
  113. if keySplit[1] == "like" {
  114. or := fmt.Sprintf("%s like %s",keySplit[0],item.KeyVal)
  115. orParam = append(orParam,or)
  116. }else if keySplit[1] == "eq"{
  117. or := fmt.Sprintf("%s=%s",keySplit[0],item.KeyVal)
  118. orParam = append(orParam,or)
  119. }else if keySplit[1] == "lt"{
  120. or := fmt.Sprintf("%s<%s",keySplit[0],item.KeyVal)
  121. orParam = append(orParam,or)
  122. }else if keySplit[1] == "gt"{
  123. or := fmt.Sprintf("%s>%s",keySplit[0],item.KeyVal)
  124. orParam = append(orParam,or)
  125. }
  126. }
  127. andParam := make([]string,0)
  128. for i:=0;i<len(req.Search.AND);i++{
  129. item := req.Search.AND[i]
  130. keySplit := strings.Split(item.KeyStr,".")
  131. if len(keySplit) < 2 {
  132. continue
  133. }
  134. if keySplit[1] == "like" {
  135. or := fmt.Sprintf("%s like %s",keySplit[0],item.KeyVal)
  136. andParam = append(andParam,or)
  137. }else if keySplit[1] == "eq"{
  138. or := fmt.Sprintf("%s=%s",keySplit[0],item.KeyVal)
  139. andParam = append(andParam,or)
  140. }else if keySplit[1] == "lt"{
  141. or := fmt.Sprintf("%s<%s",keySplit[0],item.KeyVal)
  142. andParam = append(andParam,or)
  143. }else if keySplit[1] == "gt"{
  144. or := fmt.Sprintf("%s>%s",keySplit[0],item.KeyVal)
  145. andParam = append(andParam,or)
  146. }
  147. }
  148. queryParam := ""
  149. if len(orParam)>0{
  150. queryParam += "("
  151. for i:=0;i<len(orParam);i++{
  152. if i < len(orParam)-1{
  153. queryParam += orParam[i] + " or "
  154. }else{
  155. queryParam += orParam[i]
  156. }
  157. }
  158. queryParam += ")"
  159. }
  160. if len(andParam) > 0 {
  161. queryParam += " and "
  162. for i:=0;i<len(andParam);i++{
  163. if i < len(andParam)-1{
  164. queryParam += orParam[i] + " and "
  165. }else{
  166. queryParam += orParam[i]
  167. }
  168. }
  169. }
  170. return queryParam
  171. }
  172. //func Business2_QueryTable(req *model.RequestBody,accessInfo *model.AccessInfo)(*model.CommonList,error){
  173. // //第一步:去出要查询的字段
  174. // dbInfo := getDataBaseInfoById(accessInfo.DbId)
  175. // if dbInfo==nil{
  176. // return nil,errors.New("数据库不存在!")
  177. // }
  178. //
  179. // if dbInfo.Status == false {
  180. // return nil,errors.New(fmt.Sprintf("database:%s not connect",dbInfo.DbName))
  181. // }
  182. //
  183. // if dbInfo.SqlType == "mysql" {
  184. // sql := "select"
  185. // if req.PageSize > 0 {
  186. // sql += " SQL_CALC_FOUND_ROWS"
  187. // }
  188. // args := make([]interface{},0)
  189. // first := 1
  190. // for i:=0;i<len(accessInfo.Colnum);i++{
  191. // if first == 0{
  192. // sql += ","
  193. // }else{
  194. // first = 0
  195. // }
  196. //
  197. // if accessInfo.Colnum[i].IsDesensitization == 1 {
  198. // if accessInfo.Colnum[i].DesensitizationRule.Left > 0 && accessInfo.Colnum[i].DesensitizationRule.Right > 0{
  199. // sql += "concat(left(%s, %d),'%s',right(%s, %d)) AS %s"
  200. // args = append(args,accessInfo.Colnum[i].Name)
  201. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Left)
  202. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Fill)
  203. // args = append(args,accessInfo.Colnum[i].Name)
  204. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Right)
  205. // args = append(args,accessInfo.Colnum[i].Name)
  206. // }else if accessInfo.Colnum[i].DesensitizationRule.Left > 0 {
  207. // sql += "concat(left(%s, %d),'%s') AS %s"
  208. // args = append(args,accessInfo.Colnum[i].Name)
  209. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Left)
  210. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Fill)
  211. // args = append(args,accessInfo.Colnum[i].Name)
  212. // }else if accessInfo.Colnum[i].DesensitizationRule.Right > 0{
  213. // sql += "concat('%s',right(%s, %d)) AS %s"
  214. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Fill)
  215. // args = append(args,accessInfo.Colnum[i].Name)
  216. // args = append(args,accessInfo.Colnum[i].DesensitizationRule.Right)
  217. // args = append(args,accessInfo.Colnum[i].Name)
  218. // }else{
  219. // sql +=" %s"
  220. // args = append(args,accessInfo.Colnum[i].Name)
  221. // }
  222. // }else {
  223. // sql +=" %s"
  224. // args = append(args,accessInfo.Colnum[i].Name)
  225. // }
  226. // }
  227. // sql += " from %s"
  228. // args = append(args,accessInfo.TbName)
  229. //
  230. // queryParam := getSqlQueryParam(req,accessInfo)
  231. // if len(queryParam)> 0 {
  232. // sql += " where "+queryParam
  233. // }
  234. // if req.PageSize > 0 {
  235. // sql += " limit %d,%d"
  236. // args = append(args,(req.PageNo-1)*req.PageSize)
  237. // args = append(args,req.PageSize)
  238. // }
  239. // sqlStr := fmt.Sprintf(sql,args...)
  240. // fmt.Println("------------")
  241. // fmt.Println(sqlStr)
  242. // fmt.Println("------------")
  243. // items,_,_,total,_ := dao.GetData(dbInfo.DbHandle,sqlStr)
  244. //
  245. // result := &model.CommonList{
  246. // Total: total,
  247. // Items: items,
  248. // }
  249. // //todo:
  250. // //脱敏处理
  251. //
  252. // return result,nil
  253. // }
  254. //
  255. // return nil,nil
  256. //}
  257. func Business2_QueryTable(req *model.DbQuery,accessInfo *model.Access_Data_Struct)(*model.CommonList,error){
  258. //第一步:去出要查询的字段
  259. dbInfo := getDataBaseInfoById(accessInfo.ResData.DbId)
  260. if dbInfo==nil{
  261. return nil,errors.New("数据库不存在!")
  262. }
  263. if dbInfo.Status == false {
  264. return nil,errors.New(fmt.Sprintf("database:%s not connect",dbInfo.DbName))
  265. }
  266. //fmt.Println("--------------------------1-------------------------")
  267. if dbInfo.SqlType == "mysql" {
  268. sql := "select"
  269. if req.PageSize > 0 {
  270. sql += " SQL_CALC_FOUND_ROWS"
  271. }
  272. args := make([]interface{},0)
  273. first := 1
  274. if req.QueryColn == nil {
  275. sql += " *"
  276. }else{
  277. for i:=0;i<len(req.QueryColn);i++{
  278. if first == 0{
  279. sql += ","
  280. }else{
  281. first = 0
  282. }
  283. sql +=" %s"
  284. args = append(args,req.QueryColn[i])
  285. }
  286. if len(req.QueryColn) == 0 {
  287. sql += " *"
  288. }
  289. }
  290. //fmt.Println("--------------------------2-------------------------")
  291. sql += " from %s"
  292. args = append(args,accessInfo.ResData.TbName)
  293. where := 0
  294. //用户查询参数
  295. for zz:=0;zz<len(req.Query);zz++{
  296. if len(req.Query[zz].ColName) > 0 {
  297. if where == 0 {
  298. sql += " where"
  299. where = 1
  300. }else{
  301. sql += " and"
  302. }
  303. if req.Query[zz].Cond == 0 {
  304. sql += " %s='%s'"
  305. }else if req.Query[zz].Cond == 1 {
  306. sql += " %s>'%s'"
  307. }else{
  308. sql += " %s<'%s'"
  309. }
  310. args = append(args,req.Query[zz].ColName)
  311. args = append(args,req.Query[zz].ColVal)
  312. }
  313. }
  314. //拼接默认参数
  315. cols := accessInfo.ResData.Colnums
  316. for zz:=0;zz<len(cols);zz++{
  317. //if cols[zz].IsSearchable != nil && *cols[zz].IsSearchable == 1 {
  318. if cols[zz].FilterOperator != nil && len(*cols[zz].FilterOperator) > 0 && cols[zz].FilterValue != nil && len(*cols[zz].FilterValue) > 0 {
  319. if where == 0 {
  320. sql += " where"
  321. where = 1
  322. }else{
  323. sql += " and"
  324. }
  325. //0-等于 1-大于 2-小于
  326. if *cols[zz].FilterOperator == "0" {
  327. sql += " %s='%s'"
  328. }else if *cols[zz].FilterOperator == "1" {
  329. sql += " %s>'%s'"
  330. }else if *cols[zz].FilterOperator == "2" {
  331. sql += " %s<'%s'"
  332. }
  333. args = append(args,cols[zz].Name)
  334. args = append(args,*cols[zz].FilterValue)
  335. }
  336. //}
  337. }
  338. //排序
  339. if len(req.Sort.ColName) > 0 {
  340. if req.Sort.IsDesc == 1 {
  341. sql += " order by %s desc"
  342. }else {
  343. sql += " order by %s"
  344. }
  345. args = append(args,req.Sort.ColName)
  346. }
  347. //分页
  348. if req.PageSize > 0 {
  349. sql += " limit %d,%d"
  350. args = append(args,(req.PageNo-1)*req.PageSize)
  351. args = append(args,req.PageSize)
  352. }
  353. sqlStr := fmt.Sprintf(sql,args...)
  354. //fmt.Println("---------------------------------------------------")
  355. //fmt.Println(sqlStr)
  356. //fmt.Println("---------------------------------------------------")
  357. //查询
  358. items,_,_,total,_ := dao.GetData2(dbInfo.DbHandle,sqlStr,accessInfo.ResData.Colnums)
  359. result := &model.CommonList{
  360. Total: total,
  361. Items: items,
  362. }
  363. //todo:
  364. //脱敏处理
  365. return result,nil
  366. }else if dbInfo.SqlType == "postgres" || dbInfo.SqlType == "kingbase" {
  367. sql := "select"
  368. sqlCount := "select count(*)"
  369. args_count := make([]interface{},0)
  370. args := make([]interface{},0)
  371. first := 1
  372. if req.QueryColn == nil {
  373. sql += " *"
  374. }else{
  375. for i:=0;i<len(req.QueryColn);i++{
  376. if first == 0{
  377. sql += ","
  378. }else{
  379. first = 0
  380. }
  381. sql +=" %s"
  382. args = append(args,req.QueryColn[i])
  383. }
  384. if len(req.QueryColn) == 0 {
  385. sql += " *"
  386. }
  387. }
  388. sql += " from %s"
  389. args = append(args,accessInfo.ResData.TbName)
  390. args_count = append(args_count,accessInfo.ResData.TbName)
  391. where := 0
  392. //用户查询参数
  393. for zz:=0;zz<len(req.Query);zz++{
  394. if len(req.Query[zz].ColName) > 0 {
  395. if where == 0 {
  396. sql += " where"
  397. sqlCount += " where"
  398. where = 1
  399. }else{
  400. sql += " and"
  401. sqlCount += " and"
  402. }
  403. if req.Query[zz].Cond == 0 {
  404. sql += " %s='%s'"
  405. sqlCount += " %s='%s'"
  406. }else if req.Query[zz].Cond == 1 {
  407. sql += " %s>'%s'"
  408. sqlCount += " %s>'%s'"
  409. }else{
  410. sql += " %s<'%s'"
  411. sqlCount += " %s<'%s'"
  412. }
  413. args = append(args,req.Query[zz].ColName)
  414. args = append(args,req.Query[zz].ColVal)
  415. args_count = append(args_count,req.Query[zz].ColName)
  416. args_count = append(args_count,req.Query[zz].ColVal)
  417. }
  418. }
  419. //拼接默认参数
  420. cols := accessInfo.ResData.Colnums
  421. for zz:=0;zz<len(cols);zz++{
  422. //if cols[zz].IsSearchable != nil && *cols[zz].IsSearchable == 1 {
  423. if cols[zz].FilterOperator != nil && len(*cols[zz].FilterOperator) > 0 && cols[zz].FilterValue != nil && len(*cols[zz].FilterValue) > 0 {
  424. if where == 0 {
  425. sql += " where"
  426. sqlCount += " where"
  427. where = 1
  428. }else{
  429. sql += " and"
  430. sqlCount += " and"
  431. }
  432. //0-等于 1-大于 2-小于
  433. if *cols[zz].FilterOperator == "0" {
  434. sql += " %s='%s'"
  435. }else if *cols[zz].FilterOperator == "1" {
  436. sql += " %s>'%s'"
  437. }else if *cols[zz].FilterOperator == "2" {
  438. sql += " %s<'%s'"
  439. }
  440. args = append(args,cols[zz].Name)
  441. args = append(args,*cols[zz].FilterValue)
  442. args_count = append(args_count,cols[zz].Name)
  443. args_count = append(args_count,*cols[zz].FilterValue)
  444. }
  445. //}
  446. }
  447. //统计总数
  448. sqlCntStr := fmt.Sprintf(sqlCount,args_count...)
  449. total,_:= dao.GetCount(dbInfo.DbHandle,sqlCntStr)
  450. //排序
  451. if len(req.Sort.ColName) > 0 {
  452. if req.Sort.IsDesc == 1 {
  453. sql += " order by %s desc"
  454. }else {
  455. sql += " order by %s"
  456. }
  457. args = append(args,req.Sort.ColName)
  458. }
  459. //分页
  460. if req.PageSize > 0 {
  461. sql += " limit %d,%d"
  462. args = append(args,(req.PageNo-1)*req.PageSize)
  463. args = append(args,req.PageSize)
  464. }
  465. sqlStr := fmt.Sprintf(sql,args...)
  466. //查询
  467. items,_,_,_,_ := dao.GetData2(dbInfo.DbHandle,sqlStr,accessInfo.ResData.Colnums)
  468. result := &model.CommonList{
  469. Total: total,
  470. Items: items,
  471. }
  472. return result,nil
  473. }
  474. return nil,nil
  475. }
  476. //func Business2_QueryTable(req *model.RequestBody,accessInfo *model.Access_Data_Struct)(*model.CommonList,error){
  477. // //第一步:去出要查询的字段
  478. // dbInfo := getDataBaseInfoById(accessInfo.ResData.DbId)
  479. // if dbInfo==nil{
  480. // return nil,errors.New("数据库不存在!")
  481. // }
  482. //
  483. // if dbInfo.Status == false {
  484. // return nil,errors.New(fmt.Sprintf("database:%s not connect",dbInfo.DbName))
  485. // }
  486. //
  487. // if dbInfo.SqlType == "mysql" {
  488. // sql := "select"
  489. // if req.PageSize > 0 {
  490. // sql += " SQL_CALC_FOUND_ROWS"
  491. // }
  492. // args := make([]interface{},0)
  493. // first := 1
  494. // for i:=0;i<len(accessInfo.ResData.Colnums);i++{
  495. // if first == 0{
  496. // sql += ","
  497. // }else{
  498. // first = 0
  499. // }
  500. //
  501. // sql +=" %s"
  502. // args = append(args,accessInfo.ResData.Colnums[i].Name)
  503. // }
  504. // sql += " from %s"
  505. // args = append(args,accessInfo.ResData.TbName)
  506. //
  507. // queryParam := getSqlQueryParam(req)
  508. // if len(queryParam)> 0 {
  509. // sql += " where "+queryParam
  510. // }
  511. // if req.PageSize > 0 {
  512. // sql += " limit %d,%d"
  513. // args = append(args,(req.PageNo-1)*req.PageSize)
  514. // args = append(args,req.PageSize)
  515. // }
  516. // sqlStr := fmt.Sprintf(sql,args...)
  517. // fmt.Println("------------")
  518. // fmt.Println(sqlStr)
  519. // fmt.Println("------------")
  520. // items,_,_,total,_ := dao.GetData2(dbInfo.DbHandle,sqlStr,accessInfo.ResData.Colnums)
  521. //
  522. // result := &model.CommonList{
  523. // Total: total,
  524. // Items: items,
  525. // }
  526. // //todo:
  527. // //脱敏处理
  528. //
  529. // return result,nil
  530. // }
  531. //
  532. // return nil,nil
  533. //}
  534. func getAccessParamByName(key string,access *model.Access_Service_Struct)(*model.Access_Service_Params){
  535. for i:=0;i<len(access.ResData.Params);i++{
  536. if key == access.ResData.Params[i].ParamName {
  537. return &access.ResData.Params[i]
  538. }
  539. }
  540. return nil
  541. }
  542. //总队标准接口服务解析校验
  543. func Business2_Cq119NormalApiVerify(dataByte []byte,access *model.Access_Service_Struct)(*model.DataShareNormalResponse,error) {
  544. fmt.Println("---resp:", string(dataByte))
  545. var cq119NormalResp model.CQ119Response
  546. err := json.NewDecoder(strings.NewReader(string(dataByte))).Decode(&cq119NormalResp)
  547. if err != nil {
  548. global.SystemLogger.Log(logrus.ErrorLevel, fmt.Sprintf("json转结构体出错, err:%s", err.Error()))
  549. return nil, err
  550. }
  551. normalRespPacket := &model.DataShareNormalResponse{
  552. Code: cq119NormalResp.Code,
  553. Page: cq119NormalResp.Page,
  554. Size: cq119NormalResp.Size,
  555. Total: cq119NormalResp.Total,
  556. Columns: cq119NormalResp.Columns,
  557. }
  558. for i := 0; i < len(cq119NormalResp.Data); i++ {
  559. fmt.Println("===================index:",i)
  560. item := cq119NormalResp.Data[i]
  561. v := reflect.ValueOf(item)
  562. if v.Kind() == reflect.Map {
  563. n := make(map[string]interface{})
  564. for _, key := range v.MapKeys() {
  565. strct := v.MapIndex(key)
  566. fmt.Println(key.Interface(),":", strct.Interface())
  567. newValue := strct.Interface()
  568. param := getAccessParamByName(key.Interface().(string),access)
  569. if param != nil {
  570. if param.DesensitizationRule != nil {
  571. //脱敏
  572. if len(param.DesensitizationRule.RegStr)>0 && len(param.DesensitizationRule.FillStr)>0{
  573. reg := regexp.MustCompile(param.DesensitizationRule.RegStr)
  574. newValue = reg.ReplaceAllString(strct.Interface().(string),param.DesensitizationRule.FillStr)
  575. }
  576. }
  577. n[key.Interface().(string)]=newValue
  578. }
  579. }
  580. if len(n)>0{
  581. normalRespPacket.Data = append(normalRespPacket.Data, n)
  582. }
  583. }
  584. }
  585. //v, err := json.Marshal(normalRespPacket)
  586. return normalRespPacket,nil
  587. }
  588. //数据缓存
  589. func Business2_CacheParser(dataByte []byte,req *model.DataCacheOfRedis) (*model.CQ119Response,[]map[string]interface{},error){
  590. var cq119NormalResp model.CQ119Response
  591. err := json.NewDecoder(strings.NewReader(string(dataByte))).Decode(&cq119NormalResp)
  592. if err != nil {
  593. global.SystemLogger.Log(logrus.ErrorLevel, fmt.Sprintf("json转结构体出错, err:%s", err.Error()))
  594. return nil,nil,err
  595. }
  596. serviceConfig := req.ServiceConfig
  597. column_map := serviceConfig.ColumnMap
  598. rows_array := make([]map[string]interface{},0)
  599. for i := 0; i < len(cq119NormalResp.Data);i++{
  600. fmt.Println("===================index:",i)
  601. item := cq119NormalResp.Data[i]
  602. v := reflect.ValueOf(item)
  603. if v.Kind() == reflect.Map {
  604. n := make(map[string]interface{})
  605. for _, key := range v.MapKeys() {
  606. strct := v.MapIndex(key)
  607. fmt.Println(key.Interface(),":", strct.Interface())
  608. for m:=0;m<len(column_map);m++{
  609. if key.Interface().(string) == column_map[m].FieldName {
  610. n[column_map[m].ColumnName] = strct.Interface()
  611. break
  612. }
  613. }
  614. }
  615. if len(n)>0{
  616. rows_array = append(rows_array, n)
  617. }
  618. }
  619. }
  620. //fmt.Println("------------print rows_array------------------")
  621. //for i:=0;i<len(rows_array);i++{
  622. // item := rows_array[i]
  623. // for k,v := range item {
  624. // fmt.Println("key:",k,"value:",v)
  625. // }
  626. //}
  627. //fmt.Println("--------------end print-----------------------")
  628. return &cq119NormalResp,rows_array,nil
  629. }
  630. func Business2_DataCache_DbConnect(dbInfo *model.CacheDbConfig) (*sql.DB,error){
  631. find := false
  632. for i:=0;i<len(global.Databases);i++{
  633. if dbInfo.DbId == global.Databases[i].Id{
  634. find = true
  635. return global.Databases[i].DbHandle,nil
  636. }
  637. }
  638. if find == false {
  639. //连接数据库
  640. db, err := dao.DbConnect(dbInfo.DbType,dbInfo.ConnectionString)
  641. if err != nil {
  642. return nil,err
  643. }
  644. info := global.DbInfo{
  645. DbHandle: db,
  646. ConnInfo: dbInfo.ConnectionString,
  647. Status: true,
  648. SqlType: dbInfo.DbType,
  649. DbName: "",
  650. Id: dbInfo.DbId,
  651. }
  652. global.Databases = append(global.Databases, info)
  653. return db,nil
  654. }
  655. return nil,errors.New("连接数据库失败")
  656. }
  657. //数据保存
  658. func Business2_DataSave(rows_array []map[string]interface{},dbInfo *model.CacheDbConfig)(error){
  659. //写数据表
  660. column_data := model.ColnDataInsert{
  661. Id: dbInfo.DbId,
  662. TbName: dbInfo.TbName,
  663. }
  664. for i:=0;i<len(rows_array);i++{
  665. item := rows_array[i]
  666. for k, _ := range item {
  667. //fmt.Printf("--------%s: %s\n", k, values) // ... and this line
  668. column_data.ColNameArray = append(column_data.ColNameArray,k)
  669. }
  670. break
  671. }
  672. for i:=0;i<len(rows_array);i++{
  673. var row model.ColnItem
  674. item := rows_array[i]
  675. for j:=0;j<len(column_data.ColNameArray);j++ {
  676. name := column_data.ColNameArray[j]
  677. row.List = append(row.List,item[name].(string))
  678. }
  679. //for k, values := range item {
  680. // fmt.Printf("%s: %s\n", k, values) // ... and this line
  681. // row.List = append(row.List,values.(string))
  682. //}
  683. column_data.Rows = append(column_data.Rows,row)
  684. }
  685. return DatabaseInsert(&column_data)
  686. }
  687. func Business2_DataCacheTest(){
  688. data_cache_list := dao.LoadDataCacheList()
  689. for i:=0;i< len(data_cache_list);i++{
  690. _,err := Business2_DataCache_DbConnect(&data_cache_list[i].DbConfig)
  691. if err != nil {
  692. continue
  693. }
  694. serviceConfig := data_cache_list[i].ServiceConfig
  695. if serviceConfig.AuthWay == "cq119"{
  696. _,body,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(serviceConfig.ServiceUrl,[]byte(serviceConfig.RequestParam))
  697. if err != nil {
  698. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("serviceUrl:%s ,cache data failed.",serviceConfig.ServiceUrl))
  699. continue
  700. }
  701. _,rows_array,err := Business2_CacheParser(body,&data_cache_list[i])
  702. //save
  703. Business2_DataSave(rows_array,&data_cache_list[i].DbConfig)
  704. }
  705. }
  706. }
  707. func Business2_GetApiFieldName(columnName string,dataCacheConfig *model.DataCacheOfRedis) (string,error){
  708. for i:=0;i<len(dataCacheConfig.ServiceConfig.ColumnMap);i++{
  709. if dataCacheConfig.ServiceConfig.ColumnMap[i].ColumnName == columnName{
  710. return dataCacheConfig.ServiceConfig.ColumnMap[i].FieldName,nil
  711. }
  712. }
  713. return "",errors.New("未找到搜索参数名称")
  714. }
  715. func Business2_DataCache(dataCacheConfig *model.DataCacheOfRedis) error{
  716. db,err := Business2_DataCache_DbConnect(&dataCacheConfig.DbConfig)
  717. if err != nil {
  718. return err
  719. }
  720. serviceConfig := dataCacheConfig.ServiceConfig
  721. if serviceConfig.AuthWay == "119"{
  722. //组装参数
  723. if dataCacheConfig.Mode == "full"{
  724. //全量:删除数据表,重新同步数据
  725. pageNo := 1
  726. pageSize := 10000
  727. total := 0
  728. for ;;{
  729. //参数
  730. paramMap := make(map[string]interface{},0)
  731. err := json.Unmarshal([]byte(serviceConfig.RequestParam),&paramMap)
  732. if err != nil {
  733. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("Business2_DataCache failed, errmsg:"+err.Error()))
  734. //return err
  735. }
  736. paramMap[dataCacheConfig.PageField] = pageNo
  737. paramMap[dataCacheConfig.PageSizeField] = pageSize
  738. newParam,err := json.Marshal(&paramMap)
  739. if err != nil {
  740. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("Business2_DataCache failed, errmsg:"+err.Error()))
  741. return err
  742. }
  743. _,body,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(serviceConfig.ServiceUrl,newParam)
  744. if err != nil {
  745. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("serviceUrl:%s ,cache data failed.",serviceConfig.ServiceUrl))
  746. return err
  747. }
  748. if serviceConfig.AuthWay == "gov" {
  749. _,body,err = api_proxy.GovDataFormatToResource(body)
  750. }
  751. resp,rows_array,err := Business2_CacheParser(body,dataCacheConfig)
  752. if len(rows_array)<1{
  753. global.SystemLogger.Log(logrus.InfoLevel,fmt.Sprintf("serviceUrl:%s ,cache data complete.",serviceConfig.ServiceUrl))
  754. break;
  755. }
  756. if total == 0 {
  757. total = resp.Total
  758. }
  759. //save
  760. Business2_DataSave(rows_array,&dataCacheConfig.DbConfig)
  761. pageNo += 1
  762. if pageNo*pageSize >= total{
  763. break
  764. }
  765. break;
  766. }
  767. }else if dataCacheConfig.Mode == "add"{
  768. total := 0
  769. pageNo := 1
  770. pageSize := 100
  771. //增量:按照增量标识,获取最大值,作为条件
  772. maxValue,err := dao.GetMaxValue(dataCacheConfig.AddField,dataCacheConfig.DbConfig.TbName,db)
  773. if err != nil{
  774. return err
  775. }
  776. fieldName,err := Business2_GetApiFieldName(dataCacheConfig.AddField,dataCacheConfig)
  777. if err != nil {
  778. return err
  779. }
  780. //参数
  781. for ;;{
  782. //var paramMap map[string]interface{}
  783. paramMap := make(map[string]interface{},0)
  784. err := json.Unmarshal([]byte(serviceConfig.RequestParam),&paramMap)
  785. if err != nil {
  786. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("Business2_DataCache failed, errmsg:"+err.Error()))
  787. //return err
  788. }
  789. paramMap[dataCacheConfig.PageField] = pageNo
  790. paramMap[dataCacheConfig.PageSizeField] = pageSize
  791. if maxValue != "<nil>" {
  792. if paramMap[dataCacheConfig.SearchField] != nil {
  793. searchNode,err := gabs.ParseJSON([]byte(paramMap[dataCacheConfig.SearchField].(string)))
  794. if err != nil {
  795. return err
  796. }
  797. searchNode.Set(maxValue,fmt.Sprintf("%s.gt",fieldName))
  798. paramMap[dataCacheConfig.SearchField] = searchNode.String()
  799. }else{
  800. paramMap[dataCacheConfig.SearchField] = fmt.Sprintf("{\"%s.gt\":\"%s\"}",fieldName,maxValue)
  801. }
  802. }else{
  803. //paramMap[dataCacheConfig.SearchField] = model.NullObj{}
  804. }
  805. newParam,err := json.Marshal(&paramMap)
  806. if err != nil {
  807. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("Business2_DataCache failed, errmsg:"+err.Error()))
  808. return err
  809. }
  810. fmt.Println("-------------------------------")
  811. fmt.Println(string(newParam))
  812. fmt.Println("---------------------------------")
  813. _,body,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(serviceConfig.ServiceUrl,newParam)
  814. if err != nil {
  815. global.SystemLogger.Log(logrus.ErrorLevel,fmt.Sprintf("serviceUrl:%s ,cache data failed.",serviceConfig.ServiceUrl))
  816. return err
  817. }
  818. if serviceConfig.AuthWay == "gov" {
  819. _,body,err = api_proxy.GovDataFormatToResource(body)
  820. }
  821. resp,rows_array,err := Business2_CacheParser(body,dataCacheConfig)
  822. if len(rows_array)<1{
  823. global.SystemLogger.Log(logrus.InfoLevel,fmt.Sprintf("serviceUrl:%s ,cache data complete.",serviceConfig.ServiceUrl))
  824. break;
  825. }
  826. if total == 0 {
  827. total = resp.Total
  828. }
  829. //save
  830. Business2_DataSave(rows_array,&dataCacheConfig.DbConfig)
  831. pageNo += 1
  832. if pageNo*pageSize >= total{
  833. break
  834. }
  835. break
  836. }
  837. }
  838. }
  839. return nil
  840. }