Compare commits

..

203 Commits

Author SHA1 Message Date
zhoupengwei 2c9d475a45 导出功能修改关联salesman关联关系 2022-05-18 17:52:49 +08:00
zhoupengwei 3540209b26 科创券优化 2022-05-17 12:31:47 +08:00
zhoupengwei 797681d76c 添source_type字段(券的来源:1-vip获得,2-认证获得,3-拉新获得),用来判断券的来源,
userinfo接口返回企业统一社会信用代码和营业执照路径
2022-05-13 18:43:35 +08:00
zhoupengwei 0ec83f9a95 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:50:45 +08:00
zhoupengwei ec798bd624 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:45:50 +08:00
zhoupengwei 6b57201e59 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-13 15:34:53 +08:00
zhoupengwei 4e35dfe6ed 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:34:15 +08:00
hoteas 970bdb0157 增加time类型直接转换 2022-05-13 15:31:55 +08:00
zhoupengwei d656faf915 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-13 09:36:46 +08:00
hoteas 2ecc70288e 打印影响延迟优化 2022-05-13 09:30:09 +08:00
hoteas ce95cdc021 打印影响延迟优化 2022-05-12 18:27:01 +08:00
zhoupengwei 22130c7afe vip当日购买信息导出excel的sql调整,添加新字段:用户关联parentid时间,用户关联salesmanid时间 2022-05-11 18:19:30 +08:00
zhoupengwei d85c65faef Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-11 18:17:40 +08:00
hoteas c9f33eefec 打印影响延迟优化 2022-05-11 14:55:28 +08:00
hoteas 1826e76a34 打印影响延迟优化 2022-05-11 13:56:53 +08:00
zhoupengwei b9a6b7af22 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-11 09:51:35 +08:00
hoteas 95bfea4feb 对政策匹配进行优化 2022-05-11 00:44:52 +08:00
zhoupengwei e4bb8ac94a vip当日购买信息导出excel 2022-05-10 19:47:20 +08:00
zhoupengwei d7a49bf56d vip当日购买信息导出excel 2022-05-10 19:45:00 +08:00
zhoupengwei 3d1a1670cc Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-10 19:43:36 +08:00
hoteas 7de6a79611 对政策匹配进行优化 2022-05-10 12:54:24 +08:00
zhoupengwei 83198b39cb Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei
 Conflicts:
	example/app/declare.go
	example/provider/company.go
2022-05-10 09:43:03 +08:00
hoteas db0724f09b 对政策匹配进行优化 2022-05-09 19:19:15 +08:00
hoteas c1b013c926 对政策匹配进行优化 2022-05-09 15:07:01 +08:00
zhoupengwei 40bc84ea3d Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-07 20:56:36 +08:00
zhoupengwei e977a97013 Merge pull request '修复 bug 客户管理领域信息没存起来,高层次人才单选的形式存储的' (#1) from liyun into zct-v2
Reviewed-on: #1
2022-05-07 12:55:28 +00:00
michael 9330f7f5ea 修复 bug 客户管理领域信息没存起来,高层次人才单选的形式存储的 2022-05-07 20:47:58 +08:00
zhoupengwei d20bcc162c Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-07 17:11:27 +08:00
hoteas b48ad793da 修正企服商那边不显示名称问题 2022-05-07 13:55:57 +08:00
hoteas 3754734130 临时增加state为1企服商列表不显示企业 2022-05-07 11:08:11 +08:00
hoteas 918b88332b 增加限制条件 2022-05-07 11:02:12 +08:00
hoteas 9ba182d65c 增加限制条件 2022-05-06 13:08:13 +08:00
hoteas 8cf54ce25b 增加限制条件 2022-05-06 11:35:40 +08:00
hoteas 22d00739ff 增加join的orm兼容性 2022-05-05 18:33:27 +08:00
hoteas 3b2a317d2b 增加U盘登录 2022-05-05 16:07:01 +08:00
zhoupengwei afa9b173ba Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-05 10:44:10 +08:00
hoteas 53f24c033c 初步版本修正 2022-05-05 00:29:30 +08:00
zhoupengwei 1ffcaaef8e 只在main.go中加了双//,测试是否能够提交成功 2022-05-04 21:50:52 +08:00
hoteas 62ba00270a 调优 2022-05-03 22:40:02 +08:00
hoteas fe31335cf5 验证数据 2022-05-03 15:17:27 +08:00
hoteas b709b58fef 基础整理 2022-05-03 09:41:18 +08:00
hoteas 76b220aa5d 基础整理 2022-05-03 08:09:25 +08:00
hoteas dbf8f91696 基础整理 2022-05-02 15:42:54 +08:00
hoteas 335e8730da 用户登录 2022-05-02 15:39:50 +08:00
hoteas cbed318832 科创地图打包 2022-04-29 17:58:14 +08:00
hoteas 31a6568cbe 科创地图打包 2022-04-29 03:08:32 +08:00
hoteas 2aa86361e1 增加普通时间类型,以及增加富文本类型 2022-04-28 14:44:56 +08:00
hoteas 2a21dad90a Merge branch 'zct-wechat' into zct-manage
# Conflicts:
#	example/config/config.json
#	example/main.go
#	example/zct_manage.exe
2022-04-26 09:24:51 +08:00
hoteas bae9f60012 增加普通时间类型,以及增加富文本类型 2022-04-25 20:08:16 +08:00
hoteas 79d1189803 增加普通时间类型,以及增加富文本类型 2022-04-25 19:58:49 +08:00
hoteas c3d0c8921b 系统优化 2022-04-22 15:48:17 +08:00
hoteas 1da98a058b 系统优化 2022-04-21 02:20:37 +08:00
hoteas 152386c5a0 系统优化 2022-04-21 02:20:27 +08:00
hoteas 5e2845d3a1 系统优化 2022-04-20 22:49:07 +08:00
hoteas bab49c9a66 系统优化 2022-04-20 22:47:58 +08:00
hoteas 1d3bfcaee5 系统优化 2022-04-20 18:36:05 +08:00
hoteas a37a33321f 系统优化 2022-04-18 06:28:01 +08:00
hoteas 48042ecce4 系统优化 2022-03-29 05:31:02 +08:00
hoteas 5d8227d8bb 初步完成 2022-03-28 04:52:10 +08:00
hoteas 38d3d77c59 初步完成 2022-03-28 01:14:09 +08:00
hoteas fec195b3a1 框架优化 2022-03-26 16:53:40 +08:00
hoteas 5945ed64c6 框架优化 2022-03-16 09:58:24 +08:00
hoteas ce515d991a 框架优化 2022-03-14 16:48:19 +08:00
hoteas cb04dc6c34 框架优化 2022-03-13 17:02:19 +08:00
hoteas 17905c2d21 框架优化 2022-03-13 05:13:32 +08:00
hoteas b7c243823a 框架优化 2022-03-13 05:06:28 +08:00
hoteas ebea14c74f Merge remote-tracking branch 'origin/master' into rfcb
# Conflicts:
#	code.go
2022-03-13 02:16:31 +08:00
hoteas d6ef790010 优化整体 2022-03-13 02:00:40 +08:00
hoteas 5c64580378 优化整体 2022-03-13 01:48:54 +08:00
hoteas e49164fa81 使用go mod 2022-03-13 01:12:29 +08:00
hoteas 8265e24add 使用go mod 2022-03-13 01:00:59 +08:00
hoteas 283985df52 删除无关代码 2022-03-13 00:26:01 +08:00
hoteas 95adca04bd 删除无关代码 2022-03-13 00:24:36 +08:00
hoteas 2e65138222 hotimego V1.0.1 2022-03-12 23:57:48 +08:00
hoteas 87039524a7 政企超链接开始集成 2022-03-12 23:52:42 +08:00
hoteas 66cd21c35f 政企超链接开始集成 2022-03-12 23:52:25 +08:00
hoteas 7e64131931 政企超链接开始集成 2022-03-06 23:55:14 +08:00
hoteas e30d40cfbb 政企超链接开始集成 2022-03-04 00:06:26 +08:00
hoteas 751ed0003d 政企超链接开始集成 2022-03-04 00:06:04 +08:00
hoteas 6d9f89a1d4 政企超链接开始集成 2022-03-03 21:23:57 +08:00
hoteas bc329be03b 政企超链接开始集成 2022-03-02 18:19:15 +08:00
hoteas 4597a0a50d 政企超链接开始集成 2022-03-02 12:14:07 +08:00
hoteas 3dda86d170 政企超链接开始集成 2022-02-28 19:37:52 +08:00
hoteas d847da7591 政企超链接开始集成 2022-02-28 19:08:48 +08:00
hoteas e1eca90835 政企超链接开始集成 2022-02-28 09:59:05 +08:00
hoteas 9283b8c284 政企超链接开始集成 2022-02-28 08:53:38 +08:00
hoteas d8d9afa4d2 政企超链接开始集成 2022-02-24 06:26:36 +08:00
hoteas 4d3829c345 简阳版本 2022-02-19 21:38:35 +08:00
hoteas a23037a437 简阳版本 2022-02-19 21:38:17 +08:00
hoteas 181295e54e 更新研发 2022-02-17 04:10:53 +08:00
hoteas 8cc2499e21 更新研发 2022-02-14 19:11:38 +08:00
hoteas a2c49452b4 更新研发 2022-02-14 19:10:58 +08:00
hoteas ebf0df5ca8 更新研发 2022-01-27 23:41:40 +08:00
hoteas 73bf691ccc 更新研发 2022-01-26 11:45:17 +08:00
hoteas b2e9701826 更新研发 2022-01-23 05:13:19 +08:00
hoteas 789b0a14d1 更新研发 2022-01-22 16:12:02 +08:00
hoteas 3ee64fcd8c 更新研发 2022-01-20 07:15:14 +08:00
hoteas 527503b0d9 企业画像 2022-01-19 05:38:49 +08:00
hoteas a95b2fccd7 更新研发 2022-01-17 04:47:39 +08:00
hoteas 7e2abb43e3 权限模块开发 2022-01-12 17:33:20 +08:00
hoteas 48fd753a96 权限模块开发 2022-01-10 13:23:39 +08:00
hoteas 136232dd57 修复太过于严格的bug 2022-01-03 01:42:35 +08:00
hoteas 008f19355c 增加自适应模式 2021-12-31 02:38:51 +08:00
hoteas 1fc0a5bbbc 增加自适应模式 2021-12-30 22:19:52 +08:00
hoteas ce099b8fc8 增加自适应模式 2021-12-29 00:46:07 +08:00
hoteas 9c00ac6ba1 增加自适应模式 2021-12-28 09:26:26 +08:00
hoteas a5c002bbce 增加自适应模式 2021-12-27 21:30:33 +08:00
hoteas cf50a699a6 增加自适应模式 2021-12-27 21:30:24 +08:00
hoteas 662003c0ca 增加自适应模式 2021-12-27 20:40:16 +08:00
hoteas f24de2562a 优化系统 2021-12-27 18:21:41 +08:00
hoteas b84bd7e16f 优化系统 2021-12-27 14:09:49 +08:00
hoteas 2fb6abf53a Merge branch 'master' into myhs
# Conflicts:
#	example/admin/init.go
#	example/bzyy.exe
#	example/main.go
2021-12-27 14:02:39 +08:00
hoteas 2eab29f428 优化系统 2021-12-27 14:01:04 +08:00
hoteas 84ee0d259f 优化系统 2021-12-27 14:00:08 +08:00
hoteas eccab42fc8 优化系统 2021-12-18 00:07:35 +08:00
hoteas 1465ba36d3 优化系统 2021-12-17 14:37:41 +08:00
hoteas 8380b097b2 调试 2021-12-17 01:21:08 +08:00
hoteas 6b8f901163 调试 2021-12-16 13:40:19 +08:00
hoteas bb16f0a75b 调试 2021-12-16 13:24:31 +08:00
hoteas 84dbc5d71e 出入库完成 2021-12-16 10:49:35 +08:00
hoteas 166eeee64c 出入库完成 2021-12-15 09:24:41 +08:00
hoteas 7a649fd652 出入库完成 2021-12-15 05:56:31 +08:00
hoteas 94ae568526 书写前端接口 2021-12-12 04:22:30 +08:00
hoteas 9ec597f26c 书写前端接口 2021-12-11 23:53:47 +08:00
hoteas 388bc5006d 书写前端代码 2021-12-11 17:59:02 +08:00
hoteas 0e33c2ad9d ocr增加 2021-12-09 11:16:15 +08:00
hoteas af726fbcfb ocr增加 2021-12-09 10:58:53 +08:00
hoteas 1e82a5964d 优化makecode 2021-11-29 03:27:07 +08:00
hoteas d62ba8b0cd 优化makecode 2021-11-23 18:31:00 +08:00
hoteas 320ebe25ec 优化makecode 2021-11-18 12:22:14 +08:00
hoteas 68257d1742 绵阳宏升代码优化 2021-11-15 03:35:13 +08:00
hoteas 80d167cb1b 绵阳宏升代码优化 2021-11-15 03:34:45 +08:00
hoteas cd911e8fa4 巴中代码提交 2021-11-15 03:32:50 +08:00
hoteas faa6fcb00c 初次提交 2021-11-15 03:30:21 +08:00
hoteas 836c1f461f 初次提交 2021-11-15 03:28:14 +08:00
hoteas 97b2f54383 初次提交 2021-11-15 03:26:54 +08:00
hoteas 9d5f8438c5 初次提交 2021-11-13 21:06:29 +08:00
hoteas 3f7963e7cf 初次提交 2021-11-08 09:16:28 +08:00
hoteas 269df85d27 初次提交 2021-11-08 09:15:52 +08:00
hoteas d28c6863e4 初次提交 2021-11-08 06:50:37 +08:00
hoteas bba4990ccc 完善访问日志 2021-11-08 06:49:34 +08:00
hoteas c57afd6a5d 修复短信发送bug 2021-10-27 00:27:24 +08:00
hoteas 25f355c8d0 增加天府通办登录 2021-10-25 23:18:27 +08:00
hoteas b1b0673e69 修复bug 2021-10-21 23:20:58 +08:00
hoteas 72c086d726 修复bug 2021-10-21 23:19:32 +08:00
hoteas 3810ba6c0b 修复bug 2021-10-21 22:52:40 +08:00
hoteas 5c775b4539 修复bug 2021-10-18 04:49:55 +08:00
hoteas deb3e54cc3 修复bug 2021-09-25 04:36:07 +08:00
hoteas d1a8f6c668 短信变更 2021-09-24 15:01:03 +08:00
hoteas 2291ba7402 巴中恩阳适配 2021-09-24 10:49:07 +08:00
hoteas 20390091f2 巴中恩阳适配 2021-09-17 04:45:43 +08:00
hoteas 123d819b0f 开始新增代码生成配置2.0功能,配置文件格式规定完成 2021-09-17 04:00:49 +08:00
hoteas 30e275a27d 开始新增代码生成配置2.0功能,配置文件格式规定完成 2021-09-16 04:33:10 +08:00
hoteas 1a53f587e8 增加表关联新建功能,同时修复数据库bug 2021-09-12 06:14:01 +08:00
hoteas 9c3ba81135 测试 2021-09-12 05:35:14 +08:00
hoteas 62cf625fe9 增加表关联新建功能,同时修复数据库bug 2021-08-30 07:36:17 +08:00
hoteas e1f4876621 增加表关联新建功能,同时修复数据库bug 2021-08-29 06:08:19 +08:00
hoteas b480659a22 增加表关联新建功能,同时修复数据库bug 2021-08-28 13:06:00 +08:00
hoteas 09b1d37ae3 增加表关联新建功能,同时修复数据库bug 2021-08-28 13:05:12 +08:00
hoteas 47b28e7b57 开始新增代码生成配置2.0功能,配置文件格式规定完成 2021-07-21 00:55:59 +08:00
hoteas 9cd7ad34b3 修复浏览器cookie不识别 2021-07-21 00:09:13 +08:00
hoteas d736a74198 增加表关联新建功能,同时修复数据库bug 2021-07-14 00:48:34 +08:00
hoteas ada4a926c0 增加表关联新建功能,同时修复数据库bug 2021-07-07 04:08:40 +08:00
hoteas 4ad401bafc 增加上传接口 2021-07-05 02:20:10 +08:00
hoteas 05c8159601 增加上传接口 2021-07-04 04:03:29 +08:00
hoteas efb6cb980e 优化 2021-06-18 04:56:22 +08:00
hoteas 00ad6487b6 加入树节点功能 2021-06-16 06:10:57 +08:00
hoteas 9aa836a72c 加入树节点功能 2021-06-14 01:19:05 +08:00
hoteas 9ea6082d04 接入搜索功能 2021-06-13 10:40:19 +08:00
hoteas 9e595ab6e8 接入搜索功能 2021-06-13 09:53:37 +08:00
hoteas 8b6dd5fdad 接入搜索功能 2021-06-13 03:08:43 +08:00
hoteas 5c8df885a2 优化表单生成规则 2021-06-12 13:33:35 +08:00
hoteas cc4d91cdbb 优化表单生成规则 2021-06-11 09:41:23 +08:00
hoteas 32167d4721 增加menu自动化添加功能 2021-06-11 08:06:44 +08:00
hoteas 1077f09755 优化代码 2021-06-07 11:32:47 +08:00
hoteas 642bf97272 优化代码 2021-06-06 07:50:58 +08:00
hoteas 4038598470 优化代码 2021-06-06 02:27:22 +08:00
hoteas 79453d4d2a 生成代码,逐步进行优化 2021-06-05 02:18:56 +08:00
hoteas 6aa2b74840 生成代码,逐步进行优化 2021-06-04 10:05:07 +08:00
hoteas a003612810 生成代码,逐步进行优化 2021-06-04 10:04:37 +08:00
hoteas d6c11a5d93 已经接入配置文件,开始准备生成代码 2021-06-04 03:03:48 +08:00
hoteas fe085ce889 已经接入配置文件,开始准备生成代码 2021-06-04 02:57:56 +08:00
hoteas 99933e02f4 引入数据库,代码,配置文件三位一体内容,准备进行一体化配置 2021-06-03 05:31:09 +08:00
hoteas 9af232840c 接入RESTfull风格接口 2021-05-30 00:10:07 +08:00
hoteas 465ea889a2 接入RESTfull风格接口 2021-05-30 00:01:15 +08:00
hoteas c46fdd8985 接入RESTfull风格接口 2021-05-29 02:57:03 +08:00
hoteas 9fd0a5fd61 完善error库 2021-05-29 00:54:27 +08:00
hoteas 95489fcf49 完善error库 2021-05-29 00:41:17 +08:00
hoteas 0e2932ca89 完善error库 2021-05-29 00:37:20 +08:00
hoteas 764d88894e 完善error库 2021-05-29 00:15:13 +08:00
hoteas 339302956a 缓存测试成功 2021-05-28 23:48:33 +08:00
hoteas 1101937028 缓存驱动更换成功,支持3级缓存,memory,以及db 2021-05-28 22:52:22 +08:00
hoteas fc315064e7 optimize log tool 2021-05-25 20:27:24 +08:00
hoteas 740059075a optimize log tool 2021-05-25 19:53:34 +08:00
hoteas 770f0a94c9 optimize log tool 2021-05-25 05:28:56 +08:00
hoteas df07afb744 use logrus to project default log tools 2021-05-25 05:08:17 +08:00
hoteas 9bc930750d 整个包结构重构 2021-05-24 07:27:41 +08:00
hoteas 77ded19742 move redis code to package hotime 2021-05-24 06:16:32 +08:00
hoteas 2632517fab mysql add master and slave mode 2021-05-24 06:14:58 +08:00
hoteas c8e926446e add cache to framework 2021-05-24 05:47:56 +08:00
hoteas 253f836571 调整配置项设置 2021-05-23 03:35:49 +08:00
hoteas babf6595ee 测试demo调整 2021-05-22 04:52:03 +08:00
hoteas 91dc207a78 增加readme文件和授权文件 2021-04-30 00:27:12 +08:00
91 changed files with 10598 additions and 1529 deletions
+2 -1
View File
@@ -1,2 +1,3 @@
/.idea/*
.idea
.idea
/example/config/app.json
View File
+208
View File
@@ -0,0 +1,208 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution
as defined by Sections 1 through 9 of that document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of that definition, "control" means (i) the power, direct
or indirect, to cause the direction or management of such entity, whether
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by that License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the Appendix
below).
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of that License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative
Works thereof, that is intentionally submitted to Licensor for inclusion in
the Work by the copyright owner or by an individual or Legal Entity authorized
to submit on behalf of the copyright owner. For the purposes of that definition,
"submitted" means any form of electronic, verbal, or written communication
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently incorporated
within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of that
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of that License,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in that section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise
transfer the Work, where such license applies only to those patent claims
licensable by such Contributor that are necessarily infringed by their Contribution(s)
alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses granted to You
under that License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy
of that License; and
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source
form of the Work, excluding those notices that do not pertain to any part
of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction,
or distribution of Your modifications, or for any such Derivative Works as
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in that License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of that License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. that License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under that License.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of that License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with that License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use that file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+6
View File
@@ -0,0 +1,6 @@
# hotime
golang web服务框架
支持数据库dbmysql、sqlite3
支持缓存cacheredismemory,数据库
自带工具类,上下文,以及session等功能
+502 -179
View File
@@ -1,9 +1,14 @@
package hotime
import (
"bytes"
. "code.hoteas.com/golang/hotime/cache"
"code.hoteas.com/golang/hotime/code"
. "code.hoteas.com/golang/hotime/common"
. "code.hoteas.com/golang/hotime/db"
. "code.hoteas.com/golang/hotime/log"
"database/sql"
"encoding/json"
"github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"net/url"
@@ -11,61 +16,76 @@ import (
"path/filepath"
"strconv"
"strings"
"time"
)
type Application struct {
MakeCodeRouter map[string]*code.MakeCode
MethodRouter
Router
contextBase
ContextBase
Error
Log *logrus.Logger
WebConnectLog *logrus.Logger
Port string //端口号
TLSPort string //ssl访问端口号
connectListener []func(this *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理
connectDbFunc func(err ...*Error) *sql.DB
connectListener []func(that *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理
connectDbFunc func(err ...*Error) (master, slave *sql.DB)
configPath string
Config Map
Db HoTimeDB
Server *http.Server
CacheIns
sessionLong CacheIns
sessionShort CacheIns
*HoTimeCache
*http.Server
http.Handler
}
func (this *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
this.handler(w, req)
func (that *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
that.handler(w, req)
}
//启动实例
func (this *Application) Run(router Router) {
// Run 启动实例
func (that *Application) Run(router Router) {
//如果没有设置配置自动生成配置
if this.configPath == "" || len(this.Config) == 0 {
this.SetConfig()
if that.configPath == "" || len(that.Config) == 0 {
that.SetConfig()
}
//防止手动设置缓存误伤
if this.CacheIns == nil {
this.SetCache(CacheIns(&CacheMemory{}))
if that.HoTimeCache == nil {
that.SetCache()
}
//防止手动设置session误伤
if this.sessionShort == nil && this.sessionLong == nil {
if this.connectDbFunc == nil {
this.SetSession(CacheIns(&CacheMemory{}), nil)
} else {
this.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &this.Db, Time: this.Config.GetInt64("cacheLongTime")}))
//if that.sessionShort == nil && that.sessionLong == nil {
// if that.connectDbFunc == nil {
// that.SetSession(CacheIns(&CacheMemory{}), nil)
// } else {
// that.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &that.Db, Time: that.Config.GetInt64("cacheLongTime")}))
// }
//
//}
//that.Router = router
if that.Router == nil {
that.Router = Router{}
}
for k, v := range router {
if that.Router[k] == nil {
that.Router[k] = v
}
for k1, v1 := range v {
that.Router[k][k1] = v1
}
}
this.Router = router
//重新设置MethodRouter//直达路由
this.MethodRouter = MethodRouter{}
that.MethodRouter = MethodRouter{}
modeRouterStrict := true
if this.Config.Get("modeRouterStrict").(bool) == false {
if that.Config.GetBool("modeRouterStrict") == false {
modeRouterStrict = false
}
if router != nil {
for pk, pv := range router {
if that.Router != nil {
for pk, pv := range that.Router {
if !modeRouterStrict {
pk = strings.ToLower(pk)
}
@@ -79,7 +99,7 @@ func (this *Application) Run(router Router) {
if !modeRouterStrict {
mk = strings.ToLower(mk)
}
this.MethodRouter["/"+pk+"/"+ck+"/"+mk] = mv
that.MethodRouter["/"+pk+"/"+ck+"/"+mk] = mv
}
}
}
@@ -87,181 +107,173 @@ func (this *Application) Run(router Router) {
}
}
//this.Port = port
this.Port = this.Config.GetString("port")
this.TLSPort = this.Config.GetString("tlsPort")
//that.Port = port
that.Port = that.Config.GetString("port")
that.TLSPort = that.Config.GetString("tlsPort")
if this.connectDbFunc != nil && (this.Db.DB == nil || this.Db.DB.Ping() != nil) {
this.Db.SetConnect(this.connectDbFunc)
}
if this.CacheIns == nil {
this.CacheIns = CacheIns(&CacheMemory{Map: Map{}, Time: this.Config.GetInt64("cacheShortTime")})
if that.connectDbFunc != nil && (that.Db.DB == nil || that.Db.DB.Ping() != nil) {
that.Db.SetConnect(that.connectDbFunc)
}
//异常处理
defer func() {
if err := recover(); err != nil {
//this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
logFmt(err, 2, LOG_ERROR)
//that.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
that.Log.Warn(err)
this.Run(router)
that.Run(router)
}
}()
this.Server = &http.Server{}
that.Server = &http.Server{}
if !IsRun {
IsRun = true
}
ch := make(chan int)
if ObjToCeilInt(this.Port) != 0 {
if ObjToCeilInt(that.Port) != 0 {
go func() {
App[this.Port] = this
this.Server.Handler = this
App[that.Port] = that
that.Server.Handler = that
//启动服务
this.Server.Addr = ":" + this.Port
err := this.Server.ListenAndServe()
logFmt(err, 2)
that.Server.Addr = ":" + that.Port
err := that.Server.ListenAndServe()
that.Log.Error(err)
ch <- 1
}()
}
if ObjToCeilInt(this.TLSPort) != 0 {
if ObjToCeilInt(that.TLSPort) != 0 {
go func() {
App[this.TLSPort] = this
this.Server.Handler = this
App[that.TLSPort] = that
that.Server.Handler = that
//启动服务
this.Server.Addr = ":" + this.TLSPort
err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey"))
logFmt(err, 2)
that.Server.Addr = ":" + that.TLSPort
err := that.Server.ListenAndServeTLS(that.Config.GetString("tlsCert"), that.Config.GetString("tlsKey"))
that.Log.Error(err)
ch <- 2
}()
}
if ObjToCeilInt(this.Port) == 0 && ObjToCeilInt(this.TLSPort) == 0 {
logFmt("没有端口启用", 2, LOG_INFO)
if ObjToCeilInt(that.Port) == 0 && ObjToCeilInt(that.TLSPort) == 0 {
that.Log.Error("没有端口启用")
return
}
value := <-ch
logFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
that.Log.Error("启动服务失败 : " + ObjToStr(value))
}
//启动实例
func (this *Application) SetConnectDB(connect func(err ...*Error) *sql.DB) {
// SetConnectDB 启动实例
func (that *Application) SetConnectDB(connect func(err ...*Error) (master, slave *sql.DB)) {
//this.Db.DBCached=false
//if this.Config.GetCeilInt("dbCached")!=0{
// this.Db.DBCached=true
//}
that.connectDbFunc = connect
this.connectDbFunc = connect
this.Db.SetConnect(this.connectDbFunc)
this.Db.DBCached = false
if this.Config.GetCeilInt("dbCached") != 0 {
this.Db.DBCached = true
}
this.Db.Type = this.Config.GetString("dbType")
that.Db.SetConnect(that.connectDbFunc, &that.Error)
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetSession(short CacheIns, Long CacheIns) {
this.sessionLong = Long
this.sessionShort = short
}
//默认配置缓存和session实现
func (this *Application) SetDefault(connect func(err ...*Error) *sql.DB) {
this.SetConfig()
// SetDefault 默认配置缓存和session实现
func (that *Application) SetDefault(connect func(err ...*Error) (*sql.DB, *sql.DB)) {
that.SetConfig()
if connect != nil {
this.connectDbFunc = connect
this.Db.SetConnect(this.connectDbFunc)
that.connectDbFunc = connect
that.Db.SetConnect(that.connectDbFunc)
}
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetCache(cache CacheIns) {
this.CacheIns = cache
// SetCache 设置配置文件路径全路径或者相对路径
func (that *Application) SetCache() {
cacheIns := HoTimeCache{}
cacheIns.Init(that.Config.GetMap("cache"), HoTimeDBInterface(&that.Db), &that.Error)
that.HoTimeCache = &cacheIns
//mode生产模式开启的时候才开启数据库缓存,防止调试出问题
if that.Config.GetInt("mode") == 0 {
that.Db.HoTimeCache = &cacheIns
}
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetConfig(configPath ...string) {
// SetConfig 设置配置文件路径全路径或者相对路径
func (that *Application) SetConfig(configPath ...string) {
that.Log = GetLog("", true)
that.Error = Error{Logger: that.Log}
if len(configPath) != 0 {
this.configPath = configPath[0]
that.configPath = configPath[0]
}
if this.configPath == "" {
this.configPath = "config/config.json"
if that.configPath == "" {
that.configPath = "config/config.json"
}
//加载配置文件
btes, err := ioutil.ReadFile(this.configPath)
this.Config = DeepCopyMap(Config).(Map)
btes, err := ioutil.ReadFile(that.configPath)
that.Config = DeepCopyMap(Config).(Map)
if err == nil {
cmap := Map{}
//文件是否损坏
cmap.JsonToMap(string(btes), &this.Error)
cmap.JsonToMap(string(btes), &that.Error)
for k, v := range cmap {
this.Config[k] = v //程序配置
that.Config[k] = v //程序配置
Config[k] = v //系统配置
}
} else {
logFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
that.Log.Error("配置文件不存在,或者配置出错,使用缺省默认配置")
}
that.Log = GetLog(that.Config.GetString("logFile"), true)
that.Error = Error{Logger: that.Log}
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
}
//文件如果损坏则不写入配置防止配置文件数据丢失
if this.Error.GetError() == nil {
var configByte bytes.Buffer
if that.Error.GetError() == nil {
//var configByte bytes.Buffer
err = json.Indent(&configByte, []byte(this.Config.ToJsonString()), "", "\t")
//判断配置文件是否序列有变化有则修改配置,五则不变
//判断配置文件是否序列有变化,有则修改配置,无则不变
//fmt.Println(len(btes))
if len(btes) != 0 && configByte.String() == string(btes) {
configStr := that.Config.ToJsonString()
if len(btes) != 0 && configStr == string(btes) {
return
}
//写入配置说明
var configNoteByte bytes.Buffer
json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
//var configNoteByte bytes.Buffer
configNoteStr := ConfigNote.ToJsonString()
//_ = json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir)
err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend)
_ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir)
err = ioutil.WriteFile(that.configPath, []byte(configStr), os.ModePerm)
if err != nil {
this.Error.SetError(err)
that.Error.SetError(err)
}
ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend)
_ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", []byte(configNoteStr), os.ModePerm)
}
}
//连接判断,返回true继续传输至控制层,false则停止传输
func (this *Application) SetConnectListener(lis func(this *Context) bool) {
this.connectListener = append(this.connectListener, lis)
// SetConnectListener 连接判断,返回false继续传输至控制层,true则停止传输
func (that *Application) SetConnectListener(lis func(that *Context) (isFinished bool)) {
that.connectListener = append(that.connectListener, lis)
}
//网络错误
//func (this *Application) session(w http.ResponseWriter, req *http.Request) {
//func (that *Application) session(w http.ResponseWriter, req *http.Request) {
//
//}
//序列化链接
func (this *Application) urlSer(url string) (string, []string) {
func (that *Application) urlSer(url string) (string, []string) {
q := strings.Index(url, "?")
if q == -1 {
q = len(url)
@@ -282,9 +294,10 @@ func (this *Application) urlSer(url string) (string, []string) {
//访问
func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
nowUnixTime := time.Now()
_, s := this.urlSer(req.RequestURI)
_, s := that.urlSer(req.RequestURI)
//获取cookie
// 如果cookie存在直接将sessionId赋值为cookie.Value
// 如果cookie不存在就查找传入的参数中是否有token
@@ -292,20 +305,24 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
// 如果token存在就判断token是否在Session中有保存
// 如果有取出token并复制给cookie
// 没有保存就生成随机的session
cookie, err := req.Cookie(this.Config.GetString("sessionName"))
cookie, err := req.Cookie(that.Config.GetString("sessionName"))
sessionId := Md5(strconv.Itoa(Rand(10)))
token := req.FormValue("token")
//isFirst:=false
if err != nil || (len(token) == 32 && cookie.Value != token) {
if len(token) == 32 {
sessionId = token
}
//else{
// isFirst=true;
//}
http.SetCookie(w, &http.Cookie{Name: this.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
} else {
needSetCookie := ""
token := req.Header.Get("Authorization")
if len(token) != 32 {
token = req.FormValue("token")
}
//没有cookie或者cookie不等于token
//有token优先token
if len(token) == 32 {
sessionId = token
//没有token,则查阅session
} else if err == nil && cookie.Value != "" {
sessionId = cookie.Value
//session也没有则判断是否创建cookie
} else {
needSetCookie = sessionId
}
unescapeUrl, err := url.QueryUnescape(req.RequestURI)
@@ -313,71 +330,71 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
unescapeUrl = req.RequestURI
}
//访问实例
context := Context{SessionIns: SessionIns{SessionId: sessionId,
LongCache: this.sessionLong,
ShortCache: this.sessionShort,
},
CacheIns: this.CacheIns,
Resp: w, Req: req, Application: this, RouterString: s, Config: this.Config, Db: &this.Db, HandlerStr: unescapeUrl}
context := Context{SessionIns: SessionIns{SessionId: sessionId, HoTimeCache: that.HoTimeCache},
Resp: w, Req: req, Application: that, RouterString: s, Config: that.Config, Db: &that.Db,
HandlerStr: unescapeUrl}
//header默认设置
header := w.Header()
header.Set("Content-Type", "text/html; charset=utf-8")
//url去掉参数并序列化
context.HandlerStr, context.RouterString = this.urlSer(context.HandlerStr)
context.HandlerStr, context.RouterString = that.urlSer(context.HandlerStr)
//跨域设置
this.crossDomain(&context)
//是否展示日志
if this.Config.GetInt("connectLogShow") != 0 {
logFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
}
that.crossDomain(&context, needSetCookie)
defer func() {
//是否展示日志
if that.WebConnectLog != nil {
ipStr := Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))
//负载均衡优化
if ipStr == "127.0.0.1" {
if req.Header.Get("X-Forwarded-For") != "" {
ipStr = req.Header.Get("X-Forwarded-For")
} else if req.Header.Get("X-Real-IP") != "" {
ipStr = req.Header.Get("X-Real-IP")
}
}
that.WebConnectLog.Infoln(ipStr, context.Req.Method,
"time cost:", ObjToFloat64(time.Now().UnixNano()-nowUnixTime.UnixNano())/1000000.00, "ms",
"data length:", ObjToFloat64(context.DataSize)/1000.00, "KB", context.HandlerStr)
}
}()
//访问拦截true继续false暂停
connectListenerLen := len(this.connectListener)
if connectListenerLen != 0 {
for i := 0; i < connectListenerLen; i++ {
connectListenerLen := len(that.connectListener)
if !this.connectListener[i](&context) {
for i := connectListenerLen - 1; i >= 0; i-- {
context.View()
return
}
if that.connectListener[i](&context) {
context.View()
return
}
}
//接口服务
//if len(s) == 3 {
// //如果满足规则则路由到对应控制器去
// if this.Router[s[0]] != nil && this.Router[s[0]][s[1]] != nil && this.Router[s[0]][s[1]][s[2]] != nil {
// //控制层
// this.Router[s[0]][s[1]][s[2]](&context)
// //header.Set("Content-Type", "text/html; charset=utf-8")
// context.View()
// return
// }
//
//}
//验证接口严格模式
modeRouterStrict := this.Config.Get("modeRouterStrict").(bool)
modeRouterStrict := that.Config.GetBool("modeRouterStrict")
tempHandlerStr := context.HandlerStr
if !modeRouterStrict {
tempHandlerStr = strings.ToLower(tempHandlerStr)
}
//执行接口
if this.MethodRouter[tempHandlerStr] != nil {
this.MethodRouter[tempHandlerStr](&context)
if that.MethodRouter[tempHandlerStr] != nil {
that.MethodRouter[tempHandlerStr](&context)
context.View()
return
}
//url赋值
path := this.Config.GetString("tpt") + tempHandlerStr
path := that.Config.GetString("tpt") + tempHandlerStr
//判断是否为默认
if path[len(path)-1] == '/' {
defFile := this.Config.GetSlice("defFile")
defFile := that.Config.GetSlice("defFile")
for i := 0; i < len(defFile); i++ {
temp := path + defFile.GetString(i)
@@ -401,12 +418,20 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
//设置header
delete(header, "Content-Type")
if this.Config.GetInt("debug") != 1 {
if that.Config.GetInt("mode") == 0 {
header.Set("Cache-Control", "public")
} else {
header.Set("Cache-Control", "no-cache")
}
if strings.Index(path, ".m3u8") != -1 {
header.Add("Content-Type", "audio/mpegurl")
t := strings.LastIndex(path, ".")
if t != -1 {
tt := path[t:]
if MimeMaps[tt] != "" {
header.Add("Content-Type", MimeMaps[tt])
}
}
//w.Write(data)
@@ -414,32 +439,66 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
}
func (this *Application) crossDomain(context *Context) {
func (that *Application) crossDomain(context *Context, sessionId string) {
//没有跨域设置
if context.Config.GetString("crossDomain") == "" {
if sessionId != "" {
http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
}
return
}
header := context.Resp.Header()
header.Set("Access-Control-Allow-Origin", "*")
header.Set("Access-Control-Allow-Methods", "*")
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Expose-Headers", "*")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if context.Config.GetString("crossDomain") != "*" {
header.Set("Access-Control-Allow-Origin", this.Config.GetString("crossDomain"))
//不跨域,则不设置
remoteHost := context.Req.Host
if context.Config.GetString("port") == "80" || context.Config.GetString("port") == "443" {
remoteHost = remoteHost + ":" + context.Config.GetString("port")
}
if context.Config.GetString("crossDomain") != "auto" {
//不跨域,则不设置
if strings.Contains(context.Config.GetString("crossDomain"), remoteHost) {
if sessionId != "" {
http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
}
return
}
header.Set("Access-Control-Allow-Origin", that.Config.GetString("crossDomain"))
// 后端设置,2592000单位秒,这里是30天
header.Set("Access-Control-Max-Age", "2592000")
//header.Set("Access-Control-Allow-Origin", "*")
header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE")
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Expose-Headers", "*")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if sessionId != "" {
//跨域允许需要设置cookie的允许跨域https才有效果
context.Resp.Header().Set("Set-Cookie", that.Config.GetString("sessionName")+"="+sessionId+"; Path=/; SameSite=None; Secure")
}
return
}
origin := context.Req.Header.Get("Origin")
if origin != "" {
header.Set("Access-Control-Allow-Origin", origin)
refer := context.Req.Header.Get("Referer")
if (origin != "" && strings.Contains(origin, remoteHost)) || strings.Contains(refer, remoteHost) {
if sessionId != "" {
http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
}
return
}
refer := context.Req.Header.Get("Referer")
if refer != "" {
if origin != "" {
header.Set("Access-Control-Allow-Origin", origin)
//return
} else if refer != "" {
tempInt := 0
lastInt := strings.IndexFunc(refer, func(r rune) bool {
if r == '/' && tempInt > 8 {
@@ -454,5 +513,269 @@ func (this *Application) crossDomain(context *Context) {
}
refer = Substr(refer, 0, lastInt)
header.Set("Access-Control-Allow-Origin", refer)
//header.Set("Access-Control-Allow-Origin", "*")
}
header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE")
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Expose-Headers", "*")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if sessionId != "" {
//跨域允许需要设置cookie的允许跨域https才有效果
context.Resp.Header().Set("Set-Cookie", that.Config.GetString("sessionName")+"="+sessionId+"; Path=/; SameSite=None; Secure")
}
}
//Init 初始化application
func Init(config string) *Application {
appIns := Application{}
//手动模式,
appIns.SetConfig(config)
SetDB(&appIns)
appIns.SetCache()
codeConfig := appIns.Config.GetSlice("codeConfig")
if codeConfig != nil {
for k, _ := range codeConfig {
codeMake := codeConfig.GetMap(k)
if codeMake == nil {
continue
}
//codeMake["table"] = k
if appIns.MakeCodeRouter == nil {
appIns.MakeCodeRouter = map[string]*code.MakeCode{}
}
if codeMake.GetString("name") == "" {
codeMake["name"] = codeMake.GetString("table")
}
if appIns.Config.GetInt("mode") > 0 {
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{}
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
} else {
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{}
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(nil, codeMake)
}
//接入动态代码层
if appIns.Router == nil {
appIns.Router = Router{}
}
//appIns.Router[codeMake.GetString("name")] = TptProject
appIns.Router[codeMake.GetString("name")] = Proj{}
for k2, _ := range TptProject {
appIns.Router[codeMake.GetString("name")][k2] = Ctr{}
for k3, v3 := range TptProject[k2] {
appIns.Router[codeMake.GetString("name")][k2][k3] = v3
}
}
for k1, _ := range appIns.MakeCodeRouter[codeMake.GetString("name")].TableColumns {
appIns.Router[codeMake.GetString("name")][k1] = appIns.Router[codeMake.GetString("name")]["hotimeCommon"]
}
go func() {
setMakeCodeLintener(codeMake.GetString("name"), &appIns)
}()
}
}
return &appIns
}
// SetDB 智能数据库设置
func SetDB(appIns *Application) {
db := appIns.Config.GetMap("db")
dbSqlite := db.GetMap("sqlite")
dbMysql := db.GetMap("mysql")
if db != nil && dbSqlite != nil {
SetSqliteDB(appIns, dbSqlite)
}
if db != nil && dbMysql != nil {
SetMysqlDB(appIns, dbMysql)
}
}
func SetMysqlDB(appIns *Application, config Map) {
appIns.Db.Type = "mysql"
appIns.Db.DBName = config.GetString("name")
appIns.Db.Prefix = config.GetString("prefix")
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
//master数据库配置
query := config.GetString("user") + ":" + config.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + config.GetString("port") + ")/" + config.GetString("name") + "?charset=utf8"
DB, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = DB
//slave数据库配置
configSlave := config.GetMap("slave")
if configSlave != nil {
query := configSlave.GetString("user") + ":" + configSlave.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + configSlave.GetString("port") + ")/" + configSlave.GetString("name") + "?charset=utf8"
DB1, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
slave = DB1
}
return master, slave
//return DB
})
}
func SetSqliteDB(appIns *Application, config Map) {
appIns.Db.Type = "sqlite"
appIns.Db.Prefix = config.GetString("prefix")
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
db, e := sql.Open("sqlite3", config.GetString("path"))
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = db
return master, slave
})
}
func setMakeCodeLintener(name string, appIns *Application) {
appIns.SetConnectListener(func(context *Context) (isFinished bool) {
codeIns := appIns.MakeCodeRouter[name]
//文件上传接口
if len(context.RouterString) == 1 && context.RouterString[0] == "file" && context.Req.Method == "POST" {
if context.Session(codeIns.FileConfig.GetString("table")+"_id").Data == nil {
context.Display(2, "你还没有登录")
return true
}
//读取网络文件
fi, fheader, err := context.Req.FormFile("file")
if err != nil {
context.Display(3, err)
return true
}
filePath := context.Config.GetString("filePath")
if filePath == "" {
filePath = "/file/2006/01/02/"
}
path := time.Now().Format(filePath)
e := os.MkdirAll(context.Config.GetString("tpt")+path, os.ModeDir)
if e != nil {
context.Display(3, e)
return true
}
filePath = path + Md5(ObjToStr(RandX(100000, 9999999))) + fheader.Filename[strings.LastIndex(fheader.Filename, "."):]
newFile, e := os.Create(context.Config.GetString("tpt") + filePath)
if e != nil {
context.Display(3, e)
return true
}
_, e = io.Copy(newFile, fi)
if e != nil {
context.Display(3, e)
return true
}
context.Display(0, filePath)
return true
}
if len(context.RouterString) < 2 || appIns.MakeCodeRouter[context.RouterString[0]] == nil {
return isFinished
}
if len(context.RouterString) > 1 && context.RouterString[0] == name {
if context.RouterString[1] == "hotime" && context.RouterString[2] == "login" {
return isFinished
}
if context.RouterString[1] == "hotime" && context.RouterString[2] == "logout" {
return isFinished
}
if context.Session(codeIns.FileConfig.GetString("table")+"_id").Data == nil {
context.Display(2, "你还没有登录")
return true
}
}
if len(context.RouterString) < 2 || len(context.RouterString) > 3 ||
!(context.Router[context.RouterString[0]] != nil &&
context.Router[context.RouterString[0]][context.RouterString[1]] != nil) {
return isFinished
}
//排除无效操作
if len(context.RouterString) == 2 &&
context.Req.Method != "GET" &&
context.Req.Method != "POST" {
return isFinished
}
//列表检索
if len(context.RouterString) == 2 &&
context.Req.Method == "GET" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["search"] == nil {
return isFinished
}
context.Router[context.RouterString[0]][context.RouterString[1]]["search"](context)
}
//新建
if len(context.RouterString) == 2 &&
context.Req.Method == "POST" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["add"] == nil {
return true
}
context.Router[context.RouterString[0]][context.RouterString[1]]["add"](context)
}
if len(context.RouterString) == 3 &&
context.Req.Method == "POST" {
return isFinished
}
//查询单条
if len(context.RouterString) == 3 &&
context.Req.Method == "GET" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["info"] == nil {
return isFinished
}
context.Router[context.RouterString[0]][context.RouterString[1]]["info"](context)
}
//更新
if len(context.RouterString) == 3 &&
context.Req.Method == "PUT" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["update"] == nil {
return true
}
context.Router[context.RouterString[0]][context.RouterString[1]]["update"](context)
}
//移除
if len(context.RouterString) == 3 &&
context.Req.Method == "DELETE" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["remove"] == nil {
return true
}
context.Router[context.RouterString[0]][context.RouterString[1]]["remove"](context)
}
context.View()
return true
})
}
+277
View File
@@ -0,0 +1,277 @@
package cache
import (
. "code.hoteas.com/golang/hotime/common"
"errors"
)
// HoTimeCache 可配置memorydbredis,默认启用memory,默认优先级为memory>redis>db,memory与数据库缓存设置项一致,
//缓存数据填充会自动反方向反哺,加入memory缓存过期将自动从redis更新,但memory永远不会更新redis,如果是集群建议不要开启memory,配置即启用
type HoTimeCache struct {
*Error
dbCache *CacheDb
redisCache *CacheRedis
memoryCache *CacheMemory
Config Map
}
func (that *HoTimeCache) Session(key string, data ...interface{}) *Obj {
var reData *Obj
if len(data) == 0 {
//内存缓存有
if that.memoryCache != nil && that.memoryCache.SessionSet {
reData = that.memoryCache.Cache(key, data...)
if reData.Data != nil {
return reData
}
}
//redis缓存有
if that.redisCache != nil && that.redisCache.SessionSet {
reData = that.redisCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil && that.memoryCache.SessionSet {
that.memoryCache.Cache(key, reData.Data)
}
return reData
}
}
//db缓存有
if that.dbCache != nil && that.dbCache.SessionSet {
reData = that.dbCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil && that.memoryCache.SessionSet {
that.memoryCache.Cache(key, reData.Data)
}
if that.redisCache != nil && that.redisCache.SessionSet {
that.redisCache.Cache(key, reData.Data)
}
return reData
}
}
return reData
}
//设置缓存
//设置内存缓存
if that.memoryCache != nil && that.memoryCache.SessionSet {
reData = that.memoryCache.Cache(key, data...)
}
//redis缓存有
if that.redisCache != nil && that.redisCache.SessionSet {
reData = that.redisCache.Cache(key, data...)
}
//redis缓存有
if that.dbCache != nil && that.dbCache.SessionSet {
reData = that.dbCache.Cache(key, data...)
}
return reData
}
func (that *HoTimeCache) Db(key string, data ...interface{}) *Obj {
var reData *Obj
if len(data) == 0 {
//内存缓存有
if that.memoryCache != nil && that.memoryCache.DbSet {
reData = that.memoryCache.Cache(key, data...)
if reData.Data != nil {
return reData
}
}
//redis缓存有
if that.redisCache != nil && that.redisCache.DbSet {
reData = that.redisCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil && that.memoryCache.DbSet {
that.memoryCache.Cache(key, reData.Data)
}
return reData
}
}
//redis缓存有
if that.dbCache != nil && that.dbCache.DbSet {
reData = that.dbCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil && that.memoryCache.DbSet {
that.memoryCache.Cache(key, reData.Data)
}
if that.redisCache != nil && that.redisCache.DbSet {
that.redisCache.Cache(key, reData.Data)
}
return reData
}
}
return reData
}
//设置缓存
//设置内存缓存
if that.memoryCache != nil && that.memoryCache.DbSet {
reData = that.memoryCache.Cache(key, data...)
}
//redis缓存有
if that.redisCache != nil && that.redisCache.DbSet {
reData = that.redisCache.Cache(key, data...)
}
//redis缓存有
if that.dbCache != nil && that.dbCache.DbSet {
reData = that.dbCache.Cache(key, data...)
}
return reData
}
func (that *HoTimeCache) Cache(key string, data ...interface{}) *Obj {
var reData *Obj
if len(data) == 0 {
//内存缓存有
if that.memoryCache != nil {
reData = that.memoryCache.Cache(key, data...)
if reData != nil {
return reData
}
}
//redis缓存有
if that.redisCache != nil {
reData = that.redisCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil {
that.memoryCache.Cache(key, reData.Data)
}
return reData
}
}
//redis缓存有
if that.dbCache != nil {
reData = that.dbCache.Cache(key, data...)
if reData.Data != nil {
if that.memoryCache != nil {
that.memoryCache.Cache(key, reData.Data)
}
if that.redisCache != nil {
that.redisCache.Cache(key, reData.Data)
}
return reData
}
}
return reData
}
//设置缓存
//设置内存缓存
if that.memoryCache != nil {
reData = that.memoryCache.Cache(key, data...)
}
//redis缓存有
if that.redisCache != nil {
reData = that.redisCache.Cache(key, data...)
}
//redis缓存有
if that.dbCache != nil {
reData = that.dbCache.Cache(key, data...)
}
return reData
}
func (that *HoTimeCache) Init(config Map, hotimeDb HoTimeDBInterface, err ...*Error) {
//防止空数据问题
if config == nil {
config = Map{}
}
if err[0] != nil {
that.Error = err[0]
}
that.Config = config
//memory配置初始化
memory := that.Config.GetMap("memory")
if memory == nil {
memory = Map{
"db": true,
"session": true,
"sort": 0,
"timeout": 60 * 60 * 2,
}
}
if memory.Get("db") == nil {
memory["db"] = true
}
if memory.Get("session") == nil {
memory["session"] = true
}
if memory.Get("timeout") == nil {
memory["timeout"] = 60 * 60 * 2
}
that.Config["memory"] = memory
that.memoryCache = &CacheMemory{TimeOut: memory.GetCeilInt64("timeout"),
DbSet: memory.GetBool("db"), SessionSet: memory.GetBool("session")}
if err[0] != nil {
that.memoryCache.SetError(err[0])
}
//db配置初始化
redis := that.Config.GetMap("redis")
if redis != nil {
if redis.GetString("host") == "" || redis.GetString("port") == "" {
if err[0] != nil {
err[0].SetError(errors.New("请检查redis配置host和port配置"))
}
return
}
if redis.Get("db") == nil {
redis["db"] = true
}
if redis.Get("session") == nil {
redis["session"] = true
}
if redis.Get("timeout") == nil {
redis["timeout"] = 60 * 60 * 24 * 15
}
that.Config["redis"] = redis
that.redisCache = &CacheRedis{TimeOut: redis.GetCeilInt64("timeout"),
DbSet: redis.GetBool("db"), SessionSet: redis.GetBool("session"), Host: redis.GetString("host"),
Pwd: redis.GetString("password"), Port: redis.GetCeilInt64("port")}
if err[0] != nil {
that.redisCache.SetError(err[0])
}
}
//db配置初始化
db := that.Config.GetMap("db")
if db != nil {
if db.Get("db") == nil {
db["db"] = false
}
if db.Get("session") == nil {
db["session"] = true
}
if db.Get("timeout") == nil {
db["timeout"] = 60 * 60 * 24 * 30
}
that.Config["db"] = db
that.dbCache = &CacheDb{TimeOut: db.GetCeilInt64("timeout"),
DbSet: db.GetBool("db"), SessionSet: db.GetBool("session"),
Db: hotimeDb}
if err[0] != nil {
that.dbCache.SetError(err[0])
}
}
}
+173
View File
@@ -0,0 +1,173 @@
package cache
import (
. "code.hoteas.com/golang/hotime/common"
"database/sql"
"encoding/json"
"strings"
"time"
)
type HoTimeDBInterface interface {
GetPrefix() string
Query(query string, args ...interface{}) []Map
Exec(query string, args ...interface{}) (sql.Result, *Error)
Get(table string, qu ...interface{}) Map
Select(table string, qu ...interface{}) []Map
Delete(table string, data map[string]interface{}) int64
Update(table string, data Map, where Map) int64
Insert(table string, data map[string]interface{}) int64
GetType() string
}
type CacheDb struct {
TimeOut int64
DbSet bool
SessionSet bool
Db HoTimeDBInterface
*Error
ContextBase
isInit bool
}
func (that *CacheDb) GetError() *Error {
return that.Error
}
func (that *CacheDb) SetError(err *Error) {
that.Error = err
}
func (that *CacheDb) initDbTable() {
if that.isInit {
return
}
if that.Db.GetType() == "mysql" {
dbNames := that.Db.Query("SELECT DATABASE()")
if len(dbNames) == 0 {
return
}
dbName := dbNames[0].GetString("DATABASE()")
res := that.Db.Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbName + "' AND TABLE_NAME='" + that.Db.GetPrefix() + "cached'")
if len(res) != 0 {
that.isInit = true
return
}
_, e := that.Db.Exec("CREATE TABLE `" + that.Db.GetPrefix() + "cached` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `key` varchar(60) DEFAULT NULL, `value` varchar(2000) DEFAULT NULL, `time` bigint(20) DEFAULT NULL, `endtime` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=198740 DEFAULT CHARSET=utf8")
if e.GetError() == nil {
that.isInit = true
}
}
if that.Db.GetType() == "sqlite" {
res := that.Db.Query(`select * from sqlite_master where type = 'table' and name = '` + that.Db.GetPrefix() + `cached'`)
if len(res) != 0 {
that.isInit = true
return
}
_, e := that.Db.Exec(`CREATE TABLE "` + that.Db.GetPrefix() + `cached" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"key" TEXT(60),
"value" TEXT(2000),
"time" integer,
"endtime" integer
);`)
if e.GetError() == nil {
that.isInit = true
}
}
}
//获取Cache键只能为string类型
func (that *CacheDb) get(key string) interface{} {
cached := that.Db.Get("cached", "*", Map{"key": key})
if cached == nil {
return nil
}
//data:=cacheMap[key];
if cached.GetInt64("endtime") <= time.Now().Unix() {
that.Db.Delete("cached", Map{"id": cached.GetString("id")})
return nil
}
data := Map{}
data.JsonToMap(cached.GetString("value"))
return data.Get("data")
}
//key value ,时间为时间戳
func (that *CacheDb) set(key string, value interface{}, tim int64) {
bte, _ := json.Marshal(Map{"data": value})
num := that.Db.Update("cached", Map{"value": string(bte), "time": time.Now().UnixNano(), "endtime": tim}, Map{"key": key})
if num == int64(0) {
that.Db.Insert("cached", Map{"value": string(bte), "time": time.Now().UnixNano(), "endtime": tim, "key": key})
}
//随机执行删除命令
if Rand(1000) > 950 {
that.Db.Delete("cached", Map{"endtime[<]": time.Now().Unix()})
}
}
func (that *CacheDb) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
that.Db.Delete("cached", Map{"key": key + "%"})
} else {
that.Db.Delete("cached", Map{"key": key})
}
}
func (that *CacheDb) Cache(key string, data ...interface{}) *Obj {
that.initDbTable()
if len(data) == 0 {
return &Obj{Data: that.get(key)}
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
that.delete(key)
return &Obj{Data: nil}
}
if len(data) == 1 {
if that.TimeOut == 0 {
//that.Time = Config.GetInt64("cacheLongTime")
}
tim += that.TimeOut
}
if len(data) == 2 {
that.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if that.GetError() == nil {
tim = tim + tempt
}
}
that.set(key, data[0], tim)
return &Obj{Data: nil}
}
+158
View File
@@ -0,0 +1,158 @@
package cache
import (
. "code.hoteas.com/golang/hotime/common"
"strings"
"sync"
"time"
)
type CacheMemory struct {
TimeOut int64
DbSet bool
SessionSet bool
Map
*Error
ContextBase
mutex *sync.RWMutex
}
func (that *CacheMemory) GetError() *Error {
return that.Error
}
func (that *CacheMemory) SetError(err *Error) {
that.Error = err
}
//获取Cache键只能为string类型
func (that *CacheMemory) get(key string) interface{} {
that.Error.SetError(nil)
if that.Map == nil {
that.Map = Map{}
}
if that.Map[key] == nil {
return nil
}
data := that.Map.Get(key, that.Error).(cacheData)
if that.Error.GetError() != nil {
return nil
}
if data.time < time.Now().Unix() {
delete(that.Map, key)
return nil
}
return data.data
}
func (that *CacheMemory) refreshMap() {
go func() {
that.mutex.Lock()
defer that.mutex.Unlock()
for key, v := range that.Map {
data := v.(cacheData)
if data.time <= time.Now().Unix() {
delete(that.Map, key)
}
}
}()
}
//key value ,时间为时间戳
func (that *CacheMemory) set(key string, value interface{}, time int64) {
that.Error.SetError(nil)
var data cacheData
if that.Map == nil {
that.Map = Map{}
}
dd := that.Map[key]
if dd == nil {
data = cacheData{}
} else {
data = dd.(cacheData)
}
data.time = time
data.data = value
that.Map.Put(key, data)
}
func (that *CacheMemory) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
for k, _ := range that.Map {
if strings.Index(k, key) != -1 {
delete(that.Map, k)
}
}
} else {
delete(that.Map, key)
}
}
func (that *CacheMemory) Cache(key string, data ...interface{}) *Obj {
x := RandX(1, 100000)
if x > 99950 {
that.refreshMap()
}
if that.mutex == nil {
that.mutex = &sync.RWMutex{}
}
reData := &Obj{Data: nil}
if len(data) == 0 {
that.mutex.RLock()
reData.Data = that.get(key)
that.mutex.RUnlock()
return reData
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
that.mutex.Lock()
that.delete(key)
that.mutex.Unlock()
return reData
}
if len(data) == 1 {
tim = tim + that.TimeOut
}
if len(data) == 2 {
that.Error.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if that.Error.GetError() == nil {
tim = tim + tempt
}
}
that.mutex.Lock()
that.set(key, data[0], tim)
that.mutex.Unlock()
return reData
}
+71 -54
View File
@@ -1,67 +1,84 @@
package cache
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"github.com/garyburd/redigo/redis"
"strings"
"time"
)
type CacheRedis struct {
Host string
Pwd string
Time int64
conn redis.Conn
tag int64
Error
TimeOut int64
DbSet bool
SessionSet bool
Host string
Pwd string
Port int64
conn redis.Conn
tag int64
ContextBase
*Error
}
func (that *CacheRedis) GetError() *Error {
return that.Error
}
func (that *CacheRedis) SetError(err *Error) {
that.Error = err
}
//唯一标志
func (this *CacheRedis) GetTag() int64 {
func (that *CacheRedis) GetTag() int64 {
if this.tag == int64(0) {
this.tag = time.Now().UnixNano()
if that.tag == int64(0) {
that.tag = time.Now().UnixNano()
}
return this.tag
return that.tag
}
func (this *CacheRedis) reCon() bool {
func (that *CacheRedis) reCon() bool {
var err error
this.conn, err = redis.Dial("tcp", this.Host)
that.conn, err = redis.Dial("tcp", that.Host+":"+ObjToStr(that.Port))
if err != nil {
this.conn = nil
this.Error.SetError(err)
that.conn = nil
that.Error.SetError(err)
return false
}
_, err = this.conn.Do("AUTH", this.Pwd)
if err != nil {
this.conn = nil
this.Error.SetError(err)
return false
if that.Pwd != "" {
_, err = that.conn.Do("AUTH", that.Pwd)
if err != nil {
that.conn = nil
that.Error.SetError(err)
return false
}
}
return true
}
func (this *CacheRedis) del(key string) {
func (that *CacheRedis) del(key string) {
del := strings.Index(key, "*")
if del != -1 {
val, err := redis.Strings(this.conn.Do("KEYS", key))
val, err := redis.Strings(that.conn.Do("KEYS", key))
if err != nil {
return
}
this.conn.Send("MULTI")
that.conn.Send("MULTI")
for i, _ := range val {
this.conn.Send("DEL", val[i])
that.conn.Send("DEL", val[i])
}
this.conn.Do("EXEC")
that.conn.Do("EXEC")
} else {
_, err := this.conn.Do("DEL", key)
_, err := that.conn.Do("DEL", key)
if err != nil {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
_, err = this.conn.Do("DEL", key)
if that.reCon() {
_, err = that.conn.Do("DEL", key)
}
}
}
@@ -69,32 +86,32 @@ func (this *CacheRedis) del(key string) {
}
//key value ,时间为时间戳
func (this *CacheRedis) set(key string, value string, time int64) {
_, err := this.conn.Do("SET", key, value, "EX", ObjToStr(time))
func (that *CacheRedis) set(key string, value string, time int64) {
_, err := that.conn.Do("SET", key, value, "EX", ObjToStr(time))
if err != nil {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
_, err = this.conn.Do("SET", key, value, "EX", ObjToStr(time))
if that.reCon() {
_, err = that.conn.Do("SET", key, value, "EX", ObjToStr(time))
}
}
}
}
func (this *CacheRedis) get(key string) *Obj {
func (that *CacheRedis) get(key string) *Obj {
reData := &Obj{}
var err error
reData.Data, err = redis.String(this.conn.Do("GET", key))
reData.Data, err = redis.String(that.conn.Do("GET", key))
if err != nil {
reData.Data = nil
if !strings.Contains(err.Error(), "nil returned") {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
reData.Data, err = redis.String(this.conn.Do("GET", key))
if that.reCon() {
reData.Data, err = redis.String(that.conn.Do("GET", key))
}
}
@@ -104,10 +121,10 @@ func (this *CacheRedis) get(key string) *Obj {
return reData
}
func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
func (that *CacheRedis) Cache(key string, data ...interface{}) *Obj {
reData := &Obj{}
if this.conn == nil {
re := this.reCon()
if that.conn == nil {
re := that.reCon()
if !re {
return reData
}
@@ -115,38 +132,38 @@ func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
//查询缓存
if len(data) == 0 {
reData = this.get(key)
reData = that.get(key)
return reData
}
tim := int64(0)
//删除缓存
if len(data) == 1 && data[0] == nil {
this.del(key)
that.del(key)
return reData
}
//添加缓存
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheShortTime")
if that.TimeOut == 0 {
//that.Time = Config.GetInt64("cacheShortTime")
}
tim += this.Time
tim += that.TimeOut
}
if len(data) == 2 {
this.Error.SetError(nil)
tempt := ObjToInt64(data[1], &this.Error)
that.Error.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if this.GetError() == nil {
} else if that.GetError() == nil {
tim = tim + tempt
}
}
this.set(key, ObjToStr(data[0]), tim)
that.set(key, ObjToStr(data[0]), tim)
return reData
+20
View File
@@ -0,0 +1,20 @@
package cache
import (
. "code.hoteas.com/golang/hotime/common"
)
type CacheIns interface {
//set(key string, value interface{}, time int64)
//get(key string) interface{}
//delete(key string)
GetError() *Error
SetError(err *Error)
Cache(key string, data ...interface{}) *Obj
}
//单条缓存数据
type cacheData struct {
time int64
data interface{}
}
-146
View File
@@ -1,146 +0,0 @@
package hotime
import (
"encoding/json"
"strings"
"time"
)
type CacheDb struct {
Time int64
Db *HoTimeDB
contextBase
isInit bool
}
func (this *CacheDb) initDbTable() {
if this.isInit {
return
}
if this.Db.Type == "mysql" {
dbNames := this.Db.Query("SELECT DATABASE()")
if len(dbNames) == 0 {
return
}
dbName := dbNames[0].GetString("DATABASE()")
res := this.Db.Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbName + "' AND TABLE_NAME='cached'")
if len(res) != 0 {
this.isInit = true
return
}
_, e := this.Db.Exec("CREATE TABLE `cached` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `ckey` varchar(60) DEFAULT NULL, `cvalue` varchar(2000) DEFAULT NULL, `time` bigint(20) DEFAULT NULL, `endtime` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=198740 DEFAULT CHARSET=utf8")
if e.GetError() == nil {
this.isInit = true
}
}
if this.Db.Type == "sqlite" {
res := this.Db.Query(`select * from sqlite_master where type = 'table' and name = 'cached'`)
if len(res) != 0 {
this.isInit = true
return
}
_, e := this.Db.Exec(`CREATE TABLE "cached" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"ckey" TEXT(60),
"cvalue" TEXT(2000),
"time" integer,
"endtime" integer
);`)
if e.GetError() == nil {
this.isInit = true
}
}
}
//获取Cache键只能为string类型
func (this *CacheDb) get(key string) interface{} {
cached := this.Db.Get("cached", "*", Map{"ckey": key})
if cached == nil {
return nil
}
//data:=cacheMap[key];
if cached.GetInt64("endtime") <= time.Now().Unix() {
this.Db.Delete("cached", Map{"id": cached.GetString("id")})
return nil
}
data := Map{}
data.JsonToMap(cached.GetString("cvalue"))
return data.Get("data")
}
//key value ,时间为时间戳
func (this *CacheDb) set(key string, value interface{}, tim int64) {
bte, _ := json.Marshal(Map{"data": value})
num := this.Db.Update("cached", Map{"cvalue": string(bte), "time": time.Now().UnixNano(), "endtime": tim}, Map{"ckey": key})
if num == int64(0) {
this.Db.Insert("cached", Map{"cvalue": string(bte), "time": time.Now().UnixNano(), "endtime": tim, "ckey": key})
}
//随机执行删除命令
if Rand(1000) > 950 {
this.Db.Delete("cached", Map{"endtime[<]": time.Now().Unix()})
}
}
func (this *CacheDb) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
this.Db.Delete("cached", Map{"ckey": key + "%"})
} else {
this.Db.Delete("cached", Map{"ckey": key})
}
}
func (this *CacheDb) Cache(key string, data ...interface{}) *Obj {
this.initDbTable()
if len(data) == 0 {
return &Obj{Data: this.get(key)}
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
this.delete(key)
return &Obj{Data: nil}
}
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheLongTime")
}
tim += this.Time
}
if len(data) == 2 {
this.SetError(nil)
tempt := ObjToInt64(data[1], &this.Error)
if tempt > tim {
tim = tempt
} else if this.GetError() == nil {
tim = tim + tempt
}
}
this.set(key, data[0], tim)
return &Obj{Data: nil}
}
-146
View File
@@ -1,146 +0,0 @@
package hotime
import (
"strings"
"sync"
"time"
)
type CacheMemory struct {
Time int64
Map
contextBase
mutex *sync.RWMutex
}
//获取Cache键只能为string类型
func (this *CacheMemory) get(key string) interface{} {
this.Error.SetError(nil)
if this.Map == nil {
this.Map = Map{}
}
if this.Map[key] == nil {
return nil
}
data := this.Map.Get(key, &this.Error).(cacheData)
if this.GetError() != nil {
return nil
}
if data.time < time.Now().Unix() {
delete(this.Map, key)
return nil
}
return data.data
}
func (this *CacheMemory) refreshMap() {
go func() {
this.mutex.Lock()
defer this.mutex.Unlock()
for key, v := range this.Map {
data := v.(cacheData)
if data.time <= time.Now().Unix() {
delete(this.Map, key)
}
}
}()
}
//key value ,时间为时间戳
func (this *CacheMemory) set(key string, value interface{}, time int64) {
this.Error.SetError(nil)
var data cacheData
if this.Map == nil {
this.Map = Map{}
}
dd := this.Map[key]
if dd == nil {
data = cacheData{}
} else {
data = dd.(cacheData)
}
data.time = time
data.data = value
this.Map.Put(key, data)
}
func (this *CacheMemory) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
for k, _ := range this.Map {
if strings.Index(k, key) != -1 {
delete(this.Map, key)
}
}
} else {
delete(this.Map, key)
}
}
func (this *CacheMemory) Cache(key string, data ...interface{}) *Obj {
x := RandX(1, 100000)
if x > 99950 {
this.refreshMap()
}
if this.mutex == nil {
this.mutex = &sync.RWMutex{}
}
reData := &Obj{Data: nil}
if len(data) == 0 {
this.mutex.RLock()
reData.Data = this.get(key)
this.mutex.RUnlock()
return reData
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
this.mutex.Lock()
this.delete(key)
this.mutex.Unlock()
return reData
}
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheShortTime")
}
tim = tim + this.Time
}
if len(data) == 2 {
this.Error.SetError(nil)
tempt := ObjToInt64(data[1], &this.Error)
if tempt > tim {
tim = tempt
} else if this.GetError() == nil {
tim = tim + tempt
}
}
this.mutex.Lock()
this.set(key, data[0], tim)
this.mutex.Unlock()
return reData
}
+301
View File
@@ -0,0 +1,301 @@
package hotime
import (
. "code.hoteas.com/golang/hotime/common"
"strings"
)
// Project 管理端项目
var TptProject = Proj{
//"user": UserCtr,
"hotimeCommon": Ctr{
"info": func(that *Context) {
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
str, inData := that.MakeCodeRouter[hotimeName].Info(that.RouterString[1], data, that.Db)
where := Map{"id": that.RouterString[2]}
if len(inData) == 1 {
inData["id"] = where["id"]
where = Map{"AND": inData}
} else if len(inData) > 1 {
where["OR"] = inData
where = Map{"AND": where}
}
re := that.Db.Get(that.RouterString[1], str, where)
if re == nil {
that.Display(4, "找不到对应信息")
return
}
for k, v := range re {
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
continue
}
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
seStr := "id," + column.GetString("value")
if that.MakeCodeRouter[hotimeName].TableColumns[column.GetString("link")]["phone"] != nil {
seStr = seStr + ",phone"
}
link := strings.Replace(column.GetString("name"), "_id", "", -1)
if link == "parent" {
link = that.RouterString[1]
}
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
}
}
//如果有table字段则代为link
if re["table"] != nil && re["table_id"] != nil {
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][re.GetString("table")]
v := re.GetCeilInt64("table_id")
seStr := "id," + column.GetString("value")
if that.MakeCodeRouter[hotimeName].TableColumns[column.GetString("link")]["phone"] != nil {
seStr = seStr + ",phone"
}
link := strings.Replace(column.GetString("name"), "_id", "", -1)
if link == "parent" {
link = that.RouterString[1]
}
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
}
that.Display(0, re)
},
"add": func(that *Context) {
that.Log = Map{"table": that.RouterString[1], "type": 1}
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
inData := that.MakeCodeRouter[hotimeName].Add(that.RouterString[1], data, that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
}
re := that.Db.Insert(that.RouterString[1], inData)
if re == 0 {
that.Display(4, "无法插入对应数据")
return
}
//索引管理,便于检索以及权限
if inData.Get("parent_id") != nil && inData.GetString("index") != "" {
index := that.Db.Get(that.RouterString[1], "`index`", Map{"id": inData.Get("parent_id")})
inData["index"] = index.GetString("index") + ObjToStr(re) + ","
that.Db.Update(that.RouterString[1], Map{"index": inData["index"]}, Map{"id": re})
} else if inData.GetString("index") != "" {
inData["index"] = "," + ObjToStr(re) + ","
that.Db.Update(that.RouterString[1], Map{"index": inData["index"]}, Map{"id": re})
}
that.Log["table_id"] = re
that.Display(0, re)
},
"update": func(that *Context) {
that.Log = Map{"table": that.RouterString[1], "type": 2, "table_id": that.RouterString[2]}
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Edit(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "没有找到要更新的数据")
return
}
//索引管理,便于检索以及权限
if inData.GetString("index") != "" {
if inData.Get("parent_id") != nil {
Index := that.Db.Get(that.RouterString[1], "`index`", Map{"id": that.RouterString[2]})
parentIndex := that.Db.Get(that.RouterString[1], "`index`", Map{"id": inData.Get("parent_id")})
inData["index"] = parentIndex.GetString("index") + that.RouterString[2] + ","
childNodes := that.Db.Select(that.RouterString[1], "id,`index``", Map{"index[~]": "," + that.RouterString[2] + ","})
for _, v := range childNodes {
v["index"] = strings.Replace(v.GetString("index"), Index.GetString("index"), inData.GetString("index"), -1)
that.Db.Update(that.RouterString[1], Map{"index": v["index"]}, Map{"id": v.GetCeilInt("id")})
}
} else {
delete(inData, "index")
}
}
re := that.Db.Update(that.RouterString[1], inData, Map{"id": that.RouterString[2]})
if re == 0 {
that.Display(4, "更新数据失败")
return
}
that.Display(0, re)
},
"remove": func(that *Context) {
that.Log = Map{"table": that.RouterString[1], "type": 3, "table_id": that.RouterString[2]}
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Delete(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
}
re := int64(0)
//索引管理,便于检索以及权限
if inData.Get("parent_id") != nil && inData.GetSlice("index") != nil {
re = that.Db.Delete(that.RouterString[1], Map{"index[~]": "," + that.RouterString[2] + ","})
} else {
re = that.Db.Delete(that.RouterString[1], Map{"id": that.RouterString[2]})
}
if re == 0 {
that.Display(4, "删除数据失败")
return
}
that.Display(0, "删除成功")
},
"search": func(that *Context) {
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
columnStr, leftJoin, where := that.MakeCodeRouter[hotimeName].Search(that.RouterString[1], data, that.Req, that.Db)
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
count := that.Db.Count(that.RouterString[1], leftJoin, where)
reData := that.Db.Page(page, pageSize).
PageSelect(that.RouterString[1], leftJoin, columnStr, where)
for _, v := range reData {
v.RangeSort(func(k string, v1 interface{}) (isEnd bool) {
//如果有table字段则代为link
if v["table"] != nil && v["table_id"] != nil {
id := v.GetCeilInt64("table_id")
tableName := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(v.GetString("table")).GetString("label")
v["table_table_name"] = strings.Replace(tableName, "管理", "", -1)
parentC := that.Db.Get(v.GetString("table"), "name", Map{"id": id})
v["table_table_id_name"] = ""
if parentC != nil {
v["table_table_id_name"] = parentC.GetString("name")
}
}
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
return isEnd
}
if (column["list"] == nil || column["list"] == true) && column["name"] == "parent_id" && column.GetString("link") != "" {
parentC := that.Db.Get(column.GetString("link"), column.GetString("value"), Map{"id": v.GetCeilInt(k)})
v[column.GetString("link")+"_"+column.GetString("name")+"_"+column.GetString("value")] = ""
if parentC != nil {
v[column.GetString("link")+"_"+column.GetString("name")+"_"+column.GetString("value")] = parentC.GetString(column.GetString("value"))
}
}
return isEnd
})
}
that.Display(0, Map{"count": count, "data": reData})
},
},
"hotime": Ctr{
"login": func(that *Context) {
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
name := that.Req.FormValue("name")
password := that.Req.FormValue("password")
if name == "" || password == "" {
that.Display(3, "参数不足")
return
}
user := that.Db.Get(fileConfig.GetString("table"), "*", Map{"AND": Map{"OR": Map{"name": name, "phone": name}, "password": Md5(password)}})
if user == nil {
that.Display(5, "登录失败")
return
}
that.Session(fileConfig.GetString("table")+"_id", user.GetCeilInt("id"))
that.Session(fileConfig.GetString("table")+"_name", name)
delete(user, "password")
that.Display(0, user)
},
"logout": func(that *Context) {
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
that.Session(fileConfig.GetString("table")+"_id", nil)
that.Session(fileConfig.GetString("table")+"_name", nil)
that.Display(0, "退出登录成功")
},
"info": func(that *Context) {
hotimeName := that.RouterString[0]
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
str, inData := that.MakeCodeRouter[hotimeName].Info(fileConfig.GetString("table"), data, that.Db)
where := Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()}
if len(inData) == 1 {
inData["id"] = where["id"]
where = Map{"AND": inData}
} else if len(inData) > 1 {
where["OR"] = inData
where = Map{"AND": where}
}
re := that.Db.Get(fileConfig.GetString("table"), str, where)
if re == nil {
that.Display(4, "找不到对应信息")
return
}
for k, v := range re {
column := that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")][k]
if column == nil {
continue
}
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
//是角色表则取下角色值
if column.GetString("link") == "role" {
re[column.GetString("link")] = that.Db.Get(column.GetString("link"), "id,auth,"+column.GetString("value"), Map{"id": v})
} else {
re[column.GetString("link")] = that.Db.Get(column.GetString("link"), "id,"+column.GetString("value"), Map{"id": v})
}
}
}
that.Display(0, re)
},
},
}
+108
View File
@@ -0,0 +1,108 @@
package code
import (
. "code.hoteas.com/golang/hotime/common"
)
var Config = Map{
"name": "HoTimeDashBoard",
"id": "2f92h3herh23rh2y8",
"label": "HoTime管理平台",
"menus": []Map{
{"label": "平台首页", "name": "HelloWorld", "icon": "el-icon-s-home"},
//{"label": "测试表格", "table": "table", "icon": "el-icon-suitcase"},
//{"label": "系统管理", "name": "setting", "icon": "el-icon-setting",
// "menus": []Map{
// {"label": "用户管理", "table": "user",
// "default": {
// "path": "info",
// "id": "1"
// },
// "auth": ["show","edit","info","add","delete"],
// },
// {"label": "组织管理", "table": "organization"},
// {"label": "地区管理", "table": "area"},
// {"label": "角色管理", "table": "role"},
// {"label": "日志管理", "table": "log"},
// {"label": "系统设置", "table": "system", "default": "edit"},
// },
//},
},
}
var DefaultMenuParentName = "sys"
var ColumnDataType = map[string]string{
//sqlite专有类型
"real": "number",
//mysql数据类型宽泛类型
"int": "number",
"float": "number",
"double": "number",
"decimal": "number",
"char": "text",
"text": "text",
"blob": "text",
"date": "time",
"time": "time",
"year": "time",
"geometry": "gis", //不建议使用gis类型,建议使用其他代替
}
type ColumnShow struct {
Name string
List bool
Edit bool
Info bool
Must bool
Type string //空字符串表示
Strict bool //name严格匹配必须是这个词才行
}
var ColumnNameType = []ColumnShow{
//通用
{"idcard", false, true, true, false, "", false},
{"id", true, false, true, false, "", true},
{"parent_id", true, true, true, false, "", true},
{"amount", true, true, true, false, "money", true},
{"content", false, false, false, false, "textArea", false},
{"info", false, true, true, false, "textArea", false},
//"sn"{true,true,true,""},
{"status", true, true, true, false, "select", false},
{"state", true, true, true, false, "select", false},
{"sex", true, true, true, false, "select", false},
{"delete", false, false, false, false, "", false},
{"lat", false, true, true, false, "", false},
{"lng", false, true, true, false, "", false},
{"latitude", false, true, true, false, "", false},
{"longitude", false, true, true, false, "", false},
{"index", false, false, false, false, "index", false},
{"password", false, true, false, false, "password", false},
{"pwd", false, true, false, false, "password", false},
{"version", false, false, false, false, "", false},
{"seq", false, true, true, false, "", false},
{"sort", false, true, true, false, "", false},
{"note", false, true, true, false, "", false},
{"description", false, true, true, false, "", false},
{"abstract", false, true, true, false, "", false},
{"content", false, true, true, false, "", false},
{"address", true, true, true, false, "", false},
{"full_name", false, true, true, false, "", false},
{"create_time", false, false, true, false, "time", true},
{"modify_time", true, false, true, false, "time", true},
{"image", false, true, true, false, "image", false},
{"img", false, true, true, false, "image", false},
{"icon", false, true, true, false, "image", false},
{"avatar", false, true, true, false, "image", false},
{"file", false, true, true, false, "file", false},
{"age", false, true, true, false, "", false},
{"email", false, true, true, false, "", false},
{"time", true, true, true, false, "time", false},
{"level", false, false, true, false, "", false},
{"rule", true, true, true, false, "form", false},
{"table", true, false, true, false, "table", false},
{"table_id", true, false, true, false, "table_id", false},
}
+1001
View File
File diff suppressed because it is too large Load Diff
+236
View File
@@ -0,0 +1,236 @@
package code
var InitTpt = `package {{name}}
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var ID = "{{id}}"
// Project 管理端项目
var Project = Proj{
//"user": UserCtr,
{{tablesCtr}}
"hotime":Ctr{
"login": func(that *Context) {
name := that.Req.FormValue("name")
password := that.Req.FormValue("password")
if name == "" || password == "" {
that.Display(3, "参数不足")
return
}
user := that.Db.Get("admin", "*", Map{"AND": Map{"OR":Map{"name": name,"phone":name}, "password": Md5(password)}})
if user == nil {
that.Display(5, "登录失败")
return
}
that.Session("admin_id", user.GetCeilInt("id"))
that.Session("admin_name", name)
that.Display(0, that.SessionId)
},
"logout": func(that *Context) {
that.Session("admin_id", nil)
that.Session("admin_name", nil)
that.Display(0, "退出登录成功")
},
"info": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
str, inData := that.MakeCodeRouter[hotimeName].Info("admin", data, that.Db)
where := Map{"id": that.Session("admin_id").ToCeilInt()}
if len(inData) ==1 {
inData["id"] =where["id"]
where = Map{"AND": inData}
}else if len(inData) >1 {
where["OR"]=inData
where = Map{"AND": where}
}
re := that.Db.Get("admin", str, where)
if re == nil {
that.Display(4, "找不到对应信息")
return
}
for k, v := range re {
column := that.MakeCodeRouter[hotimeName].TableColumns["admin"][k]
if column == nil {
continue
}
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
re[column.GetString("link")] = that.Db.Get(column.GetString("link"),"id," +column.GetString("value"), Map{"id": v})
}
}
that.Display(0, re)
},
},
}
`
var CtrTpt = `package {{name}}
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"strings"
)
var {{table}}Ctr = Ctr{
"info": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
str, inData := that.MakeCodeRouter[hotimeName].Info(that.RouterString[1], data, that.Db)
where := Map{"id": that.RouterString[2]}
if len(inData) ==1 {
inData["id"] =where["id"]
where = Map{"AND": inData}
}else if len(inData) >1 {
where["OR"]=inData
where = Map{"AND": where}
}
re := that.Db.Get(that.RouterString[1], str, where)
if re == nil {
that.Display(4, "找不到对应信息")
return
}
for k, v := range re {
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
continue
}
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
re[column.GetString("link")] = that.Db.Get(column.GetString("link"), "id,"+column.GetString("value"), Map{"id": v})
}
}
that.Display(0, re)
},
"add": func(that *Context) {
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Add(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
}
re := that.Db.Insert(that.RouterString[1], inData)
if re == 0 {
that.Display(4, "无法插入对应数据")
return
}
//索引管理,便于检索以及权限
if inData.Get("parent_id") != nil && inData.GetString("index") != "" {
index := that.Db.Get(that.RouterString[1], "` + "`index`" + `", Map{"id": inData.Get("parent_id")})
inData["index"] = index.GetString("index")+ObjToStr(re)+","
that.Db.Update(that.RouterString[1],Map{"index":inData["index"]},Map{"id":re})
}else if inData.GetString("index") != ""{
inData["index"] = "," + ObjToStr(re) + ","
that.Db.Update(that.RouterString[1], Map{"index": inData["index"]}, Map{"id": re})
}
that.Display(0, re)
},
"update": func(that *Context) {
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Edit(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "没有找到要更新的数据")
return
}
//索引管理,便于检索以及权限
if inData.Get("parent_id") != nil && inData.GetString("index") != "" {
Index := that.Db.Get(that.RouterString[1], "` + "`index`" + `", Map{"id": that.RouterString[2]})
parentIndex := that.Db.Get(that.RouterString[1], "` + "`index`" + `", Map{"id": inData.Get("parent_id")})
inData["index"] = parentIndex.GetString("index") + that.RouterString[2] + ","
childNodes := that.Db.Select(that.RouterString[1], "id,` + "`index`" + `", Map{"index[~]": "," + that.RouterString[2] + ","})
for _, v := range childNodes {
v["index"] = strings.Replace(v.GetString("index"), Index.GetString("index"), inData.GetString("index"), -1)
that.Db.Update(that.RouterString[1], Map{"index": v["index"]}, Map{"id": v.GetCeilInt("id")})
}
}
re := that.Db.Update(that.RouterString[1], inData, Map{"id": that.RouterString[2]})
if re == 0 {
that.Display(4, "更新数据失败")
return
}
that.Display(0, re)
},
"remove": func(that *Context) {
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Delete(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
}
re :=int64(0)
//索引管理,便于检索以及权限
if inData.Get("parent_id") != nil && inData.GetSlice("index") != nil {
re=that.Db.Delete(that.RouterString[1], Map{"index[~]": "," + that.RouterString[2] + ","})
}else {
re=that.Db.Delete(that.RouterString[1], Map{"id": that.RouterString[2]})
}
if re == 0 {
that.Display(4, "删除数据失败")
return
}
that.Display(0, "删除成功")
},
"search": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
columnStr, leftJoin, where := that.MakeCodeRouter[hotimeName].Search(that.RouterString[1], data, that.Req, that.Db)
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
count := that.Db.Count(that.RouterString[1], leftJoin, where)
reData := that.Db.Page(page, pageSize).
PageSelect(that.RouterString[1], leftJoin, columnStr, where)
for _, v := range reData {
for k, _ := range v {
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
continue
}
if column["list"] != false && column["name"] == "parent_id" && column.GetString("link") != "" {
parentC := that.Db.Get(column.GetString("link"), column.GetString("value"), Map{"id": v.GetCeilInt(k)})
v[column.GetString("link")+"_"+column.GetString("name")+"_"+column.GetString("value")] = ""
if parentC != nil {
v[column.GetString("link")+"_"+column.GetString("name")+"_"+column.GetString("value")] = parentC.GetString(column.GetString("value"))
}
}
}
}
that.Display(0, Map{"count": count, "data": reData})
},
}
`
+18
View File
@@ -0,0 +1,18 @@
package common
import (
"time"
)
type ContextBase struct {
tag string
}
//唯一标志
func (that *ContextBase) GetTag() string {
if that.tag == "" {
that.tag = ObjToStr(time.Now().Unix()) + ":" + ObjToStr(Random())
}
return that.tag
}
+27
View File
@@ -0,0 +1,27 @@
package common
import (
"github.com/sirupsen/logrus"
)
// Error 框架层处理错误
type Error struct {
Logger *logrus.Logger
error
}
func (that *Error) GetError() error {
return that.error
}
func (that *Error) SetError(err error) {
that.error = err
if that.Logger != nil && err != nil {
//that.Logger=log.GetLog("",false)
that.Logger.Warn(err)
}
return
}
+45 -90
View File
@@ -1,15 +1,10 @@
package hotime
package common
import (
"crypto/md5"
"encoding/hex"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
//安全锁
@@ -29,83 +24,7 @@ import (
// return res
//}
func LogError(logMsg interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_ERROR)
}
func LogWarn(logMsg interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_WARN)
}
func LogInfo(logMsg ...interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_INFO)
}
//func LogFmt(logMsg interface{}, loglevel ...LOG_MODE) {
//
// logFmt(logMsg, 2, loglevel...)
//}
//日志打印以及存储到文件
func logFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) {
if Config.GetInt("logLevel") == int(LOG_NIL) {
return
}
lev := LOG_INFO
if len(loglevel) != 0 {
lev = loglevel[0]
}
gofile := ""
if Config.GetInt("debug") != 0 && printLevel != 0 {
_, file, line, ok := runtime.Caller(printLevel)
if ok {
gofile = " " + file + ":" + ObjToStr(line)
}
}
logStr := ""
if lev == LOG_INFO {
logStr = "info:"
}
if printLevel == 0 {
logStr = "connect:"
}
if lev == LOG_WARN {
logStr = "warn:"
}
if lev == LOG_ERROR {
logStr = "error:"
}
logStr = fmt.Sprintln(time.Now().Format("2006/01/02 15:04:05"), logStr, logMsg, gofile)
//打印日志
fmt.Print(logStr)
//不需要存储到文件
if Config.GetString("logFile") == "" {
return
}
//存储到文件
logFilePath := time.Now().Format(Config.GetString("logFile"))
os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend)
//os.Create(logFilePath)
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return
}
f.Write([]byte(logStr))
f.Close()
}
//字符串首字符大写
// StrFirstToUpper 字符串首字符大写
func StrFirstToUpper(str string) string {
if len(str) == 0 {
return str
@@ -117,7 +36,43 @@ func StrFirstToUpper(str string) string {
return strings.ToUpper(first) + other
}
//字符串截取
// StrLd 相似度计算 ld compares two strings and returns the levenshtein distance between them.
func StrLd(s, t string, ignoreCase bool) int {
if ignoreCase {
s = strings.ToLower(s)
t = strings.ToLower(t)
}
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for j := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
}
// Substr 字符串截取
func Substr(str string, start int, length int) string {
rs := []rune(str)
rl := len(rs)
@@ -148,7 +103,7 @@ func Substr(str string, start int, length int) string {
return string(rs[start:end])
}
//获取最后出现字符串的下标
// IndexLastStr 获取最后出现字符串的下标
//return 找不到返回 -1
func IndexLastStr(str, sep string) int {
sepSlice := []rune(sep)
@@ -179,7 +134,7 @@ func IndexLastStr(str, sep string) int {
return -1
}
//md5
// Md5 md5
func Md5(req string) string {
md5Ctx := md5.New()
md5Ctx.Write([]byte(req))
@@ -187,7 +142,7 @@ func Md5(req string) string {
return hex.EncodeToString(cipherStr)
}
//随机数
// Rand 随机数
func Rand(count int) int {
res := Random()
for i := 0; i < count; i++ {
@@ -212,7 +167,7 @@ func Random() float64 {
}
//随机数范围
// RandX 随机数范围
func RandX(small int, max int) int {
res := 0
//随机对象
@@ -264,7 +219,7 @@ func RandX(small int, max int) int {
// GetDb()
//}
//复制返回数组
// DeepCopyMap 复制返回数组
func DeepCopyMap(value interface{}) interface{} {
if valueMap, ok := value.(Map); ok {
newMap := make(Map)
@@ -323,7 +278,7 @@ func DeepCopyMap(value interface{}) interface{} {
// }
//}
//浮点数四舍五入保留小数
// Round 浮点数四舍五入保留小数
func Round(f float64, n int) float64 {
pow10_n := math.Pow10(n)
return math.Trunc((f+0.5/pow10_n)*pow10_n) / pow10_n
+189
View File
@@ -0,0 +1,189 @@
package common
import (
"encoding/json"
"errors"
"reflect"
"sort"
"time"
)
//hotime的常用map
type Map map[string]interface{}
//获取string
func (that Map) GetString(key string, err ...*Error) string {
if len(err) != 0 {
err[0].SetError(nil)
}
return ObjToStr((that)[key])
}
func (that *Map) Pointer() *Map {
return that
}
//增加接口
func (that Map) Put(key string, value interface{}) {
//if that==nil{
// that=Map{}
//}
that[key] = value
}
//删除接口
func (that Map) Delete(key string) {
delete(that, key)
}
//获取Int
func (that Map) GetInt(key string, err ...*Error) int {
v := ObjToInt((that)[key], err...)
return v
}
//获取Int
func (that Map) GetInt64(key string, err ...*Error) int64 {
v := ObjToInt64((that)[key], err...)
return v
}
//获取向上取整Int64
func (that Map) GetCeilInt64(key string, err ...*Error) int64 {
v := ObjToCeilInt64((that)[key], err...)
return v
}
//获取向上取整Int
func (that Map) GetCeilInt(key string, err ...*Error) int {
v := ObjToCeilInt((that)[key], err...)
return v
}
//获取向上取整float64
func (that Map) GetCeilFloat64(key string, err ...*Error) float64 {
v := ObjToCeilFloat64((that)[key], err...)
return v
}
//获取Float64
func (that Map) GetFloat64(key string, err ...*Error) float64 {
v := ObjToFloat64((that)[key], err...)
return v
}
func (that Map) GetSlice(key string, err ...*Error) Slice {
//var v Slice
v := ObjToSlice((that)[key], err...)
return v
}
func (that Map) GetBool(key string, err ...*Error) bool {
//var v Slice
v := ObjToBool((that)[key], err...)
return v
}
func (that Map) GetTime(key string, err ...*Error) time.Time {
v := ObjToTime((that)[key], err...)
return v
}
func (that Map) RangeSort(callback func(k string, v interface{}) (isEnd bool)) {
testQu := []string{}
//testQuData:= qu[0].(Map)
for key, _ := range that {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
sort.Strings(testQu)
for _, k := range testQu {
re := callback(k, that[k])
if re {
return
}
}
}
func (that Map) GetMap(key string, err ...*Error) Map {
//var data Slice
v := ObjToMap((that)[key], err...)
return v
}
func (that Map) Get(key string, err ...*Error) interface{} {
if v, ok := (that)[key]; ok {
return v
}
e := errors.New("没有存储key及对应的数据")
if len(err) != 0 {
err[0].SetError(e)
}
return nil
}
//请传递指针过来
func (that Map) ToStruct(stct interface{}) {
data := reflect.ValueOf(stct).Elem()
for k, v := range that {
ks := StrFirstToUpper(k)
dkey := data.FieldByName(ks)
if !dkey.IsValid() {
continue
}
switch dkey.Type().String() {
case "int":
dkey.SetInt(that.GetInt64(k))
case "int64":
dkey.Set(reflect.ValueOf(that.GetInt64(k)))
case "float64":
dkey.Set(reflect.ValueOf(that.GetFloat64(k)))
case "string":
dkey.Set(reflect.ValueOf(that.GetString(k)))
case "interface{}":
dkey.Set(reflect.ValueOf(v))
}
}
}
func (that Map) ToJsonString() string {
return ObjToStr(that)
}
func (that Map) JsonToMap(jsonStr string, err ...*Error) {
e := json.Unmarshal([]byte(jsonStr), &that)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
}
+103
View File
@@ -0,0 +1,103 @@
package common
import "time"
//对象封装方便取用
type Obj struct {
Data interface{}
Error
ContextBase
}
func (that *Obj) Put(data interface{}) {
that.Data = data
}
func (that *Obj) ToInt(err ...Error) int {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToInt(that.Data, &that.Error)
}
func (that *Obj) ToTime(err ...Error) time.Time {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToTime(that.Data, &that.Error)
}
func (that *Obj) ToInt64(err ...Error) int64 {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToInt64(that.Data, &that.Error)
}
func (that *Obj) ToFloat64(err ...Error) float64 {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToFloat64(that.Data, &that.Error)
}
// ToCeilFloat64 获取向上取整float64
func (that *Obj) ToCeilFloat64(err ...*Error) float64 {
if len(err) != 0 {
that.Error = *err[0]
}
v := ObjToCeilFloat64(that.Data, err...)
return v
}
func (that *Obj) ToStr() string {
return ObjToStr(that.Data)
}
func (that *Obj) ToMap(err ...Error) Map {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToMap(that.Data, &that.Error)
}
func (that *Obj) ToSlice(err ...Error) Slice {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToSlice(that.Data, &that.Error)
}
func (that *Obj) ToMapArray(err ...Error) []Map {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToMapArray(that.Data, &that.Error)
}
func (that *Obj) ToObj() interface{} {
return that.Data
}
//获取向上取整Int64
func (that *Obj) ToCeilInt64(err ...*Error) int64 {
if len(err) != 0 {
that.Error = *err[0]
}
v := ObjToCeilInt64(that.Data, err...)
return v
}
//获取向上取整Int
func (that *Obj) ToCeilInt(err ...*Error) int {
if len(err) != 0 {
that.Error = *err[0]
}
v := ObjToCeilInt(that.Data, err...)
return v
}
+97 -2
View File
@@ -1,10 +1,11 @@
package hotime
package common
import (
"encoding/json"
"errors"
"math"
"strconv"
"time"
)
//仅限于hotime.Slice
@@ -96,6 +97,65 @@ func ObjToSlice(obj interface{}, e ...*Error) Slice {
return v
}
func ObjToTime(obj interface{}, e ...*Error) time.Time {
tInt := ObjToInt64(obj)
//字符串类型,只支持标准mysql datetime格式
if tInt == 0 {
tStr := ObjToStr(obj)
if len(tStr) > 18 {
t, e := time.Parse("2006-01-02 15:04:05", tStr)
if e == nil {
return t
}
} else if len(tStr) > 15 {
t, e := time.Parse("2006-01-02 15:04", tStr)
if e == nil {
return t
}
} else if len(tStr) > 12 {
t, e := time.Parse("2006-01-02 15", tStr)
if e == nil {
return t
}
} else if len(tStr) > 9 {
t, e := time.Parse("2006-01-02", tStr)
if e == nil {
return t
}
} else if len(tStr) > 6 {
t, e := time.Parse("2006-01", tStr)
if e == nil {
return t
}
}
}
//纳秒级别
if len(ObjToStr(tInt)) > 16 {
return time.Time{}.Add(time.Nanosecond * time.Duration(tInt))
//微秒级别
} else if len(ObjToStr(tInt)) > 13 {
return time.Time{}.Add(time.Microsecond * time.Duration(tInt))
//毫秒级别
} else if len(ObjToStr(tInt)) > 10 {
return time.Time{}.Add(time.Millisecond * time.Duration(tInt))
//秒级别
} else if len(ObjToStr(tInt)) > 9 {
return time.Time{}.Add(time.Second * time.Duration(tInt))
} else if len(ObjToStr(tInt)) > 3 {
t, e := time.Parse("2006", ObjToStr(tInt))
if e == nil {
return t
}
}
return time.Time{}
}
func ObjToFloat64(obj interface{}, e ...*Error) float64 {
var err error
v := float64(0)
@@ -135,6 +195,15 @@ func ObjToFloat64(obj interface{}, e ...*Error) float64 {
err = errors.New("没有合适的转换对象!")
}
}
if math.IsNaN(v) {
err = errors.New("float64 is NaN")
v = 0
}
if math.IsInf(v, 0) {
err = errors.New("float64 is Inf")
v = 0
}
if len(e) != 0 {
e[0].SetError(err)
}
@@ -212,6 +281,31 @@ func ObjToInt(obj interface{}, e ...*Error) int {
return int(v)
}
func ObjToBool(obj interface{}, e ...*Error) bool {
var err error
v := false
if obj == nil {
err = errors.New("没有合适的转换对象!")
} else {
switch obj.(type) {
case bool:
v = obj.(bool)
default:
toInt := ObjToInt(obj)
if toInt != 0 {
v = true
}
err = errors.New("没有合适的转换对象!")
}
}
if len(e) != 0 {
e[0].SetError(err)
}
return v
}
func ObjToStr(obj interface{}) string {
// fmt.Println(reflect.ValueOf(obj).Type().String() )
str := ""
@@ -232,7 +326,8 @@ func ObjToStr(obj interface{}) string {
case float64:
str = strconv.FormatFloat(obj.(float64), 'f', -1, 64)
default:
strbte, err := json.Marshal(obj)
strbte, err := json.MarshalIndent(obj, "", "\t")
if err == nil {
str = string(strbte)
}
+104
View File
@@ -0,0 +1,104 @@
package common
import (
"errors"
"time"
)
type Slice []interface{}
// GetString 获取string
func (that Slice) GetString(key int, err ...*Error) string {
if len(err) != 0 {
err[0].SetError(nil)
}
return ObjToStr((that)[key])
}
func (that Slice) GetTime(key int, err ...*Error) time.Time {
v := ObjToTime((that)[key], err...)
return v
}
// GetInt 获取Int
func (that Slice) GetInt(key int, err ...*Error) int {
v := ObjToInt((that)[key], err...)
return v
}
// GetInt64 获取Int
func (that Slice) GetInt64(key int, err ...*Error) int64 {
v := ObjToInt64((that)[key], err...)
return v
}
// GetCeilInt64 获取向上取整Int64
func (that Slice) GetCeilInt64(key int, err ...*Error) int64 {
v := ObjToCeilInt64((that)[key], err...)
return v
}
// GetCeilInt 获取向上取整Int
func (that Slice) GetCeilInt(key int, err ...*Error) int {
v := ObjToCeilInt((that)[key], err...)
return v
}
// GetCeilFloat64 获取向上取整float64
func (that Slice) GetCeilFloat64(key int, err ...*Error) float64 {
v := ObjToCeilFloat64((that)[key], err...)
return v
}
// GetFloat64 获取Float64
func (that Slice) GetFloat64(key int, err ...*Error) float64 {
v := ObjToFloat64((that)[key], err...)
return v
}
func (that Slice) GetSlice(key int, err ...*Error) Slice {
v := ObjToSlice((that)[key], err...)
return v
}
func (that Slice) GetBool(key int, err ...*Error) bool {
//var v Slice
v := ObjToBool((that)[key], err...)
return v
}
func (that Slice) GetMap(key int, err ...*Error) Map {
//var v Map
v := ObjToMap((that)[key], err...)
return v
}
func (that Slice) Get(key int, err ...*Error) interface{} {
if key < len(that) {
return that[key]
}
e := errors.New("没有存储key及对应的数据")
if len(err) != 0 {
err[0].SetError(e)
}
return nil
}
func (that Slice) Put(key int, value interface{}) {
that[key] = value
}
func (that Slice) ToJsonString() string {
return ObjToStr(that)
}
+1 -13
View File
@@ -1,16 +1,4 @@
package hotime
type LOG_MODE int
const (
LOG_NIL = 0
LOG_FMT = 1
//LOG_FILE = 2
LOG_INFO LOG_MODE = 0
LOG_WARN LOG_MODE = 1
LOG_ERROR LOG_MODE = 2
)
//session储存头
// HEAD_SESSION_ADD session储存头
const HEAD_SESSION_ADD = "session#"
+45 -19
View File
@@ -1,65 +1,91 @@
package hotime
import (
. "code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
. "code.hoteas.com/golang/hotime/db"
"encoding/json"
"errors"
"net/http"
"time"
)
type Context struct {
contextBase
*Application
Resp http.ResponseWriter
Req *http.Request
Application *Application
Log Map //日志有则创建
RouterString []string
Config Map
Db *HoTimeDB
RespData Map
RespFunc func()
CacheIns
SessionIns
DataSize int
HandlerStr string //复写请求url
}
//唯一标志
func (this *Context) Mtd(router [3]string) Map {
this.Application.Router[router[0]][router[1]][router[2]](this)
d := this.RespData
this.RespData = nil
// Mtd 唯一标志
func (that *Context) Mtd(router [3]string) Map {
that.Application.Router[router[0]][router[1]][router[2]](that)
d := that.RespData
that.RespData = nil
return d
}
//打印
func (this *Context) Display(statu int, data interface{}) {
func (that *Context) Display(statu int, data interface{}) {
resp := Map{"statu": statu}
resp := Map{"status": statu}
if statu != 0 {
temp := Map{}
tpe := this.Config.GetMap("error").GetString(ObjToStr(statu))
tpe := that.Config.GetMap("error").GetString(ObjToStr(statu))
if tpe == "" {
logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN)
//logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN)
}
temp["type"] = tpe
temp["msg"] = data
resp["result"] = temp
//兼容android等需要json转对象的服务
resp["error"] = temp
} else {
resp["result"] = data
}
this.RespData = resp
that.RespData = resp
//this.Data=d;
//that.Data=d;
}
func (this *Context) View() {
if this.RespData == nil {
func (that *Context) View() {
if that.RespFunc != nil {
that.RespFunc()
}
if that.RespData == nil {
return
}
d, err := json.Marshal(this.RespData)
//创建日志
if that.Log != nil {
that.Log["time"] = time.Now().Unix()
if that.Session("admin_id").Data != nil {
that.Log["admin_id"] = that.Session("admin_id").ToCeilInt()
}
if that.Session("user_id").Data != nil {
that.Log["user_id"] = that.Session("user_id").ToCeilInt()
}
that.Db.Insert("logs", that.Log)
}
d, err := json.Marshal(that.RespData)
if err != nil {
that.Display(1, err.Error())
that.View()
return
}
this.RespData = nil
this.Resp.Write(d)
that.DataSize = len(d)
that.RespData = nil
that.Resp.Write(d)
return
}
-17
View File
@@ -1,17 +0,0 @@
package hotime
import "time"
type contextBase struct {
Error
tag int64
}
//唯一标志
func (this *contextBase) GetTag() int64 {
if this.tag == int64(0) {
this.tag = time.Now().UnixNano()
}
return this.tag
}
+342 -195
View File
File diff suppressed because it is too large Load Diff
+142
View File
@@ -0,0 +1,142 @@
package aliyun
import (
. "code.hoteas.com/golang/hotime/common"
"fmt"
"io/ioutil"
"net/http"
//"fmt"
)
type company struct {
ApiCode string
Url string
}
var Company = company{}
func (that *company) Init(apiCode string) {
//"06c6a07e89dd45c88de040ee1489eef7"
that.ApiCode = apiCode
that.Url = "http://api.81api.com"
}
// GetCompanyOtherAll 获取企业基础信息
func (that *company) GetCompanyOtherAll(name string) Map {
res := Map{}
data, e := that.GetCompanyPatentsInfo(name) //获取专利信息
if e != nil {
fmt.Println(e)
} else {
res["PatentsInfo"] = data.GetMap("data")
}
data, e = that.GetCompanyOtherCopyrightsInfo(name) //获取其他专利
if e != nil {
fmt.Println(e)
} else {
res["OtherCopyrightsInfo"] = data.GetMap("data")
}
data, e = that.GetCompanyTrademarksInfo(name) //获取商标
if e != nil {
fmt.Println(e)
} else {
res["TrademarksInfo"] = data.GetMap("data")
}
data, e = that.GetCompanySoftwareCopyrightsInfo(name) //获取软著
if e != nil {
fmt.Println(e)
} else {
res["SoftwareCopyrightsInfo"] = data.GetMap("data")
}
data, e = that.GetCompanyProfileTags(name) //获取大数据标签
if e != nil {
fmt.Println(e)
} else {
res["ProfileTags"] = data.GetSlice("data")
}
return res
}
// GetCompanyBaseInfo 获取企业基础信息
func (that *company) GetCompanyList(name string) (Map, error) {
url := "/fuzzyQueryCompanyInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyBaseInfo 获取企业基础信息
func (that *company) GetCompanyBaseInfo(name string) (Map, error) {
url := "/getCompanyBaseInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyPatentsInfo 获取专利信息
func (that *company) GetCompanyPatentsInfo(name string) (Map, error) {
url := "/getCompanyPatentsInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyTrademarksInfo 获取商标信息
func (that *company) GetCompanyTrademarksInfo(name string) (Map, error) {
url := "/getCompanyTrademarksInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanySoftwareCopyrightsInfo 获取软著信息
func (that *company) GetCompanySoftwareCopyrightsInfo(name string) (Map, error) {
url := "/getCompanySoftwareCopyrightsInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyOtherCopyrightsInfo 获取其他著作信息
func (that *company) GetCompanyOtherCopyrightsInfo(name string) (Map, error) {
url := "/getCompanyOtherCopyrightsInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyProfileTags 获取大数据标签
func (that *company) GetCompanyProfileTags(name string) (Map, error) {
url := "/getCompanyProfileTags/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
func (that *company) basePost(url string, name string) (string, error) {
client := &http.Client{}
reqest, err := http.NewRequest("GET", that.Url+url+name+"/?isRaiseErrorCode=1", nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
reqest.Header.Add("Authorization", "APPCODE "+that.ApiCode)
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
res := string(body)
fmt.Println(res)
return res, err
}
+54
View File
@@ -0,0 +1,54 @@
package baidu
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type baiduMap struct {
Ak string
Url string
}
var BaiDuMap = baiduMap{}
func (that *baiduMap) Init(Ak string) {
//"ak=ZeT902EZvVgIoGVWEFK3osUm"
that.Ak = Ak
that.Url = "https://api.map.baidu.com/place/v2/suggestion?output=json" + "&ak=" + Ak
//query
}
// GetPosition 获取定位列表
func (that *baiduMap) GetPosition(name string, region string) (string, error) {
client := &http.Client{}
if region == "" {
region = "全国"
}
reqest, err := http.NewRequest("GET", that.Url+"&query="+url.PathEscape(name)+"&region="+url.PathEscape(region), nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
//fmt.Println(string(body))
return string(body), err
}
+18 -16
View File
@@ -10,31 +10,33 @@ import (
//"fmt"
)
type DDY struct {
type dingdongyun struct {
ApiKey string
YzmUrl string
TzUrl string
}
func (this *DDY) Init(apikey string) {
this.ApiKey = apikey
this.YzmUrl = "https://api.dingdongcloud.com/v2/sms/single_send"
this.TzUrl = "https://api.dingdongcloud.com/v1/sms/notice/multi_send"
var DDY = dingdongyun{}
func (that *dingdongyun) Init(apikey string) {
that.ApiKey = apikey
that.YzmUrl = "https://api.dingdongcloud.com/v2/sms/captcha/send.json"
that.TzUrl = "https://api.dingdongcloud.com/v2/sms/notice/send.json"
}
//发送短信验证码 code验证码如:123456 返回true表示发送成功flase表示发送失败
func (this *DDY) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) {
// SendYZM 发送短信验证码 code验证码如:123456 返回true表示发送成功flase表示发送失败
func (that *dingdongyun) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) {
for k, v := range data {
tpt = strings.Replace(tpt, "{"+k+"}", v, -1)
}
return this.send(this.YzmUrl, umoblie, tpt)
return that.send(that.YzmUrl, umoblie, tpt)
}
//发送通知
func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) {
// SendTz 发送通知
func (that *dingdongyun) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) {
for k, v := range data {
tpt = strings.Replace(tpt, "["+k+"]", v, -1)
tpt = strings.Replace(tpt, "{"+k+"}", v, -1)
}
umobleStr := ""
for i, v := range umoblie {
@@ -44,14 +46,14 @@ func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (b
}
umobleStr += "," + v
}
return this.send(this.TzUrl, umobleStr, tpt)
return that.send(that.TzUrl, umobleStr, tpt)
}
//发送短信
func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error) {
func (that *dingdongyun) send(mUrl string, umoblie string, content string) (bool, error) {
data_send_sms_yzm := url.Values{"apikey": {this.ApiKey}, "mobile": {umoblie}, "content": {content}}
res, err := this.httpsPostForm(mUrl, data_send_sms_yzm)
data_send_sms_yzm := url.Values{"apikey": {that.ApiKey}, "mobile": {umoblie}, "content": {content}}
res, err := that.httpsPostForm(mUrl, data_send_sms_yzm)
if err != nil && res == "" {
return false, errors.New("连接错误")
}
@@ -73,7 +75,7 @@ func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error)
}
//调用url发送短信的连接
func (this *DDY) httpsPostForm(url string, data url.Values) (string, error) {
func (that *dingdongyun) httpsPostForm(url string, data url.Values) (string, error) {
resp, err := http.PostForm(url, data)
if err != nil {
+11 -10
View File
@@ -2,37 +2,38 @@ package download
import (
"bytes"
"code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"io"
"io/ioutil"
"net/http"
"os"
)
//下载文件
func Down(url, path, name string) bool {
// Down 下载文件
func Down(url, path, name string, e ...*Error) bool {
os.MkdirAll(path, os.ModeDir)
if hotime.Substr(path, len(path)-1, len(path)) != "/" {
if Substr(path, len(path)-1, len(path)) != "/" {
path = path + "/"
}
out, err := os.Create(path + name)
e := hotime.Error{}
if err != nil {
e.SetError(err)
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}
defer resp.Body.Close()
pix, err := ioutil.ReadAll(resp.Body)
_, err = io.Copy(out, bytes.NewReader(pix))
if err != nil {
e.SetError(err)
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}
return true
+143
View File
@@ -0,0 +1,143 @@
package rsa
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"fmt"
"os"
)
func FileGet(path string) []byte {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
//读取文件的内容
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
return buf
}
// RSA_Encrypt RSA加密
// plainText 要加密的数据
// path 公钥匙文件地址
func RSA_Encrypt(plainText []byte, buf []byte) []byte {
//pem解码
block, _ := pem.Decode(buf)
//x509解码
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
//类型断言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//对明文进行加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
if err != nil {
panic(err)
}
//返回密文
return cipherText
}
// RSA_Decrypt RSA解密
// cipherText 需要解密的byte数据
// path 私钥文件路径
func RSA_Decrypt(cipherText []byte, buf []byte) []byte {
//pem解码
block, _ := pem.Decode(buf)
//X509解码
private, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
//对密文进行解密
//plainText,_:=rsa.DecryptPKCS1v15(rand.Reader,privateKey,cipherText)
v, err := rsa.DecryptPKCS1v15(rand.Reader, private.(*rsa.PrivateKey), cipherText)
//返回明文
return v
}
func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) []byte {
info := struct {
Version int
PrivateKeyAlgorithm []asn1.ObjectIdentifier
PrivateKey []byte
}{}
info.Version = 0
info.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
info.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
info.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
k, err := asn1.Marshal(info)
if err != nil {
panic(err.Error())
}
return k
}
func Demo() {
//生成密钥对,保存到文件
GenerateRSAKey(2048, "./")
//加密
data := []byte("hello world")
encrypt := RSA_Encrypt(data, FileGet("public.pem"))
fmt.Println(string(encrypt))
// 解密
decrypt := RSA_Decrypt(encrypt, FileGet("private.pem"))
fmt.Println(string(decrypt))
}
// GenerateRSAKey 生成RSA私钥和公钥,保存到文件中
// bits 证书大小
func GenerateRSAKey(bits int, path string) {
//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
//Reader是一个全局、共享的密码用强随机数生成器
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
panic(err)
}
//保存私钥
//通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
//使用pem格式对x509输出的内容进行编码
//创建文件保存私钥
privateFile, err := os.Create(path + "private.pem")
if err != nil {
panic(err)
}
defer privateFile.Close()
//构建一个pem.Block结构体对象
privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
//将数据保存到文件
pem.Encode(privateFile, &privateBlock)
//保存公钥
//获取公钥的数据
publicKey := privateKey.PublicKey
//X509对公钥编码
X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
panic(err)
}
//pem格式编码
//创建用于保存公钥的文件
publicFile, err := os.Create(path + "public.pem")
if err != nil {
panic(err)
}
defer publicFile.Close()
//创建一个pem.Block结构体对象
publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
//保存到文件
pem.Encode(publicFile, &publicBlock)
}
+119
View File
@@ -0,0 +1,119 @@
package tencent
import (
. "code.hoteas.com/golang/hotime/common"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
type company struct {
secretId string
secretKey string
}
var Company = company{}
func (that *company) Init(secretId, secretKey string) {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
//secretKey := "xxxx"
that.secretId = secretId
that.secretKey = secretKey
}
func (that *company) calcAuthorization(source string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(that.secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
that.secretId, sign)
return auth, datetime, nil
}
func (that *company) urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func (that *company) GetCompany(name string) Map {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
//secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := that.calcAuthorization(source)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["keyword"] = name
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-3jnh3ku8-1256140209.gz.apigw.tencentcs.com/release/business4/geet"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, that.urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(that.urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
fmt.Println(err)
return nil
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
fmt.Println(err)
return nil
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
return nil
}
res := string(bodyBytes)
fmt.Println(res)
return ObjToMap(res)
}
+104
View File
@@ -0,0 +1,104 @@
package tencent
import (
"fmt"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119"
)
type tencent struct {
secretId string
secretKey string
credential *common.Credential
}
var Tencent = tencent{}
func (that *tencent) Init(secretId, secretKey string) {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
//secretKey := "xxxx"
that.secretId = secretId
that.secretKey = secretKey
that.credential = common.NewCredential(
that.secretId,
that.secretKey,
)
}
func (that *tencent) OCRCOMPANY(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewBizLicenseOCRRequest()
//request.ImageUrl = common.StringPtr("https://img0.baidu.com/it/u=2041013181,3227632688&fm=26&fmt=auto")
request.ImageBase64 = common.StringPtr(base64Str)
response, err := client.BizLicenseOCR(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Println("An API error has returned: %s", err)
return ""
}
if err != nil {
fmt.Println("An API error has returned: %s", err)
return ""
}
//fmt.Printf("%s", response.ToJsonString())
return response.ToJsonString()
}
func (that *tencent) OCR(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewGeneralAccurateOCRRequest()
//request.ImageUrl = common.StringPtr("https://img0.baidu.com/it/u=2041013181,3227632688&fm=26&fmt=auto")
request.ImageBase64 = common.StringPtr(base64Str)
response, err := client.GeneralAccurateOCR(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Println("An API error has returned: %s", err)
return ""
}
if err != nil {
fmt.Println("An API error has returned: %s", err)
return ""
}
//fmt.Printf("%s", response.ToJsonString())
return response.ToJsonString()
}
func (that *tencent) Qrcode(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewQrcodeOCRRequest()
request.ImageBase64 = common.StringPtr(base64Str)
response, err := client.QrcodeOCR(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Println("An API error has returned: %s", err)
return ""
}
if err != nil {
fmt.Println("An API error has returned: %s", err)
return ""
}
//fmt.Printf("%s", response.ToJsonString())
return response.ToJsonString()
}
+5 -5
View File
@@ -1,7 +1,7 @@
package upload
import (
"code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"errors"
"io"
"mime/multipart"
@@ -15,7 +15,7 @@ type Upload struct {
Path string
}
func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) {
func (that *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) {
Request.ParseMultipartForm(32 << 20)
var filePath string
files := Request.MultipartForm.File
@@ -36,7 +36,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP
data := time.Unix(int64(t), 0).Format("2006-01")
path := ""
if strings.EqualFold(savefilepath, "") {
path = this.Path + data
path = that.Path + data
} else {
path = savefilepath + data
}
@@ -50,8 +50,8 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP
}
}
}
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + hotime.ObjToStr(hotime.Rand(6))
filePath = path + "/" + filename + this.Path
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + ObjToStr(Rand(6))
filePath = path + "/" + filename + that.Path
} else {
filePath = savePath
}
+79
View File
@@ -0,0 +1,79 @@
package wechat
import (
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/officialaccount"
h5config "github.com/silenceper/wechat/v2/officialaccount/config"
"github.com/silenceper/wechat/v2/officialaccount/js"
"github.com/silenceper/wechat/v2/officialaccount/oauth"
)
//基于此文档开发
//https://github.com/silenceper/wechat/blob/v2/doc/api/officialaccount.md
type h5Program struct {
Memory *cache.Memory
Config *h5config.Config
*officialaccount.OfficialAccount
weixin *wechat.Wechat //微信登录实例
}
var H5Program = h5Program{}
// Init 初始化
func (that *h5Program) Init(appid string, appsecret string) {
that.weixin = wechat.NewWechat()
that.Memory = cache.NewMemory()
that.Config = &h5config.Config{
AppID: appid,
AppSecret: appsecret,
//Token: "xxx",
//EncodingAESKey: "xxxx",
Cache: that.Memory,
}
that.OfficialAccount = that.weixin.GetOfficialAccount(that.Config)
}
// GetUserInfo 获取用户信息
func (that *h5Program) GetUserInfo(code string) (appid string, resToken oauth.ResAccessToken, userInfo oauth.UserInfo, err error) {
auth := that.GetOauth()
//weixin.GetOpenPlatform()
resToken, err = auth.GetUserAccessToken(code)
if err != nil {
return auth.AppID, resToken, userInfo, err
}
//getUserInfo
userInfo, err = auth.GetUserInfo(resToken.AccessToken, resToken.OpenID, "")
if err != nil {
return auth.AppID, resToken, userInfo, err
}
return auth.AppID, resToken, userInfo, err
}
// GetSignUrl js url签名
func (that *h5Program) GetSignUrl(signUrl string) (*js.Config, error) {
js := that.OfficialAccount.GetJs()
cfg1, e := js.GetConfig(signUrl)
if e != nil {
return nil, e
}
return cfg1, nil
}
// GetSignUrl js url签名
//func (that *h5Program) GetJsPay(signUrl string) (*js.Config, error) {
// //
// //js := that.OfficialAccount().GetJs()
// //
// //cfg1, e := js.GetConfig(signUrl)
// //if e != nil {
// // return nil, e
// //}
//
// return cfg1, nil
//}
+66
View File
@@ -0,0 +1,66 @@
package wechat
import (
"errors"
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/miniprogram"
"github.com/silenceper/wechat/v2/miniprogram/auth"
"github.com/silenceper/wechat/v2/miniprogram/config"
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
)
type miniProgram struct {
Memory *cache.Memory
Config *config.Config
weixin *wechat.Wechat //微信登录实例
*miniprogram.MiniProgram
}
var MiniProgram = miniProgram{}
// Init 初始化
func (that *miniProgram) Init(appid string, appsecret string) {
that.weixin = wechat.NewWechat()
that.Memory = cache.NewMemory()
that.Config = &config.Config{
AppID: appid,
AppSecret: appsecret,
//Token: "xxx",
//EncodingAESKey: "xxxx",
Cache: that.Memory,
}
that.MiniProgram = that.weixin.GetMiniProgram(that.Config)
}
func (that *miniProgram) GetBaseUserInfo(code string) (appid string, re auth.ResCode2Session, err error) {
appid = that.Config.AppID
a := that.GetAuth()
re, err = a.Code2Session(code)
if err != nil {
return appid, re, err
}
return appid, re, err
}
func (that *miniProgram) GetPhoneNumber(sessionkey, encryptedData, iv string) (appid string, re *encryptor.PlainData, err error) {
appid = that.Config.AppID
if sessionkey == "" || encryptedData == "" || iv == "" {
return appid, re, errors.New("参数不足")
}
eny := that.GetEncryptor()
re, err = eny.Decrypt(sessionkey, encryptedData, iv)
if err != nil {
return appid, re, err
}
return appid, re, err
}
+142
View File
@@ -0,0 +1,142 @@
package wechat
import (
"context"
"fmt"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/wechat/v3"
"net/http"
"time"
)
//基于此文档开发
//https://github.com/silenceper/wechat/blob/v2/doc/api/officialaccount.md
type wxpay struct {
client *wechat.ClientV3
ctx context.Context
apiV3Key string
MchId string
}
var WxPay = wxpay{}
// Init 初始化
func (that *wxpay) Init(MchId, SerialNo, APIv3Key, PrivateKey string) {
client, err := wechat.NewClientV3(MchId, SerialNo, APIv3Key, PrivateKey)
if err != nil {
//xlog.Error(err)
fmt.Println(err)
return
}
that.client = client
that.apiV3Key = APIv3Key
that.MchId = MchId
// 设置微信平台API证书和序列号(如开启自动验签,请忽略此步骤)
//client.SetPlatformCert([]byte(""), "")
that.ctx = context.Background()
// 启用自动同步返回验签,并定时更新微信平台API证书(开启自动验签时,无需单独设置微信平台API证书和序列号)
err = client.AutoVerifySign()
if err != nil {
//xlog.Error(err)
fmt.Println(err)
return
}
// 打开Debug开关,输出日志,默认是关闭的
client.DebugSwitch = gopay.DebugOn
}
// GetUserInfo 获取用户信息
func (that *wxpay) GetJsOrder(money int64, appid, openid, name, tradeNo, notifyUrl string) (jsApiParams *wechat.JSAPIPayParams, err error) {
fmt.Println("dasdas", money, appid, name, tradeNo, notifyUrl)
PrepayId, err := that.getPrepayId(money, appid, that.MchId, openid, name, tradeNo, notifyUrl)
if err != nil {
return nil, err
}
//小程序
jsapi, err := that.client.PaySignOfJSAPI(appid, PrepayId)
return jsapi, err
}
func (that *wxpay) CallbackJsOrder(req *http.Request) (*wechat.V3DecryptResult, error) {
notifyReq, err := wechat.V3ParseNotify(req)
if err != nil {
//xlog.Error(err)
return nil, err
}
// wxPublicKey 通过 client.WxPublicKey() 获取
err = notifyReq.VerifySignByPK(that.client.WxPublicKey())
if err != nil {
//xlog.Error(err)
return nil, err
}
// ========异步通知敏感信息解密========
// 普通支付通知解密
result, err := notifyReq.DecryptCipherText(that.apiV3Key)
//that.client.V3TransactionQueryOrder(that.ctx,result.BankType,result.OR)
return result, err
// 合单支付通知解密
//result, err := notifyReq.DecryptCombineCipherText(apiV3Key)
//// 退款通知解密
//result, err := notifyReq.DecryptRefundCipherText(apiV3Key)
// ========异步通知应答========
// 退款通知http应答码为200且返回状态码为SUCCESS才会当做商户接收成功,否则会重试。
// 注意:重试过多会导致微信支付端积压过多通知而堵塞,影响其他正常通知。
// 此写法是 gin 框架返回微信的写法
//c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "成功"})
//
//// 此写法是 echo 框架返回微信的写法
//return c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "成功"})
}
// GetUserInfo 获取用户信息
//func (that *wxpay) GetMiniOrder(money int64,appid,name,tradeNo,notifyUrl string) (jsApiParams *wechat.AppletParams,err error){
//
// PrepayId,err:=that.getPrepayId(money,name,tradeNo,notifyUrl)
// if err!=nil{
// return nil,err
// }
//
// //小程序
// applet, err := that.client.PaySignOfApplet(appid,PrepayId)
//
// return applet,err
//}
func (that *wxpay) getPrepayId(money int64, appid, mchid, openid, name, tradeNo, notifyUrl string) (prepayid string, err error) {
expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
// 初始化 BodyMap
bm := make(gopay.BodyMap)
bm.Set("appid", appid).
Set("mchid", mchid).
//Set("sub_mchid", "sub_mchid").
Set("description", name).
Set("out_trade_no", tradeNo).
Set("time_expire", expire).
Set("notify_url", notifyUrl).
SetBodyMap("amount", func(bm gopay.BodyMap) {
bm.Set("total", money).
Set("currency", "CNY")
}).
SetBodyMap("payer", func(bm gopay.BodyMap) {
bm.Set("openid", openid)
})
//ctx:=context.Context()
wxRsp, err := that.client.V3TransactionJsapi(that.ctx, bm)
fmt.Println("获取PrepayId", wxRsp, err)
if err != nil {
//xlog.Error(err)
return "", err
}
return wxRsp.Response.PrepayId, nil
}
-25
View File
@@ -1,25 +0,0 @@
package hotime
//框架层处理错误
type Error struct {
error
err error
}
func (this *Error) GetError() error {
return this.error
}
func (this *Error) SetError(err error, loglevel ...int) {
this.error = nil
if err == nil {
this.error = err
this.err = err
return
}
this.error = err
return
}
+118
View File
@@ -0,0 +1,118 @@
package app
import (
"bytes"
"code.hoteas.com/golang/hotime/common"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"fmt"
)
//高级加密标准(Adevanced Encryption Standard ,AES
//16,24,32位字符串的话,分别对应AES-128AES-192AES-256 加密方法
//key不能泄露
var PwdKey = []byte("mif022h3g9geAHUHY432,:da1adag389")
//PKCS7 填充模式
func pKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
//Repeat()函数的功能是把切片[]byte{byte(padding)}复制padding个,然后合并成新的字节切片返回
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
//填充的反向操作,删除填充字符串
func pKCS7UnPadding(origData []byte) ([]byte, error) {
//获取数据长度
length := len(origData)
if length == 0 {
return nil, errors.New("加密字符串错误!")
} else {
//获取填充字符串长度
unpadding := int(origData[length-1])
//截取切片,删除填充字节,并且返回明文
return origData[:(length - unpadding)], nil
}
}
//实现加密
func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
//创建加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块的大小
blockSize := block.BlockSize()
//对数据进行填充,让数据长度满足需求
origData = pKCS7Padding(origData, blockSize)
//采用AES加密方法中CBC加密模式
blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
//执行加密
blocMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//实现解密
func AesDeCrypt(cypted []byte, key []byte) (bytes []byte, err error) {
//异常处理
defer func() {
if e := recover(); e != nil {
//that.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
fmt.Println(err)
err = errors.New(common.ObjToStr(e))
}
}()
//创建加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块大小
blockSize := block.BlockSize()
//创建加密客户端实例
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(cypted))
//这个函数也可以用来解密
blockMode.CryptBlocks(origData, cypted)
//去除填充字符串
origData, err = pKCS7UnPadding(origData)
if err != nil {
return nil, err
}
return origData, err
}
//加密base64
func EnPwdCode(pwd []byte) (string, error) {
result, err := AesEcrypt(pwd, PwdKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(result), err
}
//解密
func DePwdCode(pwd string) ([]byte, error) {
//解密base64字符串
pwdByte, err := base64.StdEncoding.DecodeString(pwd)
if err != nil {
fmt.Println(err)
return nil, err
}
//执行AES解密
return AesDeCrypt(pwdByte, PwdKey)
}
//func main() {
// str := []byte("12fff我是ww.topgoer.com的站长枯藤")
// pwd, _ := EnPwdCode(str)
// bytes, _ := DePwdCode(pwd)
// fmt.Println(string(bytes))
//}
+110
View File
@@ -0,0 +1,110 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var ArticleCtr = Ctr{
"getdispatchs": func(that *Context) {
//判断类型
tp := that.Req.FormValue("type")
//判断类型
data := Map{"del_flag": 0}
if tp == "notify" {
data["notify_id[!]"] = nil
}
if tp == "policy" {
data["policy_id[!]"] = nil
}
if tp == "declare" {
data["declare_id[!]"] = nil
}
if len(data) > 1 {
data = Map{"AND": data, "GROUP": "dispatch_name"}
} else {
data["GROUP"] = "dispatch_name"
}
res := that.Db.Select("article", "dispatch_name", data)
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["release_time[>=]"] = startTime
}
if finishTime != "" {
data["release_time[<=]"] = finishTime
}
dispatchName := that.Req.FormValue("dispatch_name")
if dispatchName != "" {
data["dispatch_name"] = dispatchName
}
//判断类型
tp := that.Req.FormValue("type")
if tp == "notify" {
data["notify_id[!]"] = nil
}
if tp == "policy" {
data["policy_id[!]"] = nil
}
if tp == "declare" {
data["declare_id[!]"] = nil
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "release_time DESC"}
}
count := that.Db.Count("article", data)
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,notify_id,dispatch_name,policy_level", data)
for _, v := range res {
if v.GetCeilInt("notify_id") > 0 {
v["notify"] = that.Db.Get("notify", "tag", Map{"id": v.GetCeilInt("notify_id")})
}
if v.GetCeilInt("policy_id") > 0 {
v["policy"] = that.Db.Get("policy", "tag", Map{"id": v.GetCeilInt("policy_id")})
}
if v.GetCeilInt("declare_id") > 0 {
v["declare"] = that.Db.Get("declare", "money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt("declare_id")})
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+259
View File
@@ -0,0 +1,259 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/aliyun"
"code.hoteas.com/golang/hotime/dri/tencent"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
)
var CompanyCtr = Ctr{
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
keywords := that.Req.FormValue("keywords")
if keywords == "" {
keywords = that.Req.FormValue("company_name")
}
if keywords == "" {
keywords = that.Req.FormValue("name")
}
if len(keywords) < 2 {
that.Display(0, Slice{})
return
}
res, err := aliyun.Company.GetCompanyList(keywords)
if err != nil {
fmt.Println(err)
that.Display(0, Slice{})
return
}
if res.GetCeilInt64("status") != 200 {
fmt.Println(err)
that.Display(0, Slice{})
return
}
that.Display(0, res.GetMap("data").GetSlice("list"))
},
"search_info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
name := that.Req.FormValue("name")
if len(name) < 2 {
that.Display(3, "找不到企业")
return
}
res, err := aliyun.Company.GetCompanyBaseInfo(name)
if err != nil {
fmt.Println(err)
that.Display(4, "查询失败")
return
}
if res.GetBool("status") != true {
fmt.Println(err)
that.Display(4, "查询失败")
return
}
that.Display(0, res.GetMap("data"))
},
"info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
if user == nil {
that.Display(4, "找不到用户")
return
}
res := that.Db.Get("company", "*", Map{"id": user.GetCeilInt("company_id")})
if res == nil {
that.Display(4, "找不到企业")
return
}
//先不做限制
//if res.GetCeilInt("salesman_id")!=that.Session("salesman_id").ToCeilInt(){
// that.Display(4,"不是你的企业")
// return
//}
//res["technology_center_flag"] = ObjToSlice(res["technology_center_flag"])
//res["engineering_center_flag"] = ObjToSlice(res["engineering_center_flag"])
//res["engineering_laboratory_flag"] = ObjToSlice(res["engineering_laboratory_flag"])
//res["key_laboratory_flag"] = ObjToSlice(res["key_laboratory_flag"])
//res["industrial_design_center_flag"] = ObjToSlice(res["industrial_design_center_flag"])
//
//res["high_level_talents_flag1"] = ObjToSlice(res["high_level_talents_flag1"])
//
//res["tags"] = ObjToSlice(res["tags"])
res["technology_center_flag"] = strToArray(res.GetString("technology_center_flag"))
res["engineering_center_flag"] = strToArray(res.GetString("engineering_center_flag"))
res["engineering_laboratory_flag"] = strToArray(res.GetString("engineering_laboratory_flag"))
res["key_laboratory_flag"] = strToArray(res.GetString("key_laboratory_flag"))
res["industrial_design_center_flag"] = strToArray(res.GetString("industrial_design_center_flag"))
res["high_level_talents_flag1"] = strToArray(res.GetString("high_level_talents_flag1"))
res["tags"] = strToArray(res.GetString("tags"))
that.Display(0, res)
},
"edit": func(that *Context) {
//if that.Session("user_id").Data == nil {
// that.Display(2, "没有登录")
// return
//}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
//统一社会信用代码
social_code := that.Req.FormValue("social_code")
if social_code == "" {
that.Display(3, "请求参数异常")
return
}
//企业名称
company_name := that.Req.FormValue("company_name")
if company_name == "" {
that.Display(3, "请求参数异常")
return
}
//手机号
phone := that.Req.FormValue("phone")
if phone == "" {
that.Display(3, "请求参数异常")
return
}
//姓名
name := that.Req.FormValue("user_name")
if name == "" {
that.Display(3, "请求参数异常")
return
}
//验证码
err := auth(that, phone, company_name, name)
if err != nil {
that.Display(3, err.Error())
return
}
//营业执照路径
business_license := that.Req.FormValue("business_license")
if business_license == "" {
that.Display(3, "请求参数异常")
return
}
user_id := that.Session("user_id").Data
user := that.Db.Get("user", "*", Map{"id": user_id})
if user == nil {
that.Display(1, "没有找到该用户")
return
}
company := that.Db.Get("company", "*", Map{"AND": Map{"id": id, "user_id": user_id}})
if company == nil {
that.Display(4, "不是属于你的企业")
return
}
//认证
authentication_flag := 1
//if user.GetCeilInt("authentication_flag") == 0 {
// authentication_flag = 1
//}
//通过base64图片获取信息
that.Db.Update("user", Map{"name": name, "phone": phone, "authentication_flag": authentication_flag}, Map{"id": user_id})
that.Db.Update("company", Map{"social_code": social_code, "name": company_name, "phone": phone, "business_license": business_license, "modify_time[#]": "now()"}, Map{"id": id})
//赠送一张券
data := Map{
"user_id": user_id,
"coupon_id": 1,
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
"effective_start_time[#]": "NOW()",
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
"source_type": 2,
"status": 0,
"admin_id": user.GetCeilInt("admin_id"),
"create_time[#]": "NOW()",
}
//先判断是否领取过 source_type=2 是通过认证赠送的券
couponCount := that.Db.Count("coupon_user", Map{"AND": Map{"user_id": user_id, "source_type": 2}})
if couponCount == 0 {
that.Db.Insert("coupon_user", data)
}
that.Display(0, "认证成功")
},
//上传营业执照
"upload": func(this *Context) {
file := this.Req.FormValue("file")
if len(file) < 100 {
this.Display(3, "图片上传错误")
return
}
//fmt.Println(uimg)
btes, e := base64.StdEncoding.DecodeString(file[strings.Index(file, ",")+1:]) //成图片文件并把文件写入到buffer
//btes, e := base64.StdEncoding.DecodeString(file) //成图片文件并把文件写入到buffer
if e != nil {
this.Display(3, "无法解析图片")
return
}
//uimgPath:=time.Now().Format(this.Config.GetString("uimgPath"))
path := time.Now().Format(this.Config.GetString("wxFilePath"))
os.MkdirAll(this.Config.GetString("tpt")+"/"+path, os.ModeDir)
filePath := path + Md5(ObjToStr(time.Now().Unix())) + ".jpg"
err2 := ioutil.WriteFile(this.Config.GetString("tpt")+"/"+filePath, btes, 0666) //buffer输出到jpg文件中(不做处理,直接写到文件)
if err2 != nil {
this.Display(3, "图片保存失败")
return
}
tp := this.Req.FormValue("type")
if tp == "company" {
data := tencent.Tencent.OCRCOMPANY(file)
c := ObjToMap(data)
if c != nil {
c = c.GetMap("Response")
c["url"] = filePath
} else {
c = Map{"url": filePath}
}
this.Display(0, c)
return
}
},
}
+67
View File
@@ -0,0 +1,67 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var CouponCtr = Ctr{
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
user_id := that.Session("user_id").Data
user := that.Db.Get("user", "*", Map{"id": user_id})
if user == nil {
that.Display(1, "没有找到该用户")
return
}
//0-待使用,1-已使用,2-已过期
status := ObjToInt(that.Req.FormValue("status"))
var data = Map{
"coupon_user.user_id": user_id,
"coupon_user.state": 0,
}
if that.Req.FormValue("status") != "" {
data.Put("coupon_user.status", status)
}
specMap := Map{"AND": data}
if status == 0 {
specMap.Put("ORDER", "coupon_user.status ASC,coupon_user.effective_end_time ASC,coupon_user.create_time DESC")
}
if status == 1 {
specMap.Put("ORDER", "coupon_user.use_time DESC")
}
if status == 2 {
specMap.Put("ORDER", "coupon_user.effective_end_time DESC")
}
count := that.Db.Count("coupon_user", Map{"AND": data})
res := that.Db.Page(page, pageSize).PageSelect("coupon_user",
Map{"[>]coupon": "coupon_user.coupon_id = coupon.id"},
"coupon_user.code_no,coupon_user.effective_start_time,coupon_user.effective_end_time,coupon_user.status,"+
"coupon.coupon_amount,coupon.coupon_type,coupon.name,"+
"coupon.description",
specMap,
)
that.Display(0, Map{"total": count, "data": res})
},
}
File diff suppressed because it is too large Load Diff
+241
View File
@@ -0,0 +1,241 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var FavoriteCtr = Ctr{
//关注
"follow": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
policyId := ObjToInt(that.Req.FormValue("policy_id"))
notifyId := ObjToInt(that.Req.FormValue("notify_id"))
declareId := ObjToInt(that.Req.FormValue("declare_id"))
providerId := ObjToInt(that.Req.FormValue("provider_id"))
favorite := Map{}
data := Map{}
if providerId != 0 {
data = Map{"provider_id": providerId, "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 0
data["type"] = 1
} else if notifyId != 0 {
article := that.Db.Get("article", "id", Map{"notify_id": notifyId})
if article != nil {
data = Map{"notify_id": notifyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 0
data["type"] = 2
}
} else if policyId != 0 {
article := that.Db.Get("article", "id", Map{"policy_id": policyId})
if article != nil {
data = Map{"policy_id": policyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 0
data["type"] = 3
}
} else if declareId != 0 {
article := that.Db.Get("article", "id", Map{"declare_id": declareId})
if article != nil {
data = Map{"declare_id": declareId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 0
data["type"] = 4
}
}
if len(data) != 0 {
isFavorite := int64(0)
if favorite != nil {
isFavorite = that.Db.Update("favorite", data, Map{"id": favorite.GetCeilInt("id")})
} else {
data["create_time[#]"] = "now()"
isFavorite = that.Db.Insert("favorite", data)
}
if isFavorite != 0 {
if data.GetCeilInt("article_id") != 0 {
that.Db.Update("article", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("article_id")})
}
if data.GetCeilInt("notify_id") != 0 {
that.Db.Update("notify", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("notify_id")})
}
if data.GetCeilInt("policy_id") != 0 {
that.Db.Update("policy", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("policy_id")})
}
if data.GetCeilInt("declare_id") != 0 {
that.Db.Update("declare", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("declare_id")})
}
if data.GetCeilInt("provider_id") != 0 {
that.Db.Update("provider", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("provider_id")})
}
}
that.Display(0, "关注成功")
return
}
that.Display(4, "找不到关注对象")
return
},
//关注
"unfollow": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
policyId := ObjToInt(that.Req.FormValue("policy_id"))
notifyId := ObjToInt(that.Req.FormValue("notify_id"))
declareId := ObjToInt(that.Req.FormValue("declare_id"))
providerId := ObjToInt(that.Req.FormValue("provider_id"))
favorite := Map{}
data := Map{}
if providerId != 0 {
data = Map{"provider_id": providerId, "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 1
data["type"] = 1
} else if notifyId != 0 {
article := that.Db.Get("article", "id", Map{"notify_id": notifyId})
if article != nil {
data = Map{"notify_id": notifyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 1
data["type"] = 2
}
} else if policyId != 0 {
article := that.Db.Get("article", "id", Map{"policy_id": policyId})
if article != nil {
data = Map{"policy_id": policyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 1
data["type"] = 3
}
} else if declareId != 0 {
article := that.Db.Get("article", "id", Map{"declare_id": declareId})
if article != nil {
data = Map{"declare_id": declareId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
data["modify_time[#]"] = "now()"
data["del_flag"] = 1
data["type"] = 4
}
}
if len(data) != 0 && favorite != nil {
isFavorite := that.Db.Update("favorite", data, Map{"id": favorite.GetCeilInt("id")})
if isFavorite != 0 {
if data.GetCeilInt("article_id") != 0 {
that.Db.Update("article", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("article_id")})
}
if data.GetCeilInt("notify_id") != 0 {
that.Db.Update("notify", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("notify_id")})
}
if data.GetCeilInt("policy_id") != 0 {
that.Db.Update("policy", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("policy_id")})
}
if data.GetCeilInt("declare_id") != 0 {
that.Db.Update("declare", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("declare_id")})
}
if data.GetCeilInt("provider_id") != 0 {
that.Db.Update("provider", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("provider_id")})
}
}
that.Display(0, "取消关注成功")
return
}
that.Display(0, "没有关注")
return
},
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
tp := ObjToInt(that.Req.FormValue("type"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
if tp != 0 {
data["type"] = tp
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "modify_time DESC"}
}
count := that.Db.Count("favorite", data)
res := that.Db.Page(page, pageSize).PageSelect("favorite", "*", data)
for _, v := range res {
if v.GetCeilInt64("policy_id") != 0 {
v["policy"] = that.Db.Get("policy", "id,tag", Map{"id": v.GetCeilInt64("policy_id")})
}
if v.GetCeilInt64("declare_id") != 0 {
v["declare"] = that.Db.Get("declare", "id,money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt64("declare_id")})
}
if v.GetCeilInt64("notify_id") != 0 {
v["notify"] = that.Db.Get("notify", "id,tag", Map{"id": v.GetCeilInt64("notify_id")})
}
if v.GetCeilInt64("article_id") != 0 {
v["article"] = that.Db.Get("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status", Map{"id": v.GetCeilInt64("article_id")})
}
if v.GetCeilInt64("provider_id") != 0 {
v["provider"] = that.Db.Get("provider", "id,name,level,discount,avatar,title,description,"+
"click_num_base+click_num AS click_num,handle_num_base+handle_num AS handle_num,favorite_num_base+favorite_num AS favorite_num,modify_time", Map{"id": v.GetCeilInt64("provider_id")})
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+44
View File
@@ -0,0 +1,44 @@
package app
import (
"bytes"
"code.hoteas.com/golang/hotime/common"
"fmt"
"github.com/tealeg/xlsx"
"net/http"
"time"
)
func DataToExcel(w http.ResponseWriter, r *http.Request, titleList []string, dataList []common.Map, fileName string) {
// 生成一个新的文件
file := xlsx.NewFile()
// 添加sheet页
sheet, _ := file.AddSheet("Sheet1")
// 插入表头
titleRow := sheet.AddRow()
for _, v := range titleList {
cell := titleRow.AddCell()
cell.Value = v
cell.GetStyle().Font.Color = "00FF0000"
}
for _, v1 := range dataList {
row := sheet.AddRow()
// 插入内容
for _, v := range titleList {
cell := row.AddCell()
cell.SetValue(v1.Get(v))
}
}
//file.Save("D:\\temp\\vip_excel"+fileName)
fileName = fmt.Sprintf("%s.xlsx", fileName)
//_ = file.Save(fileName)
w.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
var buffer bytes.Buffer
_ = file.Write(&buffer)
content := bytes.NewReader(buffer.Bytes())
http.ServeContent(w, r, fileName, time.Now(), content)
}
+154
View File
@@ -0,0 +1,154 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"errors"
"strings"
"time"
"unicode/utf8"
)
// Project 管理端项目
var Project = Proj{
"article": ArticleCtr,
"company": CompanyCtr,
"declare": DeclareCtr,
"favorite": FavoriteCtr,
"lxcx": Lxcx,
"matters": MattersCtr,
"notify": NotifyCtr,
"order": OrderCtr,
"policy": PolicyCtr,
"provider": ProviderCtr,
"search_record": SearchRecordCtr,
"sms": Sms,
"tag": TagCtr,
"upan": UpanCtr,
"user": UserCtr,
"vip_order": VipOrderCtr,
"websocket": WebsocketCtr,
"wechath5": Wechath5,
"wechatmini": Wechath5,
"coupon": CouponCtr,
}
//生成随机码的6位md5
func getSn() string {
x := Rand(8)
return Substr(Md5(ObjToStr(int64(x)+time.Now().UnixNano()+int64(Rand(6)))), 0, 6)
}
//生成随机码的4位随机数
func getCode() string {
//res := ""
//for i := 0; i < 4; i++ {
res := ObjToStr(RandX(1000, 9999))
//}
return res
}
func strToArray(str string) Slice {
s := Slice{}
olds := strings.Split(str, ",")
for _, v := range olds {
if v != "" {
s = append(s, v)
}
}
return s
}
func arrayToStr(ars Slice) string {
s := ","
if ars == nil {
return s
}
for k, _ := range ars {
s = s + ars.GetString(k) + ","
}
return s
}
//认证公共方案
func auth(that *Context, phone, companyName, userName string) error {
user := that.Db.Get("user", "id,phone,salesman_id,company_id,provider_id,name", Map{"id": that.Session("user_id").ToCeilInt()})
if user == nil {
return errors.New("找不到用户")
}
company := that.Db.Get("company", "name,id", Map{"id": user.GetCeilInt("company_id")})
if company == nil {
return errors.New("找不到企业")
}
//手机号与原来的不同则进行绑定
if phone != user.GetString("phone") || companyName != company.GetString("name") || user.GetString("name") != userName {
//微信验证成功
if that.Session("wechat_phone").ToStr() == phone {
that.Db.Update("user", Map{"phone": phone}, Map{"id": user.GetCeilInt("id")})
if user.GetCeilInt("company_id") != 0 {
that.Db.Update("company", Map{"phone": phone}, Map{"id": user.GetCeilInt("company_id")})
}
user["phone"] = phone
} else if that.Req.FormValue("code") == "" || that.Session("phone").ToStr() != phone || that.Session("code").ToStr() != that.Req.FormValue("code") {
return errors.New("验证码错误")
} else {
that.Db.Update("user", Map{"phone": phone, "name": userName}, Map{"id": user.GetCeilInt("id")})
if user.GetCeilInt("company_id") != 0 {
that.Db.Update("company", Map{"phone": phone}, Map{"id": user.GetCeilInt("company_id")})
}
user["phone"] = phone
}
}
//
//company := that.Db.Get("company", "name,id", Map{"id": user.GetCeilInt("company_id")})
if company != nil {
that.Db.Update("company", Map{"name": companyName}, Map{"id": company.GetCeilInt64("id")})
if user.GetCeilInt64("salesman_id") != 0 {
that.Db.Update("user", Map{"certification_flag": 1}, Map{"id": user.GetCeilInt("id")})
}
return nil
}
company = Map{"name": companyName,
"user_id": user.GetCeilInt("id"),
}
if user.GetCeilInt("salesman_id") != 0 {
company["salesman_id"] = user.GetCeilInt("salesman_id")
}
if user.GetCeilInt("provider_id") != 0 {
company["provider_id"] = user.GetCeilInt("provider_id")
}
if user.GetString("phone") != "" {
company["phone"] = user.GetString("phone")
}
company["id"] = that.Db.Insert("company", company)
if company.GetCeilInt64("id") == 0 {
return errors.New("新建企业失败")
}
upUser := Map{"company_id": company.GetCeilInt64("id")}
if user.GetCeilInt64("salesman_id") != 0 {
upUser["certification_flag"] = 1
}
that.Db.Update("user", upUser, Map{"id": that.Session("user_id").Data})
return nil
}
// FilterEmoji 过滤 emoji 表情
func FilterEmoji(content string) string {
new_content := ""
for _, value := range content {
_, size := utf8.DecodeRuneInString(string(value))
if size <= 3 {
new_content += string(value)
}
}
return new_content
}
+29
View File
@@ -0,0 +1,29 @@
package app
import (
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/common"
"io/ioutil"
"log"
"net/http"
"net/url"
)
var Lxcx = Ctr{
"lists": func(that *Context) {
urlStr := "https://www.ruichuangshe.com/Resources/Services/sAppInterface.ashx?type=policyprojectbycompanyname&page=1&pagesize=10&code=8eb68adf79d660e57ccd69ea4bf340162e29e43ec344df62b364bd65b886da7fca9fb995ad93a5b485d66fd268f946f34cf0&CompanyName="
companyName := that.Req.FormValue("company")
companyName = url.QueryEscape(url.QueryEscape(companyName))
resp, err := http.Get(urlStr + companyName)
if err != nil {
log.Println("err")
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("err")
}
that.Display(0, common.ObjToMap(string(b)))
},
}
+168
View File
@@ -0,0 +1,168 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var MattersCtr = Ctr{
"create": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
sn := that.Req.FormValue("sn")
if sn == "" {
that.Display(3, "没有SN码")
return
}
serviceContent := that.Req.FormValue("service_content")
if serviceContent == "" {
that.Display(3, "没有服务内容")
return
}
salesman := that.Db.Get("salesman", "id,provider_id,name,nickname", Map{"AND": Map{"sn": sn, "del_flag": 0}})
if salesman == nil {
that.Display(4, "找不到服务商")
return
}
re := that.Db.Insert("matters", Map{
"user_id": that.Session("user_id").Data,
"salesman_id": salesman.GetCeilInt64("id"),
"provider_id": salesman.GetCeilInt64("provider_id"),
"type": 1,
"service_content": serviceContent,
"complete_flag": 0,
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
res := that.Db.Get("matters", "*", Map{"id": re})
if res == nil {
that.Display(4, "找不到事项")
return
}
res["salesman"] = that.Db.Get("salesman", "name,id", Map{"id": res.GetCeilInt64("salesman_id")})
res["provider"] = that.Db.Get("provider", "name,id", Map{"id": res.GetCeilInt64("provider_id")})
that.Display(0, res)
},
"info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("matters", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到事项")
return
}
res["salesman"] = that.Db.Get("salesman", "name,id", Map{"id": res.GetCeilInt64("salesman_id")})
res["provider"] = that.Db.Get("provider", "name,id", Map{"id": res.GetCeilInt64("provider_id")})
that.Display(0, res)
},
"edit": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
serviceEvaluation := ObjToInt(that.Req.FormValue("service_evaluation"))
evaluationRemark := that.Req.FormValue("evaluation_remark")
if serviceEvaluation == 0 {
that.Display(3, "请求参数异常")
return
}
matters := that.Db.Get("matters", "*", Map{"AND": Map{"id": id, "user_id": that.Session("user_id").Data}})
if matters == nil {
that.Display(4, "不是属于你的评价")
return
}
if matters.GetCeilInt("complete_flag") == 1 {
that.Display(4, "已完成评价,不可重复评价")
return
}
that.Db.Update("matters", Map{"service_evaluation": serviceEvaluation, "evaluation_remark": evaluationRemark, "complete_flag": 1, "modify_time[#]": "now()"}, Map{"id": id})
that.Display(0, "评价成功")
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
tp := that.Req.FormValue("type")
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
if tp != "" {
data["type"] = ObjToInt(tp)
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "modify_time DESC"}
}
count := that.Db.Count("matters", data)
res := that.Db.Page(page, pageSize).PageSelect("matters", "*", data)
that.Display(0, Map{"total": count, "data": res})
},
}
+111
View File
@@ -0,0 +1,111 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var NotifyCtr = Ctr{
"info": func(that *Context) {
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("notify", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到通知公告")
return
}
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
delete(res, "click_num_base")
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
delete(res, "favorite_num_base")
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
if article != nil {
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
delete(article, "click_num_base")
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
delete(article, "favorite_num_base")
}
res["article"] = article
//浏览量加1
that.Db.Update("notify", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
//浏览量加1
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
//查询是否已关注
if that.Session("user_id").Data != nil {
favorite := that.Db.Get("favorite", "user_id,notify_id", Map{"AND": Map{"notify_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
res["favorite"] = favorite
}
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "notify_id[!]": nil}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["release_date[>=]"] = startTime
}
if finishTime != "" {
data["release_date[<=]"] = finishTime
}
dispatchName := that.Req.FormValue("dispatch_name")
if dispatchName != "" {
data["dispatch_name"] = dispatchName
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "release_time DESC"}
}
count := that.Db.Count("article", data)
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,notify_id,dispatch_name,policy_level", data)
for _, v := range res {
if v.GetCeilInt("notify_id") > 0 {
v["notify"] = that.Db.Get("notify", "id,tag", Map{"id": v.GetCeilInt("notify_id")})
}
//if v.GetCeilInt("policy_id")>0{
// v["policy"]=that.Db.Get("policy","tag",Map{"id":v.GetCeilInt("policy_id")})
//}
//if v.GetCeilInt("declare_id")>0{
// v["declare"]=that.Db.Get("declare","money_scope_min,money_scope_max,tag,status",Map{"id":v.GetCeilInt("declare_id")})
//}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+208
View File
@@ -0,0 +1,208 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var OrderCtr = Ctr{
//创建订单
"create": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
providerId := ObjToInt(that.Req.FormValue("provider_id"))
phone := that.Req.FormValue("phone")
companyName := that.Req.FormValue("company_name")
userName := that.Req.FormValue("user_name")
if providerId == 0 || len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
that.Display(3, "请求参数异常")
return
}
err := auth(that, phone, companyName, userName)
if err != nil {
that.Display(3, err.Error())
return
}
declareId := ObjToInt(that.Req.FormValue("declare_id"))
tp := that.Req.FormValue("type")
//新建流程
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
if user == nil {
that.Display(4, "找不到用户")
return
}
company := that.Db.Get("company", "name", Map{"id": user.GetCeilInt("company_id")})
if company == nil {
that.Display(4, "找不到企业")
return
}
provider := that.Db.Get("provider", "*", Map{"id": providerId})
if provider == nil {
that.Display(4, "找不到该服务商")
return
}
//是否以前已经创建了该服务商的订单,如果创建了则直接跳转到订单详情中去
oldOrder := that.Db.Get("order", "id", Map{"AND": Map{"provider_id": providerId, "user_id": that.Session("user_id").Data, "del_flag": 0, "status": 0}})
if oldOrder != nil {
orderRecord := Map{
"order_id": oldOrder.GetCeilInt64("id"),
"user_id": user.GetCeilInt64("id"),
"remarks": user.GetString("nickname") + "向“" + provider.GetString("name") + "”服务商再次发起了订单请求",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
}
orderRecord["id"] = that.Db.Insert("order_record", orderRecord)
that.Db.Update("order", Map{"order_record_id": orderRecord.GetCeilInt64("id"), "modify_time[#]": "now()"}, Map{"id": oldOrder.GetCeilInt64("id")})
that.Display(0, oldOrder.GetCeilInt64("id"))
return
}
data := Map{
"name": "购买“" + provider.GetString("title") + "”服务",
"sn": "SN" + time.Now().Format("20060102150405") + getSn(),
"user_id": user.GetCeilInt64("id"),
"salesman_id": provider.GetCeilInt64("salesman_id"),
"provider_id": provider.GetCeilInt64("id"),
"company_id": company.GetCeilInt64("id"),
"company_name": company.GetString("name"),
"phone": user.GetString("phone"),
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
}
if declareId != 0 {
data["policy_declare_flag"] = 1
data["declare_id"] = declareId
}
if tp == "policy_declare_flag" {
data["policy_declare_flag"] = 1
}
data["id"] = that.Db.Insert("order", data)
if data.GetCeilInt64("id") == 0 {
that.Display(4, "无法生成订单!")
return
}
orderRecord := Map{
"order_id": data["id"],
"user_id": user.GetCeilInt64("id"),
"remarks": user.GetString("nickname") + "向“" + provider.GetString("name") + "”服务商发起了订单请求",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
}
orderRecord["id"] = that.Db.Insert("order_record", orderRecord)
if orderRecord.GetCeilInt64("id") == 0 {
that.Display(4, "无法生成订单记录!")
return
}
that.Db.Update("order", Map{"order_record_id": orderRecord.GetCeilInt64("id")}, Map{"id": data.GetCeilInt64("id")})
that.Display(0, data.GetCeilInt64("id"))
},
"info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "user_id": that.Session("user_id").Data}})
if res == nil {
that.Display(4, "找不到对应订单")
return
}
if res.GetCeilInt("provider_id") > 0 {
res["provider"] = that.Db.Get("provider", "name,title,phone", Map{"id": res.GetCeilInt("provider_id")})
}
res["order_record"] = that.Db.Select("order_record", "remarks,modify_time", Map{"order_id": res.GetCeilInt("id"), "ORDER": "modify_time DESC"})
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"sn[~]": keywords, "company_name[~]": keywords, "name[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "modify_time DESC"}
}
count := that.Db.Count("order", data)
res := that.Db.Page(page, pageSize).PageSelect("order", "*", data)
for _, v := range res {
//if v.GetCeilInt("policy_id")>0{
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
//}
if v.GetCeilInt("provider_id") > 0 {
v["provider"] = that.Db.Get("provider", "name,title", Map{"id": v.GetCeilInt("provider_id")})
}
if v.GetCeilInt("order_record_id") > 0 {
v["order_record"] = that.Db.Get("order_record", "remarks,modify_time", Map{"id": v.GetCeilInt("order_record_id")})
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+112
View File
@@ -0,0 +1,112 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var PolicyCtr = Ctr{
"info": func(that *Context) {
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("policy", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到通知公告")
return
}
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
delete(res, "click_num_base")
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
delete(res, "favorite_num_base")
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
if article != nil {
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
delete(article, "click_num_base")
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
delete(article, "favorite_num_base")
}
res["article"] = article
//浏览量加1
that.Db.Update("policy", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
//浏览量加1
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
//查询是否已关注
if that.Session("user_id").Data != nil {
favorite := that.Db.Get("favorite", "user_id,policy_id", Map{"AND": Map{"policy_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
res["favorite"] = favorite
}
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "policy_id[!]": nil}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["release_date[>=]"] = startTime
}
if finishTime != "" {
data["release_date[<=]"] = finishTime
}
dispatchName := that.Req.FormValue("dispatch_name")
if dispatchName != "" {
data["dispatch_name"] = dispatchName
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "release_time DESC"}
}
count := that.Db.Count("article", data)
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,policy_id,dispatch_name,policy_level", data)
for _, v := range res {
//if v.GetCeilInt("policy_id")>0{
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
//}
if v.GetCeilInt("policy_id") > 0 {
v["policy"] = that.Db.Get("policy", "tag", Map{"id": v.GetCeilInt("policy_id")})
}
//if v.GetCeilInt("declare_id")>0{
// v["declare"]=that.Db.Get("declare","money_scope_min,money_scope_max,tag,status",Map{"id":v.GetCeilInt("declare_id")})
//}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+92
View File
@@ -0,0 +1,92 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var ProviderCtr = Ctr{
//用户微信公众号或者小程序登录
"info": func(that *Context) {
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("provider", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到服务商")
return
}
//浏览量加1
that.Db.Update("provider", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
//查询是否已关注
if that.Session("user_id").Data != nil {
favorite := that.Db.Get("favorite", "user_id,provider_id", Map{"AND": Map{"provider_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
res["favorite"] = favorite
}
that.Display(0, res)
},
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "state": 0}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"name[~]": keywords, "title[~]": keywords}
}
tp := that.Req.FormValue("type")
if tp != "" {
data[tp] = 1
}
policyDeclareFlag := that.Req.FormValue("policy_declare_flag")
if policyDeclareFlag != "" {
data["policy_declare_flag"] = ObjToInt(policyDeclareFlag)
}
intellectualPropertyFlag := that.Req.FormValue("intellectual_property_flag")
if intellectualPropertyFlag != "" {
data["intellectual_property_flag"] = ObjToInt(intellectualPropertyFlag)
}
taxOnsultingFlag := that.Req.FormValue("tax_onsulting_flag")
if taxOnsultingFlag != "" {
data["tax_onsulting_flag"] = ObjToInt(taxOnsultingFlag)
}
lawFlag := that.Req.FormValue("law_flag")
if lawFlag != "" {
data["law_flag"] = ObjToInt(lawFlag)
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "id DESC"}
}
count := that.Db.Count("provider", data)
res := that.Db.Page(page, pageSize).PageSelect("provider", "id,name,level,discount,avatar,title,description,"+
"click_num_base+click_num AS click_num,handle_num_base+handle_num AS handle_num,favorite_num_base+favorite_num AS favorite_num,modify_time,policy_declare_flag,intellectual_property_flag,tax_onsulting_flag,law_flag", data)
that.Display(0, Map{"total": count, "data": res})
},
}
+51
View File
@@ -0,0 +1,51 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var SearchRecordCtr = Ctr{
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
//if pageSize <= 0 {
pageSize = 50
//}
data := Map{"del_flag": 0}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["search_company_name[~]"] = keywords
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["create_time[>=]"] = startTime
}
if finishTime != "" {
data["create_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data}
} else {
data["ORDER"] = "create_time DESC"
}
count := that.Db.Count("search_record", data)
res := that.Db.Page(page, pageSize).PageSelect("search_record", "id,search_company_name,policy_match_count,money_scope,create_time", data)
that.Display(0, Map{"total": count, "data": res})
},
}
+30
View File
@@ -0,0 +1,30 @@
package app
import (
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/dri/ddsms"
)
var Sms = Ctr{
//只允许微信验证过的或者登录成功的发送短信
"send": func(that *Context) {
if that.Session("wechat_id").Data == nil && that.Session("user_id").Data == nil {
that.Display(2, "没有登录不可发送短信")
return
}
phone := that.Req.FormValue("phone")
if len(phone) < 11 {
that.Display(3, "手机号格式错误")
return
}
code := getCode()
that.Session("phone", phone)
that.Session("code", code)
ddsms.DDY.SendYZM(phone, that.Config.GetString("smsLogin"), map[string]string{"code": code})
that.Display(0, "发送成功")
},
}
+83
View File
@@ -0,0 +1,83 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var TagCtr = Ctr{
"create": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
name := that.Req.FormValue("name")
oldTag := that.Db.Get("tag", "id", Map{"name": name})
if oldTag != nil {
that.Display(4, "此标签已存在")
return
}
re := that.Db.Insert("tag", Map{
"user_id": that.Session("user_id").Data,
"name": name,
"remark": "用户上传",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"state": 1, //先置为异常状态,等待审核通过
"del_flag": 0,
})
if re == 0 {
that.Display(4, "添加失败")
return
}
that.Display(0, "添加成功")
return
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 40
}
data := Map{"del_flag": 0, "state": 0}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"name[~]": keywords, "remark[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data}
}
count := that.Db.Count("tag", data)
res := that.Db.Page(page, pageSize).PageSelect("tag", "id,name,remark", data)
that.Display(0, Map{"total": count, "data": res})
},
}
+91
View File
@@ -0,0 +1,91 @@
package app
import (
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/common"
"fmt"
"strings"
)
var UpanCtr = Ctr{
"login": func(that *Context) {
timestamp := that.Req.FormValue("timestamp")
sn := that.Req.FormValue("sn")
//str,_:=EnPwdCode([]byte(lus[len(lus)-1]+":"+ObjToStr(t)))//
re, e := DePwdCode(sn)
if e != nil {
that.Display(3, "数据异常")
return
}
reStr := string(re)
realSn := strings.Replace(reStr, ":"+timestamp, "", -1)
if len(realSn)+len(timestamp)+1 != len(reStr) {
that.Display(4, "数据验证失败")
return
}
fmt.Println("U盘校验", realSn)
user := that.Db.Get("user", "*", common.Map{"upankey": realSn})
if user == nil {
that.Display(5, "还没有绑定用户")
return
}
that.Session("user_id", user.GetCeilInt("id"))
that.Display(0, "登录成功")
},
"create": func(that *Context) {
timestamp := that.Req.FormValue("timestamp")
sn := that.Req.FormValue("sn")
//str,_:=EnPwdCode([]byte(lus[len(lus)-1]+":"+ObjToStr(t)))//
re, e := DePwdCode(sn)
if e != nil {
fmt.Println(e)
that.Display(3, "数据异常")
return
}
reStr := string(re)
realSn := strings.Replace(reStr, ":"+timestamp, "", -1)
if len(realSn)+len(timestamp)+1 != len(reStr) {
that.Display(4, "数据验证失败")
return
}
fmt.Println("U盘校验", realSn)
uuser := that.Db.Get("user", "id", common.Map{"upankey": realSn})
if uuser != nil {
that.Display(4, "已经绑定了其他企业")
return
}
phone := that.Req.FormValue("phone")
companyName := that.Req.FormValue("company_name")
userName := that.Req.FormValue("user_name")
if len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
that.Display(3, "请求参数异常")
return
}
//验证不成功则反馈
err := auth(that, phone, companyName, userName)
if err != nil {
fmt.Println(err)
that.Display(3, err.Error())
return
}
num := that.Db.Update("user", common.Map{"upankey": realSn}, common.Map{"id": that.Session("user_id").Data})
if num == 0 {
that.Display(4, "更新失败")
return
}
that.Display(0, "绑定成功")
},
}
+107
View File
@@ -0,0 +1,107 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var UserCtr = Ctr{
"test": func(that *Context) {
that.Session("user_id", 1)
that.Session("wechat_id", 1)
that.Display(0, 1)
},
//用户微信公众号或者小程序登录
"info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").ToCeilInt()})
if user == nil {
that.Display(2, "获取个人信息失败")
return
}
if user.GetCeilInt("company_id") == 0 {
companyId := that.Db.Insert("company", Map{
"user_id": user["id"],
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
user["company_id"] = companyId
that.Db.Update("user", Map{"company_id": companyId}, Map{"id": user.GetCeilInt("id")})
}
delete(user, "password")
company := that.Db.Get("company", "id,name,social_code,business_license", Map{"id": user.GetCeilInt("company_id")})
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
if user != nil {
user["company"] = company
user["salesman"] = salesman
user["provider"] = provider
}
that.Display(0, user)
},
"edit": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
name := that.Req.FormValue("name")
nickname := that.Req.FormValue("nickname")
sex := that.Req.FormValue("sex")
email := that.Req.FormValue("email")
avatar := that.Req.FormValue("avatar")
address := that.Req.FormValue("address")
phone := that.Req.FormValue("phone") //如果更换手机号则要有新的短信验证码
code := that.Req.FormValue("code")
data := Map{"modify_time[#]": "now()"}
if name != "" {
data["name"] = name
}
if nickname != "" {
data["nickname"] = nickname
}
if sex != "" {
data["sex"] = sex
}
if email != "" {
data["email"] = email
}
if avatar != "" {
data["avatar"] = avatar
}
if address != "" {
data["address"] = address
}
if phone != "" {
//微信验证成功
if that.Session("wechat_phone").ToStr() == phone {
data["phone"] = phone
} else if code == "" || that.Session("phone").ToStr() != phone || that.Session("code").ToStr() != code {
that.Display(3, "手机短信验证失败")
return
}
data["phone"] = phone
}
re := that.Db.Update("user", data, Map{"id": that.Session("user_id").Data})
if re == 0 {
that.Display(4, "更新失败")
return
}
that.Display(0, "修改成功")
},
}
+235
View File
@@ -0,0 +1,235 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/wechat"
"fmt"
"time"
)
var VipOrderCtr = Ctr{
//创建V订单
"create": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
phone := that.Req.FormValue("phone")
companyName := that.Req.FormValue("company_name")
userName := that.Req.FormValue("user_name")
if len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
that.Display(3, "请求参数异常")
return
}
that.Db.Delete("vip_order", Map{"AND": Map{"user_id": that.Session("user_id").Data, "status": 0}})
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
if user == nil {
that.Display(2, "找不到此用户")
return
}
wc := that.Db.Get("wechat", "openid", Map{"AND": Map{"appid": that.Config.GetString("wechatAppID"), "user_id": that.Session("user_id").Data}})
if wc == nil {
that.Display(2, "没有获取微信个人信息")
return
}
err := auth(that, phone, companyName, userName)
if err != nil {
that.Display(3, err.Error())
return
}
data := Map{
"sn": "SN" + time.Now().Format("20060102150405") + getSn(),
//"name":"1年VIP会员",
"amount": 36000, //720元
"user_id": user.GetCeilInt64("id"),
"company_id": user.GetCeilInt("company_id"),
"expiration_time": time.Now().Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05"),
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
"status": 0,
}
tp := "购买"
if user.GetString("expiration_time") != "" {
data["old_expiration_time"] = user.GetString("expiration_time")
t, e := time.Parse("2006-01-02 15:04:05", user.GetString("expiration_time"))
fmt.Println(e, "时间创建失败")
if t.Unix() >= time.Now().Unix() {
tp = "续订"
data["expiration_time"] = t.Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")
}
}
if user.GetCeilInt("provider_id") != 0 {
data["provider_id"] = user.GetCeilInt("provider_id")
data["amount"] = 36000
//tp=tp
}
//data["amount"] = 1
if user.GetCeilInt("salesman_id") != 0 {
data["salesman_id"] = user.GetCeilInt("salesman_id")
}
data["name"] = companyName + tp + "1年VIP会员"
jsParams, e := wechat.WxPay.GetJsOrder(data.GetCeilInt64("amount"), that.Config.GetString("wechatAppID"), wc.GetString("openid"), data.GetString("name"), data.GetString("sn"), that.Config.GetString("wechatAppNotifyUrl"))
if e != nil {
fmt.Println(e)
that.Display(4, e)
return
}
re := that.Db.Insert("vip_order", data)
fmt.Println(re)
that.Display(0, jsParams)
},
"callback": func(that *Context) {
data, e := wechat.WxPay.CallbackJsOrder(that.Req)
if e != nil {
fmt.Println(e)
//that.Display(4,e)
fmt.Println("返回数据错误", e)
return
}
sn := data.OutTradeNo
amount := int64(data.Amount.Total)
state := data.TradeState
//state:="SUCCESS"
//data := Map{"ces": "das"}
//sn := that.Req.FormValue("sn")
//amount := ObjToCeilInt64(that.Req.FormValue("amount"))
if state != "SUCCESS" {
fmt.Println("购买返回失败", data)
return
}
vipOrder := that.Db.Get("vip_order", "*", Map{"sn": sn})
if vipOrder == nil {
fmt.Println("找不到订单", vipOrder, data)
return
}
user := that.Db.Get("user", "*", Map{"id": vipOrder.GetCeilInt("user_id")})
if user == nil {
fmt.Println("找不到用户", vipOrder, data)
return
}
if vipOrder.GetCeilInt64("amount") != amount {
fmt.Println("金额不符", user, vipOrder, amount, data)
return
}
that.Db.Update("vip_order", Map{"status": 1}, Map{"id": vipOrder.GetCeilInt("id")})
idata := Map{"expiration_time": time.Now().Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")}
if user.GetString("expiration_time") != "" {
t, e := time.Parse("2006-01-02 15:04:05", user.GetString("expiration_time"))
fmt.Println(e, "时间创建失败")
if t.Unix() >= time.Now().Unix() {
idata["expiration_time"] = t.Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")
}
}
re := that.Db.Update("user", idata, Map{"id": user.GetCeilInt("id")})
if re == 0 {
fmt.Println("购买失败", user, vipOrder, re, data)
return
}
fmt.Println("成功购买", user, vipOrder, re, data)
//购买成功后赠送10张券
//user_id := that.Session("user_id").Data
data2 := Map{
"user_id": that.Session("user_id").Data,
"coupon_id": 1,
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
"effective_start_time[#]": "NOW()",
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
"source_type": 1,
"status": 0,
"admin_id": user.GetCeilInt("admin_id"),
"create_time[#]": "NOW()",
}
for n := 0; n < 5; n++ {
that.Db.Insert("coupon_user", data2)
}
data2["effective_end_time"] = time.Now().AddDate(1, 0, 0).Format("2006-01-02 15:04:05")
for n := 0; n < 5; n++ {
that.Db.Insert("coupon_user", data2)
}
return
},
"export": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
buy_date := ObjToStr(that.Req.FormValue("buy_date"))
if buy_date == "" {
that.Display(3, "请求参数异常")
return
}
//data := that.Db.Query("SELECT vo.sn 订单号, vo.`name` 订单名, vo.user_id 购买用户ID,usr.`name` 购买用户名, usr.phone 购买用户电话, cp.id 企业ID, cp.`name` 企业名,\nvo.expiration_time 过期时间, vo.old_expiration_time 订购前到期时间, vo.amount `订单金额_单位(分)`,\nvo.salesman_id 业务员ID,sm.`name` 业务员名, sm.phone 业务员电话, pv.`name` 服务商名 \nFROM vip_order vo\nLEFT JOIN salesman sm ON sm.id = vo.salesman_id\nLEFT JOIN provider pv ON pv.id = vo.provider_id\nLEFT JOIN `user` usr ON usr.id = vo.user_id\nLEFT JOIN company cp ON cp.id = vo.company_id\nWHERE vo.`status` = 1 AND vo.create_time >= '" + buy_date + "' \nORDER BY vo.create_time")
//data := that.Db.Query("SELECT vo.sn 订单号, vo.`name` 订单名, vo.user_id 购买用户ID,usr.`name` 购买用户名, usr.phone 购买用户电话, cp.id 企业ID, cp.`name` 企业名,\nvo.expiration_time 过期时间, vo.old_expiration_time 订购前到期时间, vo.amount `订单金额_单位(分)`,\nvo.salesman_id 业务员ID,sm.`name` 业务员名, sm.phone 业务员电话, pv.`name` 服务商名 \nFROM vip_order vo\n" +
// "LEFT JOIN salesman sm ON sm.id = vo.salesman_id\nLEFT JOIN provider pv ON pv.id = vo.provider_id\nLEFT JOIN `user` usr" +
// " ON usr.id = vo.user_id\nLEFT JOIN company cp ON cp.id = vo.company_id\nWHERE" +
// " vo.`status` = 1 AND vo.create_time >= ? \nORDER BY vo.create_time",buy_date)
data := that.Db.Select("vip_order", Map{"[>]salesman": "salesman.id=vip_order.salesman_id",
"[>]provider": "provider.id = vip_order.provider_id",
"[>]user": "user.id = vip_order.user_id",
"[>]company": "company.id = vip_order.company_id",
}, "vip_order.sn 订单号, vip_order.`name` 订单名, vip_order.user_id 购买用户ID,user.`name` 购买用户名, user.phone 购买用户电话, company.id 企业ID, company.`name` 企业名,\nvip_order.expiration_time 过期时间, vip_order.amount `订单金额_单位(分)`,\nvip_order.salesman_id 业务员ID,salesman.`name` 业务员名, salesman.phone 业务员电话, provider.`name` 服务商名",
Map{"AND": Map{"vip_order.status": 1, "vip_order.create_time[>=]": buy_date}, "ORDER": "vip_order.create_time DESC"})
if len(data) == 0 {
that.Display(0, "今日没有vip购买信息数据")
return
}
var titleList []string
if data != nil {
m := data[0]
for k, _ := range m {
titleList = append(titleList, k)
}
}
var dataList []Map
for _, v := range data {
dataList = append(dataList, v)
}
//打印最后一次sql语句
//that.Db.LastQuery
//请求的数据
//that.Db.LastData
//that.Db.LastErr
//appIns.Db.Select("company",common.Map{"[<>]user":"company.id=user.company_id"},"company.id as id",common.Map{"AND":common.Map{"id[!]":nil},"ORDER":"id DESC"})
//appIns.Db.Query("select * from user where id = ? and name = ?",common.Slice{1,"nn"})
//titleList:= []string{"aaaa", "vvvvv", "dddd", "eeeee", "gfgggg"}
DataToExcel(that.Resp, that.Req, titleList, dataList, buy_date+"vip购买信息分析数据")
},
}
+72
View File
@@ -0,0 +1,72 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"golang.org/x/net/websocket"
"time"
)
type WSClient struct {
ID string
*websocket.Conn
time.Time
DeadTime time.Time
IsDead bool
}
//websocket链接池
var WsUserMap = map[string][]*WSClient{}
var WSMasterID = ""
func WsSendMsg(ws *WSClient, data Map) bool {
if WsUserMap[ws.ID] == nil {
return false
}
for _, v := range WsUserMap[ws.ID] {
if v.IsDead || v == ws {
//WsUserMap[ws.ID]=WsUserMap[ws.ID][:k]
continue
}
str := data.ToJsonString()
v.Conn.Write([]byte(str))
}
return true
}
var WebsocketCtr = Ctr{
"conn": func(this *Context) {
id := this.SessionId
if WsUserMap[id] == nil {
WsUserMap[id] = []*WSClient{}
}
hdler := websocket.Handler(func(ws *websocket.Conn) {
client := &WSClient{ID: id, Conn: ws, Time: time.Now(), DeadTime: time.Now(), IsDead: false}
WsUserMap[id] = append(WsUserMap[id], client)
var message string
for true {
err := websocket.Message.Receive(ws, &message)
if err != nil {
client.DeadTime = time.Now()
client.IsDead = true
return
}
data := Map{}
data.JsonToMap(message)
WsSendMsg(client, data)
//switch data.GetString("type") {
//
//}
}
})
hdler.ServeHTTP(this.Resp, this.Req)
},
}
+287
View File
@@ -0,0 +1,287 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/wechat"
"time"
)
var Wechath5 = Ctr{
//微信注册,0已经完整的注册了,1还没有注册
"code": func(that *Context) {
if that.Req.FormValue("code") == "" {
that.Display(3, "参数不足")
return
}
appid, resToken, userInfo, err := wechat.H5Program.GetUserInfo(that.Req.FormValue("code"))
if err != nil {
that.Display(4, err)
return
}
//此次获取的微信信息
wechatInfo := Map{
"openid": userInfo.OpenID,
"acttoken": resToken.AccessToken,
"retoken": resToken.RefreshToken,
"appid": appid,
"unionid": userInfo.Unionid,
"nickname": FilterEmoji(userInfo.Nickname),
"avatar": userInfo.HeadImgURL,
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
"type": 1,
}
userId := 0
//这个defer放到上面,防止出现用户第一次登陆的时候出现不返回company和salesman的情况
//如果有则直接返回用户信息到微信小程序里
defer func() {
if userId != 0 {
user := that.Db.Get("user", "*", Map{"id": userId})
if user == nil {
that.Display(4, "获取个人信息失败")
return
}
delete(user, "password")
company := that.Db.Get("company", "id,name", Map{"id": user.GetCeilInt("company_id")})
//消除company没有创建的影响
if company == nil {
companyId := that.Db.Insert("company", Map{
"user_id": user["id"],
"provider_id": user["provider_id"],
"salesman_id": user["salesman_id"],
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
user["company_id"] = companyId
that.Db.Update("user", Map{"company_id": companyId}, Map{"id": user.GetCeilInt("id")})
company = that.Db.Get("company", "*", Map{"id": user.GetCeilInt("company_id")})
}
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
user["company"] = company
user["salesman"] = salesman
user["provider"] = provider
that.Display(0, user)
}
}()
defer func() {
//有sn就关联业务员
parentId := ObjToInt(that.Req.FormValue("parent_id"))
if parentId == 0 {
return
}
if userId == 0 || userId == parentId {
return
}
puser := that.Db.Get("user", "`index`,id", Map{"id": parentId})
if puser == nil {
return
}
user := that.Db.Get("user", "parent_id", Map{"id": userId})
if user.GetCeilInt("parent_id") != 0 {
return
}
index1 := puser.GetString("index")
if index1 == "," {
index1 = index1 + ObjToStr(parentId) + ","
}
//2022/5/11 zpw 添加字段:用户关联parenid的时间 join_parent_time
that.Db.Update("user", Map{"parent_id": parentId, "index": index1 + ObjToStr(userId) + ",", "join_parent_time[#]": "NOW()"}, Map{"id": userId})
//在这里做判断 能否通过分享领券
//如果通过邀请获得的券超过了三张则不再赠送
//赠送一张券
data := Map{
"user_id": parentId,
"coupon_id": 1,
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
"effective_start_time[#]": "NOW()",
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
"source_type": 3,
"status": 0,
"admin_id": user.GetCeilInt("admin_id"),
"create_time[#]": "NOW()",
}
//先判断是否领取过 source_type=3 是通过拉新赠送的券
couponCount := that.Db.Count("coupon_user", Map{"AND": Map{"user_id": parentId, "source_type": 3}})
if couponCount < 3 {
that.Db.Insert("coupon_user", data)
}
}()
//最后验证服务商是否绑定
defer func() {
//有sn就关联业务员
sn := that.Req.FormValue("sn")
if sn == "" {
return
}
if userId == 0 {
return
}
salesman := that.Db.Get("salesman", "*", Map{"sn": sn})
if salesman.GetCeilInt("id") == 0 {
return
}
user := that.Db.Get("user", "*", Map{"id": userId})
if user == nil {
return
}
//用户都有企服人员关联
if user.GetCeilInt("salesman_id") != 0 {
return
}
//用户没有企服商id
//2022/5/11 zpw 添加字段:用户关联企服商业务人员的时间 (join_salesman_time
that.Db.Update("user", Map{"salesman_id": salesman.GetCeilInt64("id"), "provider_id": salesman.GetCeilInt64("provider_id"), "join_salesman_time[#]": "NOW()"}, Map{"id": user.GetCeilInt64("id")})
if user.GetCeilInt("company_id") == 0 {
return
}
//绑定企业
that.Db.Update("company", Map{"salesman_id": salesman.GetCeilInt64("id"), "provider_id": salesman.GetCeilInt64("provider_id")}, Map{"id": user.GetCeilInt64("company_id")})
}()
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": userInfo.OpenID, "del_flag": 0}})
if wechat != nil {
//有用户直接返回
if wechat.GetCeilInt("user_id") != 0 {
that.Db.Update("user", Map{"login_time[#]": "now()"}, Map{"id": wechat.GetCeilInt("user_id")})
that.Session("wechat_id", wechat.GetCeilInt("id"))
that.Session("user_id", wechat.GetCeilInt("user_id"))
userId = wechat.GetCeilInt("user_id")
//that.Display(0, "登录成功")
return
}
//没有用户继续查询数据库看是否有其他unionid
wechat1 := that.Db.Get("wechat", "*", Map{"AND": Map{"unionid": userInfo.Unionid, "openid[!]": userInfo.OpenID, "user_id[>]": 0, "del_flag": 0}})
//其他表有该数据,则更新当前表数据信息
if wechat1 != nil {
wechatInfo["user_id"] = wechat1.GetCeilInt("user_id")
that.Db.Update("wechat", wechatInfo, Map{"id": wechat.GetCeilInt("id")})
that.Db.Update("user", Map{"login_time[#]": "now()"}, Map{"id": wechat1.GetCeilInt("user_id")})
that.Session("wechat_id", wechat.GetCeilInt("id"))
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
userId = wechatInfo.GetCeilInt("user_id")
//that.Display(0, "登录成功")
return
}
//其他表也没有当前信息,则生成user表,并更新当前用户,一般不会走到这里来
user := Map{
"nickname": wechatInfo.GetString("nickname"),
"avatar": wechatInfo.GetString("avatar"),
"index": ",",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"login_time[#]": "now()",
"del_flag": 0,
}
user["id"] = that.Db.Insert("user", user)
//创建企业
user["company_id"] = that.Db.Insert("company", Map{
"user_id": user["id"],
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
wechatInfo["user_id"] = user.GetCeilInt("id")
that.Db.Update("wechat", wechatInfo, Map{"id": wechat.GetCeilInt("id")})
that.Session("wechat_id", wechat.GetCeilInt("id"))
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
userId = wechatInfo.GetCeilInt("user_id")
//that.Display(0, "登录成功")
return
}
user := Map{
"nickname": wechatInfo.GetString("nickname"),
"avatar": wechatInfo.GetString("avatar"),
"index": ",",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"login_time[#]": "now()",
"del_flag": 0,
}
user["id"] = that.Db.Insert("user", user)
user["company_id"] = that.Db.Insert("company", Map{
"user_id": user["id"],
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
wechatInfo["user_id"] = user.GetCeilInt("id")
wechatInfo["id"] = that.Db.Insert("wechat", wechatInfo)
if wechatInfo.GetCeilInt("id") == 0 {
that.Display(4, "创建用户失败")
return
}
that.Session("wechat_id", wechatInfo.GetCeilInt("id"))
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
userId = wechatInfo.GetCeilInt("user_id")
//that.Display(0, "登录成功")
},
//网页签名
"sign": func(that *Context) {
signUrl := that.Req.FormValue("url")
if signUrl == "" {
that.Display(3, "参数不足")
return
}
cfg1, e := wechat.H5Program.GetSignUrl(signUrl)
if e != nil {
that.Display(4, e)
return
}
sign := Map{
"appId": cfg1.AppID,
"timestamp": cfg1.Timestamp,
"nonceStr": cfg1.NonceStr,
"signature": cfg1.Signature,
}
that.Display(0, sign)
},
}
+167
View File
@@ -0,0 +1,167 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/wechat"
"fmt"
)
var WechatMini = Ctr{
"getphone": func(that *Context) {
//sessionKey := that.Req.FormValue("sessionkey")
if that.Session("wechat_id").Data == nil {
that.Display(2, "请先登录")
return
}
encryptedData := that.Req.FormValue("encryptedData")
iv := that.Req.FormValue("iv")
if encryptedData == "" || iv == "" {
that.Display(3, "参数不足")
return
}
wechatIns := that.Db.Get("wechat", "sessionkey", Map{"id": that.Session("wechat_id").ToCeilInt()})
_, re, e := wechat.MiniProgram.GetPhoneNumber(wechatIns.GetString("sessionkey"), encryptedData, iv)
if e != nil {
that.Display(4, e)
return
}
//临时存储用于校验
that.Session("wechat_phone", re.PhoneNumber)
that.Display(0, re.PhoneNumber)
},
//检查是否已经有用户登录了,如果有直接登录,如果没有则查询unionid,有则直接返回用户信息,没有则返回null
"code": func(that *Context) {
code := that.Req.FormValue("code")
if code == "" {
that.Display(3, "缺少code")
return
}
appid, re, e := wechat.MiniProgram.GetBaseUserInfo(code)
fmt.Println(re)
if e != nil {
that.Display(4, e)
return
}
wchat := Map{"openid": re.OpenID,
"appid": appid,
"sessionkey": re.SessionKey,
"unionid": re.UnionID,
"modify_time[#]": "now()",
"del_flag": 0,
"type": 2,
}
userId := 0
//如果有则直接返回用户信息到微信小程序里
defer func() {
if userId != 0 {
user := that.Db.Get("user", "*", Map{"id": userId})
company := that.Db.Get("company", "id,name", Map{"id": user.GetCeilInt("company_id")})
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
if user == nil {
that.Display(4, "获取个人信息失败")
return
}
delete(user, "password")
user["company"] = company
user["salesman"] = salesman
user["provider"] = provider
that.Display(0, user)
}
}()
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": re.OpenID, "user_id[!]": nil, "del_flag": 0}})
//有该用户,则登录成功
if wechat != nil {
that.Session("wechat_id", wechat.GetCeilInt("id"))
that.Session("user_id", wechat.GetCeilInt("user_id"))
//更新用户信息
that.Db.Update("wechat", wchat, Map{"id": wechat.GetCeilInt("id")})
//that.Display(0, "登录成功")
userId = wechat.GetCeilInt("user_id")
return
}
//如果其他人有相关信息,则直接取用
wechat = that.Db.Get("wechat", "*", Map{"AND": Map{"unionid": re.UnionID, "user_id[!]": nil, "del_flag": 0}})
if wechat != nil {
wechat1 := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": re.OpenID, "del_flag": 0}})
//有该信息,但没有相关的用户信息,则直接绑定其他的信息上来
if wechat1 != nil {
//更新用户信息
that.Db.Update("wechat", wchat, Map{"id": wechat1.GetCeilInt("id")})
that.Session("wechat_id", wechat1.GetCeilInt("id"))
that.Session("user_id", wechat.GetCeilInt("user_id"))
//that.Display(0, "登录成功")
userId = wechat.GetCeilInt("user_id")
return
}
//没有相关用户信息,则新建wechat并完成登录
wchat["user_id"] = wechat["user_id"]
wchat["create_time[#]"] = "now()"
wchat["id"] = that.Db.Insert("wechat", wchat)
if wchat.GetCeilInt("id") == 0 {
that.Display(5, "创建wechat失败")
return
}
that.Session("wechat_id", wchat.GetCeilInt("id"))
that.Session("user_id", wchat.GetCeilInt("user_id"))
userId = wchat.GetCeilInt("user_id")
//that.Display(0, "登录成功")
return
}
user := Map{
"create_time[#]": "now()",
"modify_time[#]": "now()",
"login_time[#]": "now()",
"del_flag": 0,
}
user["id"] = that.Db.Insert("user", user)
user["company_id"] = that.Db.Insert("company", Map{
"user_id": user["id"],
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
wchat["user_id"] = user.GetCeilInt("id")
wchat["create_time[#]"] = "now()"
wchat["id"] = that.Db.Insert("wechat", wchat)
if wchat.GetCeilInt("id") == 0 {
that.Display(5, "登录失败")
return
}
that.Session("wechat_id", wchat.GetCeilInt("id"))
that.Session("user_id", wchat.GetCeilInt("user_id"))
userId = wchat.GetCeilInt("user_id")
//that.Display(0, nil)
},
}
+66
View File
@@ -0,0 +1,66 @@
{
"aliyunCode": "06c6a07e89dd45c88de040ee1489eef7",
"avatarPath": "avatar/2006/01/02/",
"cache": {
"db": {
"db": false,
"session": true
},
"memory": {
"db": true,
"session": true,
"timeout": 7200
}
},
"codeConfig": [
{
"config": "config/admin.json",
"mode": 0,
"name": "",
"rule": "config/adminRule.json",
"table": "admin"
}
],
"crossDomain": "",
"db": {
"mysql": {
"host": "192.168.2.50",
"name": "zct_v2_v2",
"password": "kct@2021",
"port": "3306",
"prefix": "",
"user": "root"
}
},
"defFile": [
"index.html",
"index.htm"
],
"error": {
"1": "内部系统异常",
"2": "访问权限异常",
"3": "请求参数异常",
"4": "数据处理异常",
"5": "数据结果异常",
"6": "需要进一步获取个人信息"
},
"imgPath": "img/2006/01/02/",
"mode": 2,
"port": "8081",
"sessionName": "HOTIME",
"smsKey": "b0eb4bf0198b9983cffcb85b69fdf4fa",
"smsLogin": "【政策通】您的验证码为:{code},请在5分钟内使用,切勿将验证码泄露于他人,如非本人操作请忽略。",
"tencentId": "AKIDOgT8cKCQksnY7yKATaYO7j9ORJzSYohP",
"tencentKey": "GNXgjdN4czA9ya0FNMApVJzTmsmU0KSN",
"tpt": "tpt",
"wechatAppID": "wxdcc8d6360661a179",
"wechatAppNotifyUrl": "https://zcth5.kct.cn/app/vip_order/callback",
"wechatAppSecret": "4d793683ca915264663a9c9a33530c3c",
"wechatMiniAppID": "wx1c795e883b5b54c4",
"wechatMiniAppSecret": "d2bec12d1fa4d8b5714ccbed1c0671e4",
"wechatPayMApiV3Key": "dh33tyagd1623623GDYGGDhe1d9dh171",
"wechatPayMCHID": "1624888906",
"wechatPayPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1vs3i/4sozxsK\noiS2S95rl+csLXQDugg23bcAVzXr7ZeTM/h81sCwraQDMnAJ/V3n7LxFAZeaFwLb\nyrkQ3lv4IEtWVgjVUkjkhvKGWcAp16Q/grOpxWmmn+VlW5ZGwQQ4DL4sC6BeEyxu\nUdtZ7UVc9lqsQX01R0oiegItJGPMMXNgeLFDEeoAwyIQcL0VG2bND7qrEVeQkLTj\nFm9ZkSb0LySPkSgqxMlSpiX1MS+wWWIHpq91CvdVHNowaGFA7ajU3RztbFAuxdpl\ng9RIocbrY1QwGXouQTEOUI2KZaES9rAa2lD6oWom4mRYiQ1oNO12XlUTcKsr84P5\nTq50dOYFAgMBAAECggEAQUns/mncnOlhhn1fANnaaf5kvlsJvTj8MHGPhyDNLxbo\nB6p4zqf7Cr0mGTvqQbxyGpnRvFxpEKLJlRmLSAMJOOapCbfYboGjy+yqfRcK0D02\nNNaIIinX3VK9fp7bKkm2cUgqnPoEPydWI79mNDTnYRDi29Se3R/iAuafl4XmD/js\nOKWG5tlXEatZ+gDbhnug4hp3xEGm4pbTS1HedV7HgYiKpxAT9uc/YmiHelZUUqlG\nwa1Nda2J88pzCSZX6TsRyY9UF/sjorxSNZGfj+5waeYMccj0Cx4uEQYgBv5tm+I+\nFTRgo/riM5gT9oRTnuNuzUrNwUNLyUsldvdQdlheNQKBgQDqwhrW52q3xClFLXR4\nHu9cTPt/p96MYE+xBllO/M9VFcG/hT++9R9l26+o26Lu+iIF5euDQiYSyURniGim\nWfV0I2q8HufhPLJBamvxRPI0V8LHwbY7c6HKnRR3eDAWAVYIcmsV4RLS67bsgtnr\nCgaFUDHXnpPKjxp1b4M5K3GqxwKBgQDGMLgAQn0a3nZwquPD4D+6tjy5xTxDX4Op\nULHBQheX0lBAR9Kcurzy4ca+T5xsyHd6SPwQxobRPei/3TBmc18J1T3nxJkTbEEP\nqy8k7MOWW2es3ou4CRL5lVKPx4YDWb5iT7X3Ue55JjPFAoj6FBOHxdvRQnDYsLFy\nSuSHPc280wKBgQCqfvCZNZcnAbtrd3jIKMd0hKB/dP7HesdF7TN9j1RRGi0NmIvU\ndxgnlOa9v05VO6rsF7D1MlyOdkhM3SAL+PewMmy5VcTYq4lWwyDEKGuzoi1fgIuG\nIBPYID8WCV77DFtcZSTqzf0q3HCM0vfLoQtdVQHt9Ein60ivE579LVUvTwKBgFid\nefgrwnJcG8serb5sKzKZvyc1CE/7igwPl5sYqSHqGJXVR1dqq4dR6iI3yHJfZASa\nU5JQogE21DXNeZGlbk4gOZDCt8sWcTTHTsoMzxsQfZeu3fwImqJb4NGG3eXrn5On\nnm4aBS3IJgelrYdbqKvhjPrQ4VISFxVKZUoPGUmfAoGARZbtbyl3s8cAExWe9dK6\nyWdkA3M2wR4n623W13rTQDc3D7p/hmlgB2x8it88m+580326G4qgwdUbG93EW1WQ\nahbkkcmdxzHgPVJdsyx22fR0TkeT1gjMpoSh4k3HOsbZE4EvlI459yE9fTSLBq2A\nFzGjYRpBTlRyrsSEhyVg4G0=\n-----END PRIVATE KEY-----",
"wechatPaySerialNo": "7A92D2D26D212D6BF934BDB10D547274807C3DDB",
"wxFilePath": "wxfile/2006/01/02/"
}
+78
View File
@@ -0,0 +1,78 @@
{
"cache": {
"db": {
"db": "默认false,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 24 * 30,非必须,过期时间,超时自动删除"
},
"memory": {
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 2,非必须,过期时间,超时自动删除"
},
"redis": {
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"host": "默认服务ip127.0.0.1,必须,如果需要使用redis服务时配置,",
"password": "默认密码空,必须,如果需要使用redis服务时配置,默认密码空",
"port": "默认服务端口:6379,必须,如果需要使用redis服务时配置,",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
"timeout": "默认60 * 60 * 24 * 15,非必须,过期时间,超时自动删除"
},
"注释": "可配置memorydbredis,默认启用memory,默认优先级为memory\u003eredis\u003edb,memory与数据库缓存设置项一致,缓存数据填充会自动反方向反哺,加入memory缓存过期将自动从redis更新,但memory永远不会更新redis,如果是集群建议不要开启memory,配置即启用"
},
"codeConfig": [
"注释:配置即启用,非必须,默认无",
{
"config": "默认config/app.json,必须,接口描述配置文件",
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
"table": "默认admin,必须,根据数据库内当前表名做为用户生成数据"
}
],
"crossDomain": "默认空 非必须,空字符串为不开启,如果需要跨域设置,auto为智能开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域",
"db": {
"mysql": {
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
"prefix": "默认空,非必须,数据表前缀",
"slave": {
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
"user": "默认root,必须,数据库用户名",
"注释": "从数据库配置,mysql里配置slave项即启用主从读写,减少数据库压力"
},
"user": "默认root,必须,数据库用户名",
"注释": "除prefix及主从数据库slave项,其他全部必须"
},
"sqlite": {
"path": "默认config/data.db,必须,数据库位置"
},
"注释": "配置即启用,非必须,默认使用sqlite数据库"
},
"defFile": "默认访问index.html或者index.htm文件,必须,默认访问文件类型",
"error": {
"1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用",
"2": "访问权限异常,没有登录或者登录异常等时候使用",
"3": "请求参数异常,request参数不满足要求,比如参数不足,参数类型错误,参数不满足要求等时候使用",
"4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用",
"5": "数据结果异常,一般用于无法给出response要求的格式要求下使用,比如response需要的是string格式但你只能提供int数据时",
"注释": "web服务内置错误提示,自定义异常建议10开始"
},
"logFile": "无默认,非必须,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"logLevel": "默认0,必须,0关闭,1打印,日志等级",
"mode": "默认0,非必须,0生产模式,1,测试模式,2开发模式,3内嵌代码模式,在开发模式下会显示更多的数据用于开发测试,并能够辅助研发,自动生成配置文件、代码等功能,web无缓存,数据库不启用缓存",
"modeRouterStrict": "默认false,必须,路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配",
"port": "默认80,必须,web服务开启Http端口,0为不启用http服务,默认80",
"sessionName": "默认HOTIME,必须,设置session的cookie名",
"tlsCert": "默认空,非必须,https证书",
"tlsKey": "默认空,非必须,https密钥",
"tlsPort": "默认空,非必须,web服务https端口,0为不启用https服务",
"tpt": "默认tpt,必须,web静态文件目录,默认为程序目录下tpt目录",
"webConnectLogFile": "无默认,非必须,webConnectLogShow开启之后才能使用,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"webConnectLogShow": "默认true,非必须,访问日志如果需要web访问链接、访问ip、访问时间打印,false为关闭true开启此功能"
}
Binary file not shown.
+72 -89
View File
@@ -1,106 +1,89 @@
package main
import (
"code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/tools/db"
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/dri/aliyun"
"code.hoteas.com/golang/hotime/dri/ddsms"
"code.hoteas.com/golang/hotime/dri/tencent"
"code.hoteas.com/golang/hotime/dri/wechat"
"code.hoteas.com/golang/hotime/example/app"
"code.hoteas.com/golang/hotime/example/provider"
//. "code.hoteas.com/golang/hotime/common"
"fmt"
//"go.hoteas.com/hotime/cache"
"golang.org/x/net/websocket"
"time"
//"go.hoteas.com/hotime/cache"
)
//
func main() {
date, _ := time.Parse("2006-01-02 15:04", time.Now().Format("2006-01-02")+" 14:00")
fmt.Println(date, date.Unix())
//fmt.Println("开始测试")
//t:=common.Map{"t":1652425167}
//fmt.Println(t.GetTime("t"))
//t["t"]=1652425167123
//fmt.Println(t.GetTime("t"))
//t["t"]=1652425167123456
//fmt.Println(t.GetTime("t"))
//t["t"]=1652425167123456789
//fmt.Println(t.GetTime("t"))
//fmt.Println("开始测试2")
//t["t"]="2006-01-02 15:04:05"
//fmt.Println(t.GetTime("t"))
//t["t"]="2006-01-02 15"
//fmt.Println(t.GetTime("t"))
//t["t"]="2006-01-02"
//fmt.Println(t.GetTime("t"))
//t["t"]="2006-01"
//fmt.Println(t.GetTime("t"))
//t["t"]="2006-01"
//fmt.Println(t.GetTime("t"))
//t["t"]="2006"
//fmt.Println(t.GetTime("t"))
//
//t["t"]="06"
//fmt.Println(t.GetTime("t"))
appIns := hotime.Application{}
//fmt.Println("0123456"[1:7])
appIns := Init("config/config.json")
appIns.SetConnectListener(func(context *hotime.Context) bool {
//fmt.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + hotime.Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":")))
aliyun.Company.Init(appIns.Config.GetString("aliyunCode"))
//this.HandlerStr = "/test.html"
return true
//初始化短信配置
ddsms.DDY.Init(appIns.Config.GetString("smsKey"))
//初始化公众号配置
wechat.H5Program.Init(appIns.Config.GetString("wechatAppID"), appIns.Config.GetString("wechatAppSecret"))
//初始化小程序配置
wechat.MiniProgram.Init(appIns.Config.GetString("wechatMiniAppID"), appIns.Config.GetString("wechatMiniAppSecret"))
//初始化小程序及公众号支付配置
wechat.WxPay.Init(appIns.Config.GetString("wechatPayMCHID"),
appIns.Config.GetString("wechatPaySerialNo"),
appIns.Config.GetString("wechatPayMApiV3Key"),
appIns.Config.GetString("wechatPayPrivateKey"))
tencent.Tencent.Init(appIns.Config.GetString("tencentId"), appIns.Config.GetString("tencentKey"))
//用户侧访问前设置
appIns.SetConnectListener(func(that *Context) (isFinished bool) {
//发送短信校验
//that.RespFunc = func() {
// go func(Form url.Values, RespData common.Map) {
// fmt.Println(Form)
// fmt.Println(RespData)
// }(that.Req.Form, that.RespData)
//
//}
return isFinished
})
//手动模式,
appIns.SetConfig("example/config/config.json")
//redis缓存接入
//ca:=hotime.CacheIns(&cache.CacheRedis{Host:appIns.Config.GetString("redisHost"),Pwd:appIns.Config.GetString("redisPwd"),Time:appIns.Config.GetCeilInt64("cacheLongTime")})
//ca.Cache("xyzm","dasdas")
//ca.Cache("xyzn","dasdas")
//ca.Cache("xyzo","dasdas")
//ca.Cache("xyz*",nil)
//fmt.Println(ca.Cache("xyzm").Data)
//mysql
//mysql.SetDB(&appIns)
//自动选择数据库
db.SetDB(&appIns)
//appIns.SetConnectDB(func(err ...*hotime.Error) *sql.DB {
// query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") +
// "@tcp(" + appIns.Config.GetString("dbHost") + ":" + appIns.Config.GetString("dbPort") + ")/" + appIns.Config.GetString("dbName") + "?charset=utf8"
// DB, e := sql.Open("mysql", query)
// if e != nil && len(err) != 0 {
// err[0].SetError(e)
// }
// return DB
//appIns.SetConnectListener(func(that *Context) (isFinished bool) {
//
// return isFinished
//})
//内存缓存数据库数据,错误则删除
// appIns.Db.CacheIns=hotime.CacheIns(&hotime.CacheMemory{})
appIns.SetSession(hotime.CacheIns(&hotime.CacheMemory{}), hotime.CacheIns(&hotime.CacheDb{Db: &appIns.Db, Time: appIns.Config.GetInt64("cacheTime")}))
appIns.SetCache(hotime.CacheIns(&hotime.CacheMemory{}))
//快捷模式
//appIns.SetDefault(func(err ...*hotime.Error) *sql.DB {
// query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") +
// "@tcp(" + appIns.Config.GetString("dbHost") + ":" + appIns.Config.GetString("dbPort") + ")/" + appIns.Config.GetString("dbName") + "?charset=utf8"
// DB, e := sql.Open("mysql", query)
// if e != nil && len(err) != 0 {
// err[0].SetError(e)
// }
// return DB
//appIns.Db.Action(func(db db.HoTimeDB) (isSuccess bool) {
// return isSuccess
//})
appIns.Run(hotime.Router{
"app": hotime.Proj{
"index": hotime.Ctr{
"test": func(this *hotime.Context) {
fmt.Println(this.Db.GetTag())
//x:=this.Db.Action(func(db hotime.HoTimeDB) bool {
//
// db.Insert("user",hotime.Map{"unickname":"dasdas"})
//
// return true
//})
hotime.LogError("dasdasdasdasdas")
this.Display(5, "dsadas")
},
"websocket": func(this *hotime.Context) {
hdler := websocket.Handler(func(ws *websocket.Conn) {
for true {
msg := make([]byte, 5120)
n, err := ws.Read(msg)
go func() {
time.Sleep(time.Second * 5)
ws.Write([]byte("dsadasdasgregergrerge"))
}()
if err != nil {
return
}
fmt.Printf("Receive: %s\n", msg[:n])
send_msg := "[" + string(msg[:n]) + "]"
m, err := ws.Write([]byte(send_msg))
if err != nil {
return
}
fmt.Printf("Send: %s\n", msg[:m])
}
})
hdler.ServeHTTP(this.Resp, this.Req)
},
},
},
appIns.Run(Router{
"provider": provider.Project,
"app": app.Project,
})
}
+144
View File
@@ -0,0 +1,144 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/aliyun"
"fmt"
)
var CompanyCtr = Ctr{
"search": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
keywords := that.Req.FormValue("keywords")
if keywords == "" {
keywords = that.Req.FormValue("company_name")
}
if keywords == "" {
keywords = that.Req.FormValue("name")
}
if len(keywords) < 2 {
that.Display(0, Slice{})
return
}
res, err := aliyun.Company.GetCompanyList(keywords)
if err != nil {
fmt.Println(err)
that.Display(0, Slice{})
return
}
if res.GetCeilInt64("status") != 200 {
fmt.Println(err)
that.Display(0, Slice{})
return
}
that.Display(0, res.GetMap("data").GetSlice("list"))
},
"search_info": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
name := that.Req.FormValue("name")
if len(name) < 2 {
that.Display(3, "找不到企业")
return
}
res, err := aliyun.Company.GetCompanyBaseInfo(name)
if err != nil {
fmt.Println(err)
that.Display(4, "查询失败")
return
}
if res.GetBool("status") != true {
fmt.Println(err)
that.Display(4, "查询失败")
return
}
that.Display(0, res.GetMap("data"))
},
"info": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("company", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到企业")
return
}
//先不做限制
//if res.GetCeilInt("salesman_id")!=that.Session("salesman_id").ToCeilInt(){
// that.Display(4,"不是你的企业")
// return
//}
res["technology_center_flag"] = strToArray(res.GetString("technology_center_flag"))
res["engineering_center_flag"] = strToArray(res.GetString("engineering_center_flag"))
res["engineering_laboratory_flag"] = strToArray(res.GetString("engineering_laboratory_flag"))
res["key_laboratory_flag"] = strToArray(res.GetString("key_laboratory_flag"))
res["industrial_design_center_flag"] = strToArray(res.GetString("industrial_design_center_flag"))
res["high_level_talents_flag1"] = strToArray(res.GetString("high_level_talents_flag1"))
res["tags"] = strToArray(res.GetString("tags"))
that.Display(0, res)
},
"edit": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
company := that.Db.Get("company", "*", Map{"id": id})
delete(company, "id")
delete(company, "salesman_id")
delete(company, "provider_id")
delete(company, "user_id")
delete(company, "del_flag")
delete(company, "state")
delete(company, "create_time")
delete(company, "modify_time")
data := Map{}
for k, _ := range company {
if that.Req.Form[k] != nil {
if k == "tags" || k == "high_level_talents_flag1" || k == "technology_center_flag" || k == "engineering_center_flag" || k == "engineering_laboratory_flag" || k == "key_laboratory_flag" || k == "industrial_design_center_flag" {
data[k] = arrayToStr(ObjToSlice(that.Req.Form[k]))
} else {
data[k] = that.Req.FormValue(k)
}
}
}
that.Db.Update("company", data, Map{"id": id})
that.Display(0, "更新成功")
},
}
+113
View File
@@ -0,0 +1,113 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var DeclareCtr = Ctr{
"info": func(that *Context) {
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("declare", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到通知公告")
return
}
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
delete(res, "click_num_base")
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
delete(res, "favorite_num_base")
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
if article != nil {
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
delete(article, "click_num_base")
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
delete(article, "favorite_num_base")
}
res["article"] = article
//浏览量加1
that.Db.Update("declare", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
//浏览量加1
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
//查询是否已关注
if that.Session("user_id").Data != nil {
favorite := that.Db.Get("favorite", "user_id,declare_id", Map{"AND": Map{"declare_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
res["favorite"] = favorite
}
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "declare_id[!]": nil}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["release_date[>=]"] = startTime
}
if finishTime != "" {
data["release_date[<=]"] = finishTime
}
dispatchName := that.Req.FormValue("dispatch_name")
if dispatchName != "" {
data["dispatch_name"] = dispatchName
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "release_time DESC"}
}
count := that.Db.Count("article", data)
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,declare_id,declare_id,declare_id,dispatch_name,policy_level", data)
for _, v := range res {
//if v.GetCeilInt("declare_id")>0{
// v["declare"]=that.Db.Get("declare","id,tag",Map{"id":v.GetCeilInt("declare_id")})
//}
//if v.GetCeilInt("declare_id")>0{
// v["declare"]=that.Db.Get("declare","tag",Map{"id":v.GetCeilInt("declare_id")})
//}
if v.GetCeilInt("declare_id") > 0 {
v["declare"] = that.Db.Get("declare", "money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt("declare_id")})
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+72
View File
@@ -0,0 +1,72 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"strings"
"time"
"unicode/utf8"
)
// Project 管理端项目
var Project = Proj{
"company": CompanyCtr,
"declare": DeclareCtr,
"matters": MattersCtr,
"order": OrderCtr,
"salesman": Salesman,
"sms": Sms,
"tag": TagCtr,
"user": UserCtr,
"wechat": Wechat,
}
func strToArray(str string) Slice {
s := Slice{}
olds := strings.Split(str, ",")
for _, v := range olds {
if v != "" {
s = append(s, v)
}
}
return s
}
func arrayToStr(ars Slice) string {
s := ","
if ars == nil {
return s
}
for k, _ := range ars {
s = s + ars.GetString(k) + ","
}
return s
}
//生成随机码的6位md5
func getSn() string {
x := Rand(8)
return Substr(Md5(ObjToStr(int64(x)+time.Now().UnixNano()+int64(Rand(6)))), 0, 6)
}
//生成随机码的4位随机数
func getCode() string {
//res := ""
//for i := 0; i < 4; i++ {
res := ObjToStr(RandX(1000, 9999))
//}
return res
}
// 过滤 emoji 表情
func FilterEmoji(content string) string {
new_content := ""
for _, value := range content {
_, size := utf8.DecodeRuneInString(string(value))
if size <= 3 {
new_content += string(value)
}
}
return new_content
}
+108
View File
@@ -0,0 +1,108 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var MattersCtr = Ctr{
"info": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
res := that.Db.Get("matters", "*", Map{"id": id})
if res == nil {
that.Display(4, "找不到事项")
return
}
if res.GetCeilInt("salesman_id") != that.Session("salesman_id").ToCeilInt() {
that.Display(4, "不是你的事项")
return
}
res["user"] = that.Db.Get("user", "id,name,nickname,company_id", Map{"id": res.GetCeilInt64("user_id")})
if res.GetMap("user") != nil && res.GetMap("user").GetCeilInt64("company_id") != 0 {
res["company"] = that.Db.Get("company", "id,name", Map{"id": res.GetMap("user").GetCeilInt64("company_id")})
}
that.Display(0, res)
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
userId := ObjToInt(that.Req.FormValue("id"))
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
tp := that.Req.FormValue("type")
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "salesman_id": that.Session("salesman_id").Data}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
}
if userId != 0 {
user := that.Db.Get("user", "id", Map{"AND": Map{"id": userId, "salesman_id": that.Session("salesman_id").Data}})
if user != nil {
data["user_id"] = userId
}
}
if tp != "" {
data["type"] = ObjToInt("tp")
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data}
}
count := that.Db.Count("matters", data)
res := that.Db.Page(page, pageSize).PageSelect("matters", "*", data)
for _, v := range res {
if v.GetCeilInt64("user_id") != 0 {
v["user"] = that.Db.Get("user", "id,avatar,name,nickname,company_id", Map{"id": v.GetCeilInt64("user_id")})
if v.GetMap("user") != nil && v.GetMap("user").GetCeilInt64("company_id") != 0 {
v["company"] = that.Db.Get("company", "id,name", Map{"id": v.GetMap("user").GetCeilInt64("company_id")})
}
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+239
View File
@@ -0,0 +1,239 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var OrderCtr = Ctr{
"info": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(2, "登录错误")
return
}
res := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
if res == nil {
that.Display(4, "找不到对应订单")
return
}
//if res.GetCeilInt("salesman_id") != that.Session("salesman_id").ToCeilInt() {
// that.Display(4, "不是你的订单")
// return
//}
if res.GetCeilInt("user_id") > 0 {
res["user"] = that.Db.Get("user", "name,nickname,avatar", Map{"id": res.GetCeilInt("user_id")})
}
res["order_record"] = that.Db.Select("order_record", "remarks,modify_time", Map{"order_id": res.GetCeilInt("id"), "ORDER": "modify_time DESC"})
that.Display(0, res)
},
"create_order_record": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
remarks := that.Req.FormValue("remarks")
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(2, "登录错误")
return
}
order := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
if order == nil {
that.Display(4, "不是属于你的订单")
return
}
if order.GetCeilInt("status") != 0 {
that.Display(4, "已完结订单,不可操作")
return
}
orderRecordId := that.Db.Insert("order_record", Map{
"order_id": id,
"user_id": order.GetCeilInt64("user_id"),
"remarks": salesman.GetString("name") + ":" + remarks,
"salesman_id": order.GetCeilInt64("salesman_id"),
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
that.Db.Update("order", Map{"order_record_id": orderRecordId}, Map{"id": id})
that.Display(0, "新增订单记录成功")
},
"edit": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
id := ObjToInt(that.Req.FormValue("id"))
if id == 0 {
that.Display(3, "请求参数异常")
return
}
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(2, "登录错误")
return
}
policyDeclareFlag := ObjToInt(that.Req.FormValue("policy_declare_flag"))
declareId := ObjToInt(that.Req.FormValue("declare_id"))
intellectualPropertyFlag := ObjToInt(that.Req.FormValue("intellectual_property_flag"))
intellectualPropertyCount := ObjToInt(that.Req.FormValue("intellectual_property_count"))
taxOnsultingFlag := ObjToInt(that.Req.FormValue("tax_onsulting_flag"))
lawFlag := ObjToInt(that.Req.FormValue("law_flag"))
status := ObjToInt(that.Req.FormValue("status"))
data := Map{
"policy_declare_flag": policyDeclareFlag,
"intellectual_property_flag": intellectualPropertyFlag,
"intellectual_property_count": intellectualPropertyCount,
"tax_onsulting_flag": taxOnsultingFlag,
"law_flag": lawFlag,
"status": status,
"modify_time[#]": "now()",
}
if declareId != 0 {
data["declare_id"] = declareId
}
order := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
if order == nil {
that.Display(4, "不是属于你的订单")
return
}
if order.GetCeilInt("status") != 0 {
that.Display(4, "已完结订单,不可操作")
return
}
data["order_record_id"] = that.Db.Insert("order_record", Map{
"order_id": id,
"user_id": order.GetCeilInt64("user_id"),
"remarks": salesman.GetString("name") + "变更了订单服务内容",
"salesman_id": order.GetCeilInt64("salesman_id"),
"create_time[#]": "now()",
"modify_time[#]": "now()",
"del_flag": 0,
})
re := that.Db.Update("order", data, Map{"id": id})
if re == 0 {
that.Display(4, "变更订单内容失败")
return
}
that.Display(0, "变更订单内容成功")
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
userId := ObjToInt(that.Req.FormValue("id"))
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(2, "登录错误")
return
}
data := Map{"del_flag": 0, "provider_id": salesman.GetCeilInt64("provider_id")}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"sn[~]": keywords, "name[~]": keywords}
}
if userId != 0 {
user := that.Db.Get("user", "id", Map{"AND": Map{"id": userId, "salesman_id": that.Session("salesman_id").Data}})
if user != nil {
data["user_id"] = userId
}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data}
}
count := that.Db.Count("order", data)
res := that.Db.Page(page, pageSize).PageSelect("order", "*", data)
for _, v := range res {
//if v.GetCeilInt("policy_id")>0{
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
//}
if v.GetCeilInt("user_id") > 0 {
v["user"] = that.Db.Get("user", "name,nickname,avatar", Map{"id": v.GetCeilInt("user_id")})
}
if v.GetCeilInt("order_record_id") > 0 {
v["order_record"] = that.Db.Get("order_record", "remarks,modify_time", Map{"id": v.GetCeilInt("order_record_id")})
}
}
that.Display(0, Map{"total": count, "data": res})
},
}
+143
View File
@@ -0,0 +1,143 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var Salesman = Ctr{
"test": func(that *Context) {
that.Session("salesman_id", 1)
that.Session("wechat_id", 1)
that.Display(0, 1)
},
"info": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(4, "找不到该业务员")
return
}
if salesman.GetString("nickname") == "" {
wechat := that.Db.Get("wechat", "*", Map{"salesman_id": salesman.GetCeilInt64("id")})
if wechat != nil {
salesman["nickname"] = wechat.GetString("nickname")
salesman["avatar"] = wechat.GetString("avatar")
that.Db.Update("salesman", Map{"nickname": wechat.GetString("nickname"), "avatar": wechat.GetString("avatar")}, Map{"id": salesman.GetCeilInt64("id")})
}
}
salesman["user"] = that.Db.Count("user", Map{"AND": Map{"salesman_id": that.Session("salesman_id").Data, "del_flag": 0}})
salesman["matters"] = that.Db.Count("matters", Map{"AND": Map{"salesman_id": that.Session("salesman_id").Data, "del_flag": 0}})
salesman["admin"] = that.Db.Get("admin", "id,name,avatar", Map{"id": salesman.GetCeilInt64("admin_id")})
salesman["provider"] = that.Db.Get("provider", "*", Map{"id": salesman.GetCeilInt64("provider_id")})
if salesman["provider"] != nil {
salesman["provider_salesman"] = that.Db.Get("salesman", "id,nickname,name,avatar", Map{"id": salesman.GetMap("provider").GetCeilInt64("salesman_id")})
}
that.Display(0, salesman)
},
"search": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
if salesman == nil {
that.Display(4, "找不到该业务员")
return
}
provider := that.Db.Get("provider", "*", Map{"id": salesman.GetCeilInt64("provider_id")})
if provider.GetCeilInt("salesman_id") != salesman.GetCeilInt("id") {
that.Display(0, Slice{})
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
data := Map{"del_flag": 0, "provider_id": salesman.GetCeilInt64("provider_id")}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"name[~]": keywords, "nickname[~]": keywords, "phone[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modifye_time[>=]"] = startTime
}
if finishTime != "" {
data["modifye_time[<=]"] = finishTime
}
count := that.Db.Count("salesman", data)
res := that.Db.Page(page, pageSize).PageSelect("salesman", "id,name,nickname,avatar", data)
that.Display(0, Map{"total": count, "data": res})
},
//用户微信公众号或者小程序登录
"login": func(that *Context) {
code := that.Req.FormValue("code")
phone := that.Req.FormValue("phone")
if phone != that.Session("phone").ToStr() && code == that.Session("code").ToStr() {
that.Display(3, "手机号或者验证码错误")
return
}
if that.Session("wechat_id").Data == nil {
that.Display(2, "还未登录")
return
}
wechat := that.Db.Get("wechat", "*", Map{"id": that.Session("wechat_id").ToCeilInt()})
salesman := that.Db.Get("salesman", "*", Map{"phone": phone})
if salesman == nil {
that.Display(3, "找不到企服商")
return
}
if wechat == nil {
that.Display(2, "还未绑定微信")
return
}
//有用户直接返回
if wechat.GetCeilInt("salesman_id") != 0 && wechat.GetCeilInt64("salesman_id") != salesman.GetCeilInt64("id") {
that.Display(5, "你已经绑定了其他商户")
return
}
that.Db.Update("wechat", Map{"salesman_id": salesman.GetCeilInt64("id")}, Map{"id": wechat.GetCeilInt64("id")})
that.Db.Update("salesman", Map{"login_time[#]": "now()", "modify_time[#]": "now()"},
Map{"id": salesman.GetCeilInt("id")})
wechat["salesman_id"] = salesman.GetCeilInt64("id")
that.Session("salesman_id", salesman.GetCeilInt64("id"))
that.Display(0, "登录成功!")
},
}
+38
View File
@@ -0,0 +1,38 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/ddsms"
)
var Sms = Ctr{
//只允许微信验证过的或者登录成功的发送短信
"send": func(that *Context) {
phone := that.Req.FormValue("phone")
if len(phone) < 11 {
that.Display(3, "手机号格式错误")
return
}
if that.Session("wechat_id").Data == nil && that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录不可发送短信")
return
}
salesman := that.Db.Get("salesman", "id", common.Map{"phone": phone})
if salesman == nil {
that.Display(3, "你还不是企服人员,请联系管理员")
return
}
code := getCode()
that.Session("phone", phone)
that.Session("code", code)
ddsms.DDY.SendYZM(phone, that.Config.GetString("smsLogin"), map[string]string{"code": code})
that.Display(0, "发送成功")
},
}
+83
View File
@@ -0,0 +1,83 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var TagCtr = Ctr{
"create": func(that *Context) {
if that.Session("user_id").Data == nil {
that.Display(2, "没有登录")
return
}
name := that.Req.FormValue("name")
oldTag := that.Db.Get("tag", "id", Map{"name": name})
if oldTag != nil {
that.Display(4, "此标签已存在")
return
}
re := that.Db.Insert("tag", Map{
"user_id": that.Session("user_id").Data,
"name": name,
"remark": "用户上传",
"create_time[#]": "now()",
"modify_time[#]": "now()",
"state": 1, //先置为异常状态,等待审核通过
"del_flag": 0,
})
if re == 0 {
that.Display(4, "添加失败")
return
}
that.Display(0, "添加成功")
return
},
//用户微信公众号或者小程序登录
"search": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 40
}
data := Map{"del_flag": 0, "state": 0}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"name[~]": keywords, "remark[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modify_time[>=]"] = startTime
}
if finishTime != "" {
data["modify_time[<=]"] = finishTime
}
if len(data) > 1 {
data = Map{"AND": data}
}
count := that.Db.Count("tag", data)
res := that.Db.Page(page, pageSize).PageSelect("tag", "id,name,remark", data)
that.Display(0, Map{"total": count, "data": res})
},
}
+150
View File
@@ -0,0 +1,150 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var UserCtr = Ctr{
//用户微信公众号或者小程序登录
"info": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
userId := ObjToInt(that.Req.FormValue("id"))
if userId == 0 {
that.Display(3, "参数错误")
return
}
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").ToCeilInt()})
if user == nil {
that.Display(4, "获取个人信息失败")
return
}
delete(user, "password")
that.Display(0, user)
},
"edit": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
userId := ObjToInt(that.Req.FormValue("id"))
if userId == 0 {
that.Display(3, "参数错误")
return
}
name := that.Req.FormValue("name")
nickname := that.Req.FormValue("nickname")
sex := that.Req.FormValue("sex")
email := that.Req.FormValue("email")
avatar := that.Req.FormValue("avatar")
address := that.Req.FormValue("address")
phone := that.Req.FormValue("phone") //如果更换手机号则要有新的短信验证码
data := Map{"modify_time[#]": "now()"}
if name != "" {
data["name"] = name
}
if nickname != "" {
data["nickname"] = nickname
}
if sex != "" {
data["sex"] = sex
}
if email != "" {
data["email"] = email
}
if avatar != "" {
data["avatar"] = avatar
}
if address != "" {
data["address"] = address
}
if phone != "" {
data["phone"] = phone
}
re := that.Db.Update("user", data, Map{"id": userId})
if re == 0 {
that.Display(4, "更新失败")
return
}
that.Display(4, "修改成功")
},
"search": func(that *Context) {
if that.Session("salesman_id").Data == nil {
that.Display(2, "没有登录")
return
}
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page < 1 {
page = 1
}
if pageSize <= 0 {
pageSize = 20
}
tp := ObjToInt(that.Req.FormValue("type")) //0,无操作,1,已扫码未认证,2,已认证,3,VIP会员
data := Map{"del_flag": 0, "salesman_id": that.Session("salesman_id").Data}
keywords := that.Req.FormValue("keywords")
if keywords != "" {
data["OR"] = Map{"name[~]": keywords, "nickname[~]": keywords, "phone[~]": keywords}
}
startTime := that.Req.FormValue("starttime")
finishTime := that.Req.FormValue("finishtime")
if startTime != "" {
data["modifye_time[>=]"] = startTime
}
if finishTime != "" {
data["modifye_time[<=]"] = finishTime
}
if tp == 1 {
data["certification_flag"] = 0
}
if tp == 2 {
data["certification_flag"] = 1
data["OR"] = Map{"expiration_time": nil, "expiration_time[#]": "now()"}
}
if tp == 3 {
data["certification_flag"] = 1
data["expiration_time[>]"] = time.Now().Format("2006-01-02 15:04:05")
}
if len(data) > 1 {
data = Map{"AND": data, "ORDER": "modify_time DESC"}
}
count := that.Db.Count("user", data)
res := that.Db.Page(page, pageSize).PageSelect("user", "*", data)
for _, v := range res {
delete(v, "password")
}
that.Display(0, Map{"total": count, "data": res})
},
}
+97
View File
@@ -0,0 +1,97 @@
package provider
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/dri/wechat"
)
var Wechat = Ctr{
////微信注册
"code": func(that *Context) {
if that.Req.FormValue("code") == "" {
that.Display(3, "参数不足")
return
}
appid, resToken, userInfo, err := wechat.H5Program.GetUserInfo(that.Req.FormValue("code"))
if err != nil {
that.Display(4, err)
return
}
//此次获取的微信信息
wechatInfo := Map{
"openid": userInfo.OpenID,
"acttoken": resToken.AccessToken,
"retoken": resToken.RefreshToken,
"appid": appid,
"unionid": userInfo.Unionid,
"nickname": FilterEmoji(userInfo.Nickname),
"avatar": userInfo.HeadImgURL,
//"create_time[#]":"now()",
"modify_time[#]": "now()",
"del_flag": 0,
"type": 1,
}
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": userInfo.OpenID, "del_flag": 0}})
if wechat != nil {
//有用户直接返回
if wechat.GetCeilInt("salesman_id") != 0 {
that.Db.Update("salesman", Map{"login_time[#]": "now()"},
Map{"id": wechat.GetCeilInt("salesman_id")})
that.Session("salesman_id", wechat.GetCeilInt("salesman_id"))
that.Display(0, "登录成功")
return
}
that.Session("wechat_id", wechat.GetCeilInt("id"))
that.Display(2, "暂未绑定")
return
}
wechatInfo["create_time[#]"] = "now()"
wechatInfo["id"] = that.Db.Insert("wechat", wechatInfo)
if wechatInfo.GetCeilInt("id") == 0 {
that.Display(4, "创建用户失败")
return
}
that.Session("wechat_id", wechatInfo.GetCeilInt("id"))
that.Display(2, "暂未绑定")
},
//网页签名
"sign": func(that *Context) {
signUrl := that.Req.FormValue("url")
if signUrl == "" {
that.Display(3, "参数不足")
return
}
cfg1, e := wechat.H5Program.GetSignUrl(signUrl)
if e != nil {
that.Display(4, e)
return
}
sign := Map{
"appId": cfg1.AppID,
"timestamp": cfg1.Timestamp,
"nonceStr": cfg1.NonceStr,
"signature": cfg1.Signature,
}
that.Display(0, sign)
},
}
-28
View File
@@ -1,28 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Sample of websocket with golang</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(function() {
var ws = new WebSocket("ws://localhost:8080/app/index/websocket");
ws.onmessage = function(e) {
$('<li>').text(e.data).appendTo($ul);
};
var $ul = $('#msg-list');
$('#sendBtn').click(function(){
var data = $('#name').val();
ws.send(data);
});
});
</script>
</head>
<body>
<input id="name" type="text"/>
<input type="button" id="sendBtn" value="send"/>
<ul id="msg-list"></ul>
</body>
</html>
+80
View File
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信登录</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<script type="text/javascript" src="js/hotime.js"></script>
<script type="text/javascript" src="js/qrcode.min.js"></script>
<style>
body{margin:0;}
.box{width:100%;height: 100vh;display:flex;align-items:center;justify-content: center;position: relative;}
.logo{position: absolute;top:7px;left: 17px;z-index: 2;width: 62px;height:22px;}
.logo img{width:100%;background-size: contain;}
.bg-img{position: absolute;top:0;left:0;width:100%;background-size: contain;}
.title{font-size: 14px;font-weight: bold;color: #FFF;letter-spacing: 6px;margin-bottom:50px;text-align: center;}
#qrcode{width:117px; height:117px; margin:23px auto 40px;}
.content{background: #D0ECF9;border: 1px solid rgba(255, 255, 255, 0.6);box-shadow: 0px 4px 12px rgba(25, 105, 146, 0.24);border-radius: 8px;padding:34px 0;font-size: 18px;color: #0674AE;margin:0 auto;width:65%;text-align: center;}
.footer{position: fixed;bottom:14px;width: 100%;font-size: 12px;
color: rgba(0, 0, 0, 0.7);text-align: center;line-height: 16px;}
</style>
</head>
<body>
<div class="box">
<div class="logo">
<img src="./img/logo_2@2x.png" alt="">
</div>
<img class="bg-img" src="./img/bg_up@2x.png">
<div style="flex:1;">
<div class="title">
欢迎使用政策狩猎精灵
</div>
<div class="content">
<div>初次使用需要绑定您的信息</div>
<div>请打开微信扫描下方二维码</div>
<div id="qrcode"></div>
</div>
</div>
<div class="footer">
<div>成都市创新创业服务平台</div>
<div>国家级双创示范平台</div>
</div>
</div>
<script>
var qrcode = new QRCode(document.getElementById("qrcode"), {
width: 117,
height: 117
})
function run() {
var data={"timestamp": window.H.getParam("timestamp"),"sn":window.H.getParam("sn")}
// if(data.code==null){
// location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4d97696b9ecb49fc&redirect_uri='+location.href+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
// return
// }
//定时器,3s刷新登录
window.H.post("/app/upan/login", data, function (res) {
if (res.status != 0) {
//展示二维码,链接扫码到一个页面传参timestamp&sn,页面内容:app/upan/createtimestamp&sn&phone&company_name&code,成功后跳转到首页
let url = 'https://'+location.host+'/#/qrcode?timestamp='+ window.H.getParam("timestamp")+"&sn="+ encodeURIComponent(window.H.getParam("sn"))
qrcode.makeCode(url)
setTimeout(function(){
run()
},3000)
return
}
// let res = { "result": { "acttoken": "56_ogEfWa4mglG-Ilf2kD50FfekZWimJXUouZ4gMKmkVP2CwcLwv2lHO35LOn5NSLOQ-yEAZcIs3FvgIBhk2uF9CA", "appid": "wx4d97696b9ecb49fc", "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLNj0yKXe77H8C60ic2lUFIx5hkibf0FluNCRfTkiazrBfuqclqRhm4nDug9Hx3nsXQhtzNdfchAvJTQ/132", "nickname": "候鸟半夏", "openid": "oPoZT6juCkF6fvnMHrCFI6SK_vK8", "retoken": "56_tjuJPobvbLVvOPtqPRZjTzQHR7i3Vmx_aGXOy9j0WsNTFS_JRnb4ArmUGhWtq6e7eCpUnPNKulIQ44CPiBnYEA", "unionid": "ofKK36PEkbIt0xMMUgch4H-bVaFI" }, "status": 0 }
location.href="/#/home"
})
}
run()
</script>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
module code.hoteas.com/golang/hotime
go 1.16
require (
github.com/garyburd/redigo v1.6.3
github.com/go-pay/gopay v1.5.78
github.com/go-sql-driver/mysql v1.6.0
github.com/mattn/go-sqlite3 v1.14.12
github.com/silenceper/wechat/v2 v2.1.2
github.com/sirupsen/logrus v1.8.1
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364
golang.org/x/net v0.0.0-20220225172249-27dd8689420f
)
+72
View File
@@ -0,0 +1,72 @@
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/garyburd/redigo v1.6.3 h1:HCeeRluvAgMusMomi1+6Y5dmFOdYV/JzoRrrbFlkGIc=
github.com/garyburd/redigo v1.6.3/go.mod h1:rTb6epsqigu3kYKBnaF028A7Tf/Aw5s0cqA47doKKqw=
github.com/go-pay/gopay v1.5.78 h1:wIHp8g/jK0ik5bZo2MWt3jAQsktT3nkdXZxlRZvljko=
github.com/go-pay/gopay v1.5.78/go.mod h1:M6Nlk2VdZHCbWphOw3rtbnz4SiOk6Xvxg6mxwDfg+Ps=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gomodule/redigo v1.8.5 h1:nRAxCa+SVsyjSBrtZmG/cqb6VbTmuRzpg/PoTFlpumc=
github.com/gomodule/redigo v1.8.5/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/silenceper/wechat/v2 v2.1.2 h1:+QfIMiYfwST2ZloTwmYp0O0p5Y1LYRZxfLWfMuSE30k=
github.com/silenceper/wechat/v2 v2.1.2/go.mod h1:0OprxYCCp2CZAKw06BBlnaczInTk2KxOLsKeiopshGg=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364 h1:X1Jws4XqrTH+p7FBQ7BpjW4qFXObKHWm0/XhW/GvqRs=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364 h1:kbor60vo37v7Hu+i17gooox9Rw281fVHNna8zwtDG1w=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364/go.mod h1:LeIUBOLhc+Y5YCEpZrULPD9lgoXXV4/EmIcoEvmHz9c=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0=
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+117
View File
@@ -0,0 +1,117 @@
package log
import (
"fmt"
log "github.com/sirupsen/logrus"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
func GetLog(path string, showCodeLine bool) *log.Logger {
hook := MyHook{
Field: "line",
Skip: 5,
Path: path, ShowCodeLine: showCodeLine,
}
loger := log.New()
loger.SetFormatter(&log.TextFormatter{})
loger.AddHook(&hook)
return loger
}
// MyHook ...
type MyHook struct {
Path string //存储日志的位置
ShowCodeLine bool //输出代码文件名称和日志行
Field string
Skip int
levels []log.Level
}
// Levels 只定义 error 和 panic 等级的日志,其他日志等级不会触发 hook
func (that *MyHook) Levels() []log.Level {
return log.AllLevels
}
// Fire 将异常日志写入到指定日志文件中
func (that *MyHook) Fire(entry *log.Entry) error {
if that.ShowCodeLine {
entry.Data[that.Field] = findCaller(that.Skip)
}
//不需要存储到文件
if that.Path == "" {
return nil
}
//存储到文件
logFilePath := time.Now().Format(that.Path)
err := os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend)
if err != nil {
return err
}
//os.Create(logFilePath)
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
bte, _ := entry.Bytes()
_, err = f.Write(bte)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
return nil
}
// 对caller进行递归查询, 直到找到非logrus包产生的第一个调用.
// 因为filename我获取到了上层目录名, 因此所有logrus包的调用的文件名都是 logrus/...
// 因此通过排除logrus开头的文件名, 就可以排除所有logrus包的自己的函数调用
func findCaller(skip int) string {
file := ""
line := 0
for i := 0; i < 10; i++ {
file, line = getCaller(skip + i)
if !strings.HasPrefix(file, "logrus") {
if file == "common/error.go" {
file, line = getCaller(skip + i + 1)
}
break
}
}
return fmt.Sprintf("%s:%d", file, line)
}
// 这里其实可以获取函数名称的: fnName := runtime.FuncForPC(pc).Name()
// 但是我觉得有 文件名和行号就够定位问题, 因此忽略了caller返回的第一个值:pc
// 在标准库log里面我们可以选择记录文件的全路径或者文件名, 但是在使用过程成并发最合适的,
// 因为文件的全路径往往很长, 而文件名在多个包中往往有重复, 因此这里选择多取一层, 取到文件所在的上层目录那层.
func getCaller(skip int) (string, int) {
_, file, line, ok := runtime.Caller(skip)
//fmt.Println(file)
//fmt.Println(line)
if !ok {
return "", 0
}
n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}
return file, line
}
+6 -6
View File
@@ -44,17 +44,17 @@ func Run() {
appIns.Run(hotime.Router{
"app": hotime.Proj{
"index": hotime.Ctr{
"test": func(this *hotime.Context) {
fmt.Println(this.Db.GetTag())
//x := this.Db.Action(func(db hotime.HoTimeDB) bool {
"test": func(that *hotime.Context) {
fmt.Println(that.Db.GetTag())
//x := that.Db.Action(func(db hotime.HoTimeDB) bool {
//
// db.Insert("user", hotime.Map{"unickname": "dasdas"})
//
// return true
//})
this.Display(0, 1)
that.Display(0, 1)
},
"websocket": func(this *hotime.Context) {
"websocket": func(that *hotime.Context) {
hdler := websocket.Handler(func(ws *websocket.Conn) {
for true {
msg := make([]byte, 5120)
@@ -73,7 +73,7 @@ func Run() {
fmt.Printf("Send: %s\n", msg[:m])
}
})
hdler.ServeHTTP(this.Resp, this.Req)
hdler.ServeHTTP(that.Resp, that.Req)
},
},
},
-155
View File
@@ -1,155 +0,0 @@
package hotime
import (
"encoding/json"
"errors"
"reflect"
)
//hotime的常用map
type Map map[string]interface{}
//获取string
func (this Map) GetString(key string, err ...*Error) string {
if len(err) != 0 {
err[0].SetError(nil)
}
return ObjToStr((this)[key])
}
func (this *Map) Pointer() *Map {
return this
}
//增加接口
func (this Map) Put(key string, value interface{}) {
//if this==nil{
// this=Map{}
//}
this[key] = value
}
//删除接口
func (this Map) Delete(key string) {
delete(this, key)
}
//获取Int
func (this Map) GetInt(key string, err ...*Error) int {
v := ObjToInt((this)[key], err...)
return v
}
//获取Int
func (this Map) GetInt64(key string, err ...*Error) int64 {
v := ObjToInt64((this)[key], err...)
return v
}
//获取向上取整Int64
func (this Map) GetCeilInt64(key string, err ...*Error) int64 {
v := ObjToCeilInt64((this)[key], err...)
return v
}
//获取向上取整Int
func (this Map) GetCeilInt(key string, err ...*Error) int {
v := ObjToCeilInt((this)[key], err...)
return v
}
//获取向上取整float64
func (this Map) GetCeilFloat64(key string, err ...*Error) float64 {
v := ObjToCeilFloat64((this)[key], err...)
return v
}
//获取Float64
func (this Map) GetFloat64(key string, err ...*Error) float64 {
v := ObjToFloat64((this)[key], err...)
return v
}
func (this Map) GetSlice(key string, err ...*Error) Slice {
//var v Slice
v := ObjToSlice((this)[key], err...)
return v
}
func (this Map) GetMap(key string, err ...*Error) Map {
//var data Slice
v := ObjToMap((this)[key], err...)
return v
}
func (this Map) Get(key string, err ...*Error) interface{} {
if v, ok := (this)[key]; ok {
return v
}
e := errors.New("没有存储key及对应的数据")
if len(err) != 0 {
err[0].SetError(e)
}
return nil
}
//请传递指针过来
func (this Map) ToStruct(stct interface{}) {
data := reflect.ValueOf(stct).Elem()
for k, v := range this {
ks := StrFirstToUpper(k)
dkey := data.FieldByName(ks)
if !dkey.IsValid() {
continue
}
switch dkey.Type().String() {
case "int":
dkey.SetInt(this.GetInt64(k))
case "int64":
dkey.Set(reflect.ValueOf(this.GetInt64(k)))
case "float64":
dkey.Set(reflect.ValueOf(this.GetFloat64(k)))
case "string":
dkey.Set(reflect.ValueOf(this.GetString(k)))
case "interface{}":
dkey.Set(reflect.ValueOf(v))
}
}
}
func (this Map) ToJsonString() string {
return ObjToStr(this)
}
func (this Map) JsonToMap(jsonStr string, err ...*Error) {
e := json.Unmarshal([]byte(jsonStr), &this)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
}
-93
View File
@@ -1,93 +0,0 @@
package hotime
//对象封装方便取用
type Obj struct {
Data interface{}
contextBase
}
func (this *Obj) Put(data interface{}) {
this.Data = data
}
func (this *Obj) ToInt(err ...Error) int {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToInt(this.Data, &this.Error)
}
func (this *Obj) ToInt64(err ...Error) int64 {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToInt64(this.Data, &this.Error)
}
func (this *Obj) ToFloat64(err ...Error) float64 {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToFloat64(this.Data, &this.Error)
}
//获取向上取整float64
func (this *Obj) ToCeilFloat64(err ...*Error) float64 {
if len(err) != 0 {
this.Error = *err[0]
}
v := ObjToCeilFloat64(this.Data, err...)
return v
}
func (this *Obj) ToStr() string {
return ObjToStr(this.Data)
}
func (this *Obj) ToMap(err ...Error) Map {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToMap(this.Data, &this.Error)
}
func (this *Obj) ToSlice(err ...Error) Slice {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToSlice(this.Data, &this.Error)
}
func (this *Obj) ToMapArray(err ...Error) []Map {
if len(err) != 0 {
this.Error = err[0]
}
return ObjToMapArray(this.Data, &this.Error)
}
func (this *Obj) ToObj() interface{} {
return this.Data
}
//获取向上取整Int64
func (this *Obj) ToCeilInt64(err ...*Error) int64 {
if len(err) != 0 {
this.Error = *err[0]
}
v := ObjToCeilInt64(this.Data, err...)
return v
}
//获取向上取整Int
func (this *Obj) ToCeilInt(err ...*Error) int {
if len(err) != 0 {
this.Error = *err[0]
}
v := ObjToCeilInt(this.Data, err...)
return v
}
+26 -41
View File
@@ -1,71 +1,56 @@
package hotime
import (
. "code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
)
//session对象
type SessionIns struct {
ShortCache CacheIns
LongCache CacheIns
SessionId string
*HoTimeCache
SessionId string
Map
contextBase
ContextBase
}
func (this *SessionIns) set() {
if this.ShortCache != nil {
this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
}
if this.LongCache != nil {
this.LongCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
}
func (that *SessionIns) set() {
that.HoTimeCache.Session(HEAD_SESSION_ADD+that.SessionId, that.Map)
}
func (this *SessionIns) Session(key string, data ...interface{}) *Obj {
func (that *SessionIns) Session(key string, data ...interface{}) *Obj {
if this.Map == nil {
this.get()
if that.Map == nil {
that.get()
}
if len(data) != 0 {
if data[0] == nil {
delete(this.Map, key)
this.set()
delete(that.Map, key)
that.set()
} else {
this.Map[key] = data[0]
this.set()
that.Map[key] = data[0]
that.set()
}
return &Obj{Data: nil}
}
return &Obj{Data: this.Map.Get(key)}
return &Obj{Data: that.Map.Get(key)}
}
func (this *SessionIns) get() {
func (that *SessionIns) get() {
if this.ShortCache != nil {
this.Map = this.ShortCache.Cache(HEAD_SESSION_ADD + this.SessionId).ToMap()
if this.Map != nil {
return
}
that.Map = that.HoTimeCache.Session(HEAD_SESSION_ADD + that.SessionId).ToMap()
if that.Map != nil {
return
}
if this.LongCache != nil {
this.Map = this.LongCache.Cache(HEAD_SESSION_ADD + this.SessionId).ToMap()
if this.Map != nil {
if this.ShortCache != nil {
this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
}
return
}
}
this.Map = Map{}
this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
that.Map = Map{}
that.HoTimeCache.Session(HEAD_SESSION_ADD+that.SessionId, that.Map)
return
}
func (this *SessionIns) Init(short CacheIns, long CacheIns) {
this.ShortCache = short
this.LongCache = long
func (that *SessionIns) Init(cache *HoTimeCache) {
that.HoTimeCache = cache
}
-87
View File
@@ -1,87 +0,0 @@
package hotime
import (
"errors"
)
type Slice []interface{}
//获取string
func (this Slice) GetString(key int, err ...*Error) string {
if len(err) != 0 {
err[0].SetError(nil)
}
return ObjToStr((this)[key])
}
//获取Int
func (this Slice) GetInt(key int, err ...*Error) int {
v := ObjToInt((this)[key], err...)
return v
}
//获取Int
func (this Slice) GetInt64(key int, err ...*Error) int64 {
v := ObjToInt64((this)[key], err...)
return v
}
//获取向上取整Int64
func (this Slice) GetCeilInt64(key int, err ...*Error) int64 {
v := ObjToCeilInt64((this)[key], err...)
return v
}
//获取向上取整Int
func (this Slice) GetCeilInt(key int, err ...*Error) int {
v := ObjToCeilInt((this)[key], err...)
return v
}
//获取向上取整float64
func (this Slice) GetCeilFloat64(key int, err ...*Error) float64 {
v := ObjToCeilFloat64((this)[key], err...)
return v
}
//获取Float64
func (this Slice) GetFloat64(key int, err ...*Error) float64 {
v := ObjToFloat64((this)[key], err...)
return v
}
func (this Slice) GetSlice(key int, err ...*Error) Slice {
v := ObjToSlice((this)[key], err...)
return v
}
func (this Slice) GetMap(key int, err ...*Error) Map {
//var v Map
v := ObjToMap((this)[key], err...)
return v
}
func (this Slice) Get(key int, err ...*Error) interface{} {
if key < len(this) {
return this[key]
}
e := errors.New("没有存储key及对应的数据")
if len(err) != 0 {
err[0].SetError(e)
}
return nil
}
func (this Slice) Put(key int, value interface{}) {
this[key] = value
}
func (this Slice) ToJsonString() string {
return ObjToStr(this)
}
-18
View File
@@ -1,18 +0,0 @@
package db
import (
"code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/tools/mysql"
"code.hoteas.com/golang/hotime/tools/sqlite"
"strings"
)
func SetDB(appIns *hotime.Application) {
if appIns.Config.GetString("dbType") == "sqlite" || strings.Index(appIns.Config.GetString("dbName"), ".db") == len(appIns.Config.GetString("dbName"))-3 {
appIns.Config["dbType"] = "sqlite"
sqlite.SetDB(appIns)
} else {
appIns.Config["dbType"] = "mysql"
mysql.SetDB(appIns)
}
}
-19
View File
@@ -1,19 +0,0 @@
package mysql
import (
"code.hoteas.com/golang/hotime"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func SetDB(appIns *hotime.Application) {
appIns.SetConnectDB(func(err ...*hotime.Error) *sql.DB {
query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") +
"@tcp(" + appIns.Config.GetString("dbHost") + ":" + appIns.Config.GetString("dbPort") + ")/" + appIns.Config.GetString("dbName") + "?charset=utf8"
DB, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
return DB
})
}
-17
View File
@@ -1,17 +0,0 @@
package sqlite
import (
"code.hoteas.com/golang/hotime"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func SetDB(appIns *hotime.Application) {
appIns.SetConnectDB(func(err ...*hotime.Error) *sql.DB {
db, e := sql.Open("sqlite3", appIns.Config.GetString("dbName"))
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
return db
})
}
+2 -15
View File
@@ -1,21 +1,8 @@
package hotime
//控制器
// Ctr 控制器
type Ctr map[string]Method
type Proj map[string]Ctr
type Router map[string]Proj
type MethodRouter map[string]Method //直接字符串关联函数
type Method func(this *Context)
type CacheIns interface {
//set(key string, value interface{}, time int64)
//get(key string) interface{}
//delete(key string)
Cache(key string, data ...interface{}) *Obj
}
//单条缓存数据
type cacheData struct {
time int64
data interface{}
}
type Method func(that *Context)
+109 -43
View File
@@ -1,21 +1,40 @@
package hotime
import (
. "code.hoteas.com/golang/hotime/common"
)
var IsRun = false //当前状态
var App = map[string]*Application{} //整个项目
//var Db = HoTimeDB{} //数据库实例
var Config = Map{
"debug": 1, //debug 0关闭1开启
"logLevel": LOG_FMT,
"dbHost": "127.0.0.1",
"dbName": "test",
"dbUser": "root",
"dbPwd": "root",
"dbPort": "3306",
"dbCached": 0, //0不开启缓存
"cacheShortTime": 60 * 60 * 2,
"cacheLongTime": 60 * 60 * 24 * 30,
"mode": 2, //模式 0生产模式,1,测试模式,2,开发模式
//"codeConfig": Map{
// "admin": "config/app.json",
//},
"codeConfig": Slice{
Map{
"table": "admin", //默认admin,必须,有则根据数据库内当前表名做为用户生成数据
"name": "", //默认admin,非必须,有则生成代码到此目录,无则采用缺省模式使用表名
"config": "config/app.json", //默认config/app.json,必须,接口描述配置文件
"rule": "config/rule.json", //默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成
"mode": 0, //默认0,非必须,0为内嵌代码模式,1为生成代码模式
},
},
"db": Map{
"sqlite": Map{
"path": "config/data.db",
},
},
"cache": Map{
"memory": Map{
"timeout": 60 * 60 * 2,
"db": true,
"session": true,
},
},
"error": Map{
"1": "内部系统异常",
"2": "访问权限异常",
@@ -23,32 +42,80 @@ var Config = Map{
"4": "数据处理异常",
"5": "数据结果异常",
},
"tpt": "tpt",
"defFile": []string{"index.html", "index.htm"},
"modeRouterStrict": false, //路由严格模式/a/b/c
"port": "80",
"sessionName": "HOTIME",
"tlsPort": "0",
"tlsKey": "",
"tlsCert": "",
"tpt": "tpt",
"defFile": []string{"index.html", "index.htm"},
"port": "80",
"sessionName": "HOTIME",
}
var ConfigNote = Map{
"logLevel": "日志等级0关闭,1打印",
"logFile": "如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"debug": "是否开启debug模式,0关闭,其他开启,debug模式下日志展示更全", //debug 0关闭1开启
"dbHost": "数据库ip地址默认127.0.0.1",
"dbName": "数据库名称,sqlite为文件路径比如a/x.db",
"dbUser": "数据库用户名",
"dbPwd": "数据库密码",
"dbPort": "数据库端口",
"dbType": "如果需要使用自动数据库配置,请设置此项,手动配置数据库不需要,目前支持mysql,sqlite",
"dbCached": "是否开启数据库缓存0为关闭,其他开启", //0不开启缓存
"redisHost": "如果需要使用redis服务时配置,默认服务ip127.0.0.1",
"redisPort": "如果需要使用redis服务时配置,默认服务端口:6379",
"redisPwd": "如果需要使用redis服务时配置,默认服务密码:123456",
"cacheShortTime": "两级缓存,短缓存存储时间60 * 60 * 2,一般为内存缓存",
"cacheLongTime": "两级缓存,长缓存存储时间60 * 60 * 24 * 30,一般为数据库或者redis缓存",
"logLevel": "默认0,必须0关闭,1打印,日志等级",
"logFile": "无默认,非必须,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"webConnectLogShow": "默认true,非必须,访问日志如果需要web访问链接、访问ip、访问时间打印,false为关闭true开启此功能",
"webConnectLogFile": "无默认,非必须,webConnectLogShow开启之后才能使用,如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置",
"mode": "默认0,非必须,0生产模式,1,测试模式,2开发模式,3内嵌代码模式,在开发模式下会显示更多的数据用于开发测试,并能够辅助研发,自动生成配置文件、代码等功能,web无缓存,数据库不启用缓存", //debug 0关闭1开启
//"codeConfig": Map{
// "注释": "配置即启用,非必须,默认无",
// //"package":"默认admin,必须,mode模式为2时会自动生成包文件夹和代码文件",
// //"path":""
//
// "packageName": "默认无,必须,包名称以及应用名,生成代码的配置文件地址,比如config/app.json,数据库有更新时自动更新配置文件以及对应的生成文件",
//},
"codeConfig": Slice{
"注释:配置即启用,非必须,默认无",
Map{ //默认无,必须,接口类别名称
//"注释": "", //
"table": "默认admin,必须,根据数据库内当前表名做为用户生成数据",
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
"config": "默认config/app.json,必须,接口描述配置文件", //
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
},
},
"db": Map{
"注释": "配置即启用,非必须,默认使用sqlite数据库",
"mysql": Map{
"注释": "除prefix及主从数据库slave项,其他全部必须",
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"user": "默认root,必须,数据库用户名",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
"prefix": "默认空,非必须,数据表前缀",
"slave": Map{
"注释": "从数据库配置,mysql里配置slave项即启用主从读写,减少数据库压力",
"host": "默认127.0.0.1,必须,数据库ip地址",
"name": "默认test,必须,数据库名称",
"user": "默认root,必须,数据库用户名",
"password": "默认root,必须,数据库密码",
"port": "默认3306,必须,数据库端口",
},
},
"sqlite": Map{
"path": "默认config/data.db,必须,数据库位置",
},
},
"cache": Map{
"注释": "可配置memorydbredis,默认启用memory,默认优先级为memory>redis>db,memory与数据库缓存设置项一致,缓存数据填充会自动反方向反哺,加入memory缓存过期将自动从redis更新,但memory永远不会更新redis,如果是集群建议不要开启memory,配置即启用",
"memory": Map{
"timeout": "默认60 * 60 * 2,非必须,过期时间,超时自动删除",
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
},
"db": Map{
"timeout": "默认60 * 60 * 24 * 30,非必须,过期时间,超时自动删除",
"db": "默认false,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
},
"redis": Map{
"host": "默认服务ip127.0.0.1,必须,如果需要使用redis服务时配置,",
"port": "默认服务端口:6379,必须,如果需要使用redis服务时配置,",
"password": "默认密码空,必须,如果需要使用redis服务时配置,默认密码空",
"timeout": "默认60 * 60 * 24 * 15,非必须,过期时间,超时自动删除",
"db": "默认true,非必须,缓存数据库,启用后能减少数据库的读写压力",
"session": "默认true,非必须,缓存web session,同时缓存session保持的用户缓存",
},
},
"error": Map{
"1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用",
"2": "访问权限异常,没有登录或者登录异常等时候使用",
@@ -57,14 +124,13 @@ var ConfigNote = Map{
"5": "数据结果异常,一般用于无法给出response要求的格式要求下使用,比如response需要的是string格式但你只能提供int数据时",
"注释": "web服务内置错误提示,自定义异常建议10开始",
},
"tpt": "静态文件目录,默认为程序目录下tpt目录",
"defFile": "默认访问文件,默认访问index.html或者index.htm文件",
"crossDomain": "如果需要跨域设置,空字符串为不开启,*为开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域", //是否开启跨域
"modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配", //路由严格模式/a/b/c
"connectLogShow": "如果需要web访问链接、访问ip、访问时间打印,0为关闭其他数字开启此功能",
"sessionName": "设置session的cookie名默认HOTIME",
"port": "web服务开启Http端口,0为不启用http服务,默认80",
"tlsPort": "web服务https端口,0为不启用https服务",
"tlsKey": "https密钥",
"tlsCert": "https证书",
"tpt": "默认tpt,必须,web静态文件目录,默认为程序目录下tpt目录",
"defFile": "默认访问index.html或者index.htm文件,必须,默认访问文件类型",
"crossDomain": "默认空 非必须,空字符串为不开启,如果需要跨域设置,auto为智能开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域", //是否开启跨域
"modeRouterStrict": "默认false,必须,路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配", //路由严格模式/a/b/c
"sessionName": "默认HOTIME,必须,设置session的cookie名",
"port": "默认80,必须,web服务开启Http端口,0为不启用http服务,默认80",
"tlsPort": "默认空,非必须,web服务https端口,0为不启用https服务",
"tlsKey": "默认空,非必须,https密钥",
"tlsCert": "默认空,非必须,https证书",
}