mirror of
https://gitee.com/johng/gf
synced 2026-06-08 18:47:45 +08:00
Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 872536c035 | |||
| c7a6a6fff0 | |||
| 0cb82d70fd | |||
| acac5a2ad6 | |||
| 9ec15ad2ca | |||
| ad50ca6e60 | |||
| 8285c31bf1 | |||
| 230be66fa9 | |||
| 2c53f934c9 | |||
| 08785cb272 | |||
| bd0207c938 | |||
| 6fad737617 | |||
| af4148d985 | |||
| 922eaf4d42 | |||
| 4b5153950f | |||
| 78010d2bd7 | |||
| 85c2ed1bf2 | |||
| 429aa90e0d | |||
| 4f792b347d | |||
| 6d8ced21b9 | |||
| 8b3eb5b02d | |||
| b90d61b27c | |||
| 85606e3e7e | |||
| 1fc85d49bd | |||
| a5cfb4e638 | |||
| 38754bf062 | |||
| f1818ed2ff | |||
| 352ad17715 | |||
| e50b8d9632 | |||
| 2107061a46 | |||
| 61f57b4895 | |||
| d34273abff | |||
| 0aff0f0362 | |||
| 68949b69bc | |||
| c56c77d3a1 | |||
| dc82ce395a | |||
| 2a29483456 | |||
| 4f10562980 | |||
| 6863928b06 | |||
| aa4dca11f0 | |||
| dc6ab820ce | |||
| be0fa4d60b | |||
| a86d2272af | |||
| 08550d413e | |||
| b89294561b | |||
| 630d8fdb43 | |||
| c4c7e6caf4 | |||
| 8a8fea1257 | |||
| 0e0f297a3f | |||
| fd2c0f2b24 | |||
| ecc6e3888d | |||
| 47c073aaf3 | |||
| 07476a4349 | |||
| 817148f3a1 | |||
| bd4271cd8c | |||
| b1804fc346 | |||
| a3886c2179 | |||
| f258b5bf1c | |||
| a05361011f | |||
| 6b34a77251 | |||
| afb1adee3d | |||
| 22fa7a37f3 | |||
| 6a58bfc574 | |||
| 64124c60fc | |||
| 9a0066de62 | |||
| 22c7c7403b | |||
| 83db8e4b15 | |||
| 25f2e121e7 | |||
| 1325a145d8 | |||
| 9bc49c0b29 | |||
| 8e84e5b0f3 | |||
| a42e6b0c45 | |||
| 51bb7a9854 | |||
| 62580b5719 | |||
| 15cfd5ce5c | |||
| 11c89c4090 | |||
| 4a12cb9f27 | |||
| 32f575eddd | |||
| fbb4cb3b1c | |||
| c9d2d5e8ab | |||
| 93763192f2 | |||
| 80e0eae6b0 | |||
| 4e3d735b90 | |||
| 60e5a7da28 | |||
| 997b5ba889 | |||
| b3e7ca1963 | |||
| 5a82d695c1 | |||
| 64a0427150 |
@ -1,6 +1,7 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- "1.10.x"
|
||||
- "1.11.x"
|
||||
- "1.12.x"
|
||||
|
||||
|
||||
62
README.MD
62
README.MD
@ -5,9 +5,8 @@
|
||||
[](https://travis-ci.org/gogf/gf)
|
||||
[](https://goreportcard.com/report/github.com/gogf/gf)
|
||||
[](https://codecov.io/gh/gogf/gf/branch/master)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf/releases)
|
||||
|
||||
<!--
|
||||
GoFrame is a modular, loose-coupled, production-ready and most-powerful application development framework of golang. Providing a series of core components and dozens of practical modules, such as: cache, logging, containers, timer, validator, database orm, etc. Supporting web server integrated with router, cookie, session, logger, configure, template, https, hooks, rewrites and many more features.
|
||||
@ -31,7 +30,7 @@ golang version >= 1.9.2
|
||||
|
||||
# Documentation
|
||||
|
||||
* [GoDoc](https://godoc.org/github.com/gogf/gf)
|
||||
* [APIDoc](https://godoc.org/github.com/gogf/gf)
|
||||
* [中文文档](https://goframe.org)
|
||||
|
||||
# Architecture
|
||||
@ -65,42 +64,35 @@ func main() {
|
||||
|
||||
`GF` is licensed under the [MIT License](LICENSE), 100% free and open-source, forever.
|
||||
|
||||
# Contributors(TOP 10)
|
||||
# Contributors
|
||||
|
||||
<a href="https://gitee.com/johng" target="_blank" title="John"><img src="https://gitee.com/uploads/27/1309327_johng.png?1530630243" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/wenzi1" target="_blank" title="蚊子"><img src="https://images.gitee.com/uploads/22/1923122_wenzi1.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/zseeker" target="_blank" title="zseeker"><img src="https://goframe.org/images/contributors/zseeker.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/ymrjqyy" target="_blank" title="一墨染尽青衣颜"><img src="https://images.gitee.com/uploads/27/876827_ymrjqyy.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://github.com/chenyang351" target="_blank" title="chenyang351"><img src="https://avatars1.githubusercontent.com/u/30063958?s=60&v=4" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/wxkj" target="_blank" title="wxkj"><img src="https://gitee.com/uploads/56/91356_wxkj.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://github.com/wxkj001" target="_blank" title="3wxkj001
|
||||
"><img src="https://avatars0.githubusercontent.com/u/7794279?s=60&v=4" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/zhangjinfu" target="_blank" title="张金富"><img src="https://images.gitee.com/uploads/63/356163_zhangjinfu.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/garfieldkwong" target="_blank" title="GarfieldKwong"><img src="https://goframe.org/images/contributors/garfieldkwong.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/qq1054000800" target="_blank" title="hello"><img src="https://gitee.com/uploads/9/2209_qq1054000800.jpg" width="60" align="left"></a>
|
||||
|
||||
<br /><br /><br />
|
||||
- [aloncn](https://github.com/aloncn)
|
||||
- [chenyang351](https://github.com/chenyang351)
|
||||
- [garfieldkwong](https://gitee.com/garfieldkwong)
|
||||
- [hailaz](https://gitee.com/hailaz)
|
||||
- [johng](https://gitee.com/johng)
|
||||
- [pibigstar](https://github.com/pibigstar)
|
||||
- [qq1054000800](https://gitee.com/qq1054000800)
|
||||
- [wenzi1](https://gitee.com/wenzi1)
|
||||
- [wxkj001](https://github.com/wxkj001)
|
||||
- [ymrjqyy](https://gitee.com/ymrjqyy)
|
||||
- [youyixiao](https://github.com/youyixiao)
|
||||
- [zhangjinfu](https://gitee.com/zhangjinfu)
|
||||
- [zhaopengme](https://github.com/zhaopengme)
|
||||
- [zseeker](https://gitee.com/zseeker)
|
||||
|
||||
# Donators
|
||||
|
||||
<a href="https://gitee.com/tiangenglan" target="_blank" title="zhuhuan12"><img src="https://images.gitee.com/uploads/99/1167099_tiangenglan.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/zhuhuan12" target="_blank" title="zhuhuan12"><img src="https://gitee.com/uploads/39/751839_zhuhuan12.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/zfan_codes" target="_blank" title="范钟"><img src="https://images.gitee.com/uploads/32/2044832_zfan_codes.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/hailaz" target="_blank" title="HaiLaz"><img src="https://gitee.com/uploads/87/1273187_hailaz.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/mg91" target="_blank" title="mg91"><img src="https://images.gitee.com/uploads/30/1410930_mg91.png" width="60" align="left"></a>
|
||||
- [flyke-xu](https://gitee.com/flyke-xu)
|
||||
- [hailaz](https://gitee.com/hailaz)
|
||||
- [mg91](https://gitee.com/mg91)
|
||||
- [pibigstar](https://github.com/pibigstar)
|
||||
- [tiangenglan](https://gitee.com/tiangenglan)
|
||||
- [wxkj](https://gitee.com/wxkj)
|
||||
- [zhuhuan12](https://gitee.com/zhuhuan12)
|
||||
- [zfan_codes](https://gitee.com/zfan_codes)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
48
README_ZH.MD
48
README_ZH.MD
@ -5,9 +5,8 @@
|
||||
[](https://travis-ci.org/gogf/gf)
|
||||
[](https://goreportcard.com/report/github.com/gogf/gf)
|
||||
[](https://codecov.io/gh/gogf/gf/branch/master)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf/releases)
|
||||
|
||||
`GF(Go Frame)`是一款模块化、松耦合、生产级Go应用开发框架。提供了常用的核心开发组件,如:缓存、日志、文件、时间、队列、数组、集合、字符串、定时器、命令行、文件锁、内存锁、对象池、连接池、数据校验、数据编码、文件监控、定时任务、数据库ORM、TCP/UDP组件、进程管理/通信、
|
||||
并发安全容器等等。并提供了Web服务开发的系列核心组件,如:Router、Cookie、Session、服务注册、配置管理、模板引擎等等,支持热重启、热更新、多域名、多端口、多服务、HTTPS、Rewrite等特性。
|
||||
@ -85,30 +84,31 @@ func main() {
|
||||
<img src="https://goframe.org/images/donate.png" width="300"/>
|
||||
</a>
|
||||
|
||||
# 贡献者(TOP 10)
|
||||
# 贡献者
|
||||
|
||||
<a href="https://gitee.com/johng" target="_blank" title="John"><img src="https://gitee.com/uploads/27/1309327_johng.png" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/wenzi1" target="_blank" title="蚊子"><img src="https://images.gitee.com/uploads/22/1923122_wenzi1.png" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/zseeker" target="_blank" title="zseeker"><img src="https://goframe.org/images/contributors/zseeker.png" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/ymrjqyy" target="_blank" title="一墨染尽青衣颜"><img src="https://images.gitee.com/uploads/27/876827_ymrjqyy.png" width="60" align="left"></a>
|
||||
<a href="https://github.com/chenyang351" target="_blank" title="chenyang351"><img src="https://avatars1.githubusercontent.com/u/30063958?s=60&v=4" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/wxkj" target="_blank" title="wxkj"><img src="https://gitee.com/uploads/56/91356_wxkj.png" width="60" align="left"></a>
|
||||
<a href="https://github.com/wxkj001" target="_blank" title="3wxkj001
|
||||
"><img src="https://avatars0.githubusercontent.com/u/7794279?s=60&v=4" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/zhangjinfu" target="_blank" title="张金富"><img src="https://images.gitee.com/uploads/63/356163_zhangjinfu.png" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/garfieldkwong" target="_blank" title="GarfieldKwong"><img src="https://goframe.org/images/contributors/garfieldkwong.png" width="60" align="left"></a>
|
||||
<a href="https://gitee.com/qq1054000800" target="_blank" title="hello"><img src="https://gitee.com/uploads/9/2209_qq1054000800.jpg" width="60" align="left"></a>
|
||||
|
||||
<br /><br /><br />
|
||||
- [aloncn](https://github.com/aloncn)
|
||||
- [chenyang351](https://github.com/chenyang351)
|
||||
- [garfieldkwong](https://gitee.com/garfieldkwong)
|
||||
- [hailaz](https://gitee.com/hailaz)
|
||||
- [johng](https://gitee.com/johng)
|
||||
- [pibigstar](https://github.com/pibigstar)
|
||||
- [qq1054000800](https://gitee.com/qq1054000800)
|
||||
- [wenzi1](https://gitee.com/wenzi1)
|
||||
- [wxkj001](https://github.com/wxkj001)
|
||||
- [ymrjqyy](https://gitee.com/ymrjqyy)
|
||||
- [youyixiao](https://github.com/youyixiao)
|
||||
- [zhangjinfu](https://gitee.com/zhangjinfu)
|
||||
- [zhaopengme](https://github.com/zhaopengme)
|
||||
- [zseeker](https://gitee.com/zseeker)
|
||||
|
||||
# 捐赠者
|
||||
|
||||
<a href="https://gitee.com/tiangenglan" target="_blank" title="zhuhuan12"><img src="https://images.gitee.com/uploads/99/1167099_tiangenglan.png" width="60" align="left"></a>
|
||||
- [flyke-xu](https://gitee.com/flyke-xu)
|
||||
- [hailaz](https://gitee.com/hailaz)
|
||||
- [mg91](https://gitee.com/mg91)
|
||||
- [pibigstar](https://github.com/pibigstar)
|
||||
- [tiangenglan](https://gitee.com/tiangenglan)
|
||||
- [wxkj](https://gitee.com/wxkj)
|
||||
- [zhuhuan12](https://gitee.com/zhuhuan12)
|
||||
- [zfan_codes](https://gitee.com/zfan_codes)
|
||||
|
||||
<a href="https://gitee.com/zhuhuan12" target="_blank" title="zhuhuan12"><img src="https://gitee.com/uploads/39/751839_zhuhuan12.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/zfan_codes" target="_blank" title="范钟"><img src="https://images.gitee.com/uploads/32/2044832_zfan_codes.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/hailaz" target="_blank" title="HaiLaz"><img src="https://gitee.com/uploads/87/1273187_hailaz.png" width="60" align="left"></a>
|
||||
|
||||
<a href="https://gitee.com/mg91" target="_blank" title="mg91"><img src="https://images.gitee.com/uploads/30/1410930_mg91.png" width="60" align="left"></a>
|
||||
48
RELEASE.MD
48
RELEASE.MD
@ -1,3 +1,51 @@
|
||||
# `v1.6.0` (2019-04-09)
|
||||
|
||||
## 新功能/改进
|
||||
1. `gcron`定时任务模块增加运行日志记录功能:https://goframe.org/os/gcron/index
|
||||
1. `gredis`增加全局分组配置功能,并增加更多的配置选项`maxIdle/maxActive/idleTimeout/maxConnLifetime`:https://goframe.org/database/gredis/index
|
||||
1. `gcfg`模块增加更多的默认配置文件检索路径,并且增加全局分组配置特性,增加`Instance`单例方法:https://goframe.org/os/gcfg/index
|
||||
1. `gview`模块增加更多的默认配置文件检索路径,并且增加`Instance`单例方法:https://goframe.org/os/gview/index
|
||||
1. `ghttp`模块新功能及改进:
|
||||
- 新增`CORS`HTTP(S)跨域请求特性: https://goframe.org/net/ghttp/cors
|
||||
- 增加`TLSConfig`配置功能;
|
||||
- 去掉路由注册方法的`error`返回值,当产生注册错误时直接终端打印错误/输出到日志文件;
|
||||
- 增加在`HTTP Code 302`跳转时的`Set-Cookie`支持;
|
||||
- 增加对`SESSION ID`的安全性检查;
|
||||
- 增加对基于`HTTPS`的`WebSocket`支持(`WSS`):https://goframe.org/net/ghttp/websocket/index
|
||||
- `Request`对象增加`Error`方法,用于输出自定义错误信息到`WebServer`错误日志中;
|
||||
- 其他一些改进;
|
||||
1. `gdb`模块新功能及改进:
|
||||
- 新增`Instance`单例管理方法;
|
||||
- 新增`Structs/Scan`链式操作方法,`gdb.DB/TX`新增`GetStructs/GetScan`方法,用于结果集`struct`/`slice`映射转换:https://goframe.org/database/gdb/chaining
|
||||
- 新增`Safe`链式操作方法(默认非并发安全),用于链式安全控制:https://goframe.org/database/gdb/chaining
|
||||
- `Where`链式操作方法改进:
|
||||
- 方法支持任意的`string/map/slice/struct/*struct`类型;
|
||||
- 逻辑调整,当链式操作中存在多个`Where`方法调用时,自动转换为`And`条件;
|
||||
- 支持`slice`条件参数,常用在`SELECT IN`查询中,例如:`Where("uid IN(?)", g.Slice{1,2,3})`;
|
||||
- 支持在`map`类型条件参数的`key`中传递条件,例如:`Where(g.Map{"uid>?", uid})`;
|
||||
1. `gconv`及`gvalid`模块改进并去掉对私有`struct`方法属性的转换/校验;
|
||||
1. `gconv.Map`转换方法新增对`json tag`: `-`, `omitempty`的支持: https://goframe.org/util/gconv/map
|
||||
1. `gstr`模块新增 `ReplaceI/ReplaceIByArray/ReplaceIByMap`大小写非敏感替换方法;
|
||||
1. `gutil`模块增加`IsEmpty`方法,用于判断给定变量是否为空(整型0, 布尔false, slice/map长度为0, 其他为nil的情况,判断为空),并增加快捷方法`g.IsEmpty`;
|
||||
1. `gutil`模块增加`Export`方法,用于导出返回格式化打印的变量内容字符串,并增加快捷方法`g.Export`;
|
||||
1. `gspath`增加缓存及非缓存检索检索方法`Search`/`SearchWithCache`;
|
||||
1. `gjson`模块增加默认的`UseNumber`功能支持;
|
||||
1. `gmap`增加`SetIfNotExistFunc/SetIfNotExistFuncLock`方法;
|
||||
1. 迁移`greuseport`模块到新的仓库:https://github.com/gogf/greuseport
|
||||
1. 大量的单元测试完善;
|
||||
|
||||
## Bug Fix
|
||||
1. 修复`gqueue`模块的资源竞争问题;
|
||||
1. 修复`gconv.GTime`转换失败问题;
|
||||
1. 修复`gconv.String`在转换`int`参数时字节溢出问题;
|
||||
1. 修复`ghttp.Request`的`HTTP Basic Auth`校验问题;
|
||||
1. 修复`gxml`针对于非`UTF-8`编码内容转换的并发安全问题;
|
||||
1. 修复`gtime`部分`Format`(`G`&`j`)格式失效问题;
|
||||
1. 修复`gudp.Conn`对象的`RemoteAddr`获取客户端连接地址方法问题;
|
||||
1. 修复`gmap/gcache`模块的`GetOrSetFuncLock`方法,增加对回调方法返回值的`nil`判断,只有非nil返回值才会被保存;
|
||||
|
||||
|
||||
|
||||
# `v1.5.8` (2019-02-28)
|
||||
|
||||
## 新特性
|
||||
|
||||
43
TODO.MD
43
TODO.MD
@ -1,23 +1,16 @@
|
||||
# ON THE WAY
|
||||
1. 增加图形验证码支持,至少支持数字和英文字母;
|
||||
1. 增加热编译工具,提高开发环境的开发/测试效率(媲美PHP开发效率);
|
||||
1. 增加可选择性的orm tag特性,用以数据表记录与struct对象转换的键名属性映射;
|
||||
1. ghttp.Response增加输出内容后自动退出当前请求机制,不需要用户手动return,参考beego如何实现;
|
||||
1. Cookie&Session数据池化处理;
|
||||
1. ghttp.Client增加proxy特性;
|
||||
1. gtime增加对时区转换的封装,并简化失去转换时对类似+80500时区的支持;
|
||||
1. orm增加sqlite对Save方法的支持(去掉触发器语句);
|
||||
1. ghttp.Server增加Ip访问控制功能(DenyIps&AllowIps);
|
||||
1. ghttp路由功能增加分组路由特性;
|
||||
1. ghttp增加返回数据压缩机制;
|
||||
1. gview中的template标签失效问题;
|
||||
1. gfile文件stat信息使用gfsnotify进行缓存更新改进;
|
||||
1. ghttp.Server增加proxy功能特性,本地proxy和远程proxy,本地即将路由规则映射;远程即反向代理;
|
||||
1. gjson对大json数据的解析效率问题;
|
||||
1. ghttp增加route name特性,并同时支持backend和template(提供内置函数)引用,可以通过RedirectRoute方法给定route name和路由参数跳转到指定的路由地址上;
|
||||
1. ghttp.Client自动Close机制;
|
||||
1. gvalid校验支持当第一个规则失败后便不再校验后续的规则,最好做成链式操作;
|
||||
1. 检查ghttp.Server超时问题;
|
||||
1. gvalid增加支持对[]rune的长度校验(一个中文占3个字节);
|
||||
1. ghttp.Request增加对输入参数的自动HtmlEncode机制;
|
||||
1. 常量命名风格根据golint进行修改;
|
||||
@ -36,31 +29,20 @@
|
||||
- https://github.com/Masterminds/sprig
|
||||
1. gform参考 https://gohouse.github.io/gorose/dist/index.html 进行改进
|
||||
1. gtcp提供简便的包发送/接收方法(SendPkg/RecvPkg)以解决常见的TCP通信粘包问题,并完善文档(参考:https://www.cnblogs.com/kex1n/p/6502002.html);
|
||||
1. gfile对于文件的读写强行使用了gfpool,在某些场景下不合适,需要考虑剥离开,并为开发者提供单独的指针池文件操作特性;
|
||||
1. 路由增加不区分大小写得匹配方式;
|
||||
1. str_ireplace: http://php.net/manual/en/function.str-ireplace.php
|
||||
1. strpos/stripos/strrpos/strripos: http://php.net/manual/en/function.stripos.php
|
||||
1. 改进WebServer获取POST参数处理逻辑,当提交非form数据时,例如json数据,针对某些方法可以直接解析;
|
||||
1. WebServer增加可选择的路由覆盖配置,默认情况下不覆盖;
|
||||
1. gkafka这个包比较重,未来从框架中剥离出来;
|
||||
1. grpool性能压测结果变慢的问题;
|
||||
1. 增加jumplist的数据结构容器;
|
||||
1. DelayQueue/PriorityQueue;
|
||||
1. gconv针对struct的转换增加json tag支持,gconv.Map默认也支持json tag, 完善开发文档;
|
||||
1. 增加SO_REUSEPORT的支持;
|
||||
1. 权限管理模块;
|
||||
1. 从ghttp中剥离SESSION功能构成单独的模块gsession;
|
||||
1. 改进gproc进程间通信处理逻辑,提高稳定性,以应对进程间大批量的数据发送/接收;
|
||||
1. gdb的Data方法支持struct参数传入;
|
||||
1. gfcache依旧使用gcache作为缓存控制对象,不要使用gmap;
|
||||
1. 增加对ghttp路由注册的{.struct}/{.method}单元测试;
|
||||
1. 更新跨域请求CORS相关功能文档;
|
||||
1. ghttp的热重启的本地进程端口监听,在不使用该特性时默认关闭掉;
|
||||
1. gcfg包目前允许添加重复的目录路径,需要在SetPath/AddPath时判断重复性,不能添加重复的路径;
|
||||
1. gdb执行数据写入时,如果参数为struct/[]struct,自动映射与表字段对应关系,不再使用gconv标签标识;
|
||||
|
||||
|
||||
|
||||
1. gtcp增加对TLS加密通信的支持;
|
||||
1. 添加Save/Replace/BatchSave/BatchReplace方法对sqlite数据库的支持;
|
||||
1. 添加sqlite数据库的单元测试用例;
|
||||
1. gredis增加cluster支持;
|
||||
|
||||
# DONE
|
||||
1. gconv完善针对不同类型的判断,例如:尽量减少sprintf("%v", xxx)来执行string类型的转换;
|
||||
@ -119,4 +101,19 @@
|
||||
1. gform对于MySQL字段类型为datetime类型的时区问题分析;
|
||||
1. 改进证书打开失败时的WebServer错误提示,前置HOOK校验后关闭后续的HOOK逻辑执行;
|
||||
1. 目前WebServer的HOOK是按照优先级执行的,需要增加覆盖特性;
|
||||
|
||||
1. 更新跨域请求CORS相关功能文档;
|
||||
1. ghttp.Response增加输出内容后自动退出当前请求机制,不需要用户手动return,参考beego如何实现;
|
||||
1. gcfg包目前允许添加重复的目录路径,需要在SetPath/AddPath时判断重复性,不能添加重复的路径;
|
||||
1. gdb执行数据写入时,如果参数为struct/[]struct,自动映射与表字段对应关系,不再使用gconv标签标识;
|
||||
1. gdb的Data方法支持struct参数传入;
|
||||
1. gfcache依旧使用gcache作为缓存控制对象,不要使用gmap;
|
||||
1. 增加对ghttp路由注册的{.struct}/{.method}单元测试;
|
||||
1. gconv针对struct的转换增加json tag支持,gconv.Map默认也支持json tag, 完善开发文档;
|
||||
1. 增加SO_REUSEPORT的支持;
|
||||
1. gkafka这个包比较重,未来从框架中剥离出来;
|
||||
1. str_ireplace: http://php.net/manual/en/function.str-ireplace.php
|
||||
1. strpos/stripos/strrpos/strripos: http://php.net/manual/en/function.stripos.php
|
||||
1. gfile对于文件的读写强行使用了gfpool,在某些场景下不合适,需要考虑剥离开,并为开发者提供单独的指针池文件操作特性;
|
||||
1. ghttp.Client自动Close机制;
|
||||
1. ghttp路由功能增加分组路由特性;
|
||||
1. 增加可选择性的orm tag特性,用以数据表记录与struct对象转换的键名属性映射;
|
||||
@ -4,8 +4,6 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package garray provides kinds of concurrent-safe(alternative) arrays.
|
||||
//
|
||||
// 并发安全数组.
|
||||
// Package garray provides concurrent-safe/unsafe arrays.
|
||||
package garray
|
||||
|
||||
|
||||
@ -4,9 +4,9 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gchan provides graceful operations for channel.
|
||||
// Package gchan provides graceful channel for safe operations.
|
||||
//
|
||||
// 优雅的Channel操作.
|
||||
// It's safe to call Chan.Push/Close functions repeatedly.
|
||||
package gchan
|
||||
|
||||
import (
|
||||
@ -15,39 +15,48 @@ import (
|
||||
)
|
||||
|
||||
type Chan struct {
|
||||
list chan interface{}
|
||||
closed *gtype.Bool
|
||||
channel chan interface{}
|
||||
closed *gtype.Bool
|
||||
}
|
||||
|
||||
// New creates a graceful channel with given limit.
|
||||
func New(limit int) *Chan {
|
||||
return &Chan {
|
||||
list : make(chan interface{}, limit),
|
||||
closed : gtype.NewBool(),
|
||||
channel : make(chan interface{}, limit),
|
||||
closed : gtype.NewBool(),
|
||||
}
|
||||
}
|
||||
|
||||
// 将数据压入队列
|
||||
func (q *Chan) Push(v interface{}) error {
|
||||
if q.closed.Val() {
|
||||
// Push pushes <value> to channel.
|
||||
// It is safe to be called repeatedly.
|
||||
func (c *Chan) Push(value interface{}) error {
|
||||
if c.closed.Val() {
|
||||
return errors.New("closed")
|
||||
}
|
||||
q.list <- v
|
||||
c.channel <- value
|
||||
return nil
|
||||
}
|
||||
|
||||
// 先进先出地从队列取出一项数据,当没有数据可获取时,阻塞等待
|
||||
func (q *Chan) Pop() interface{} {
|
||||
return <- q.list
|
||||
// Pop pops value from channel.
|
||||
// If there's no value in channel, it would block to wait.
|
||||
func (c *Chan) Pop() interface{} {
|
||||
return <- c.channel
|
||||
}
|
||||
|
||||
// 关闭队列(通知所有通过Pop阻塞的协程退出)
|
||||
func (q *Chan) Close() {
|
||||
if !q.closed.Set(true) {
|
||||
close(q.list)
|
||||
// Close closes the channel.
|
||||
// It is safe to be called repeatedly.
|
||||
func (c *Chan) Close() {
|
||||
if !c.closed.Set(true) {
|
||||
close(c.channel)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前队列大小
|
||||
func (q *Chan) Size() int {
|
||||
return len(q.list)
|
||||
// See Len.
|
||||
func (c *Chan) Size() int {
|
||||
return c.Len()
|
||||
}
|
||||
|
||||
// Len returns the length of the channel.
|
||||
func (c *Chan) Len() int {
|
||||
return len(c.channel)
|
||||
}
|
||||
@ -5,9 +5,7 @@
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
//
|
||||
|
||||
// Package glist provides a concurrent-safe(alternative) doubly linked list.
|
||||
//
|
||||
// 并发安全双向链表.
|
||||
// Package glist provides a concurrent-safe/unsafe doubly linked list.
|
||||
package glist
|
||||
|
||||
import (
|
||||
@ -15,14 +13,14 @@ import (
|
||||
"github.com/gogf/gf/g/internal/rwmutex"
|
||||
)
|
||||
|
||||
// 变长双向链表
|
||||
type List struct {
|
||||
mu *rwmutex.RWMutex
|
||||
list *list.List
|
||||
}
|
||||
|
||||
type Element = list.Element
|
||||
type (
|
||||
List struct {
|
||||
mu *rwmutex.RWMutex
|
||||
list *list.List
|
||||
}
|
||||
|
||||
Element = list.Element
|
||||
)
|
||||
|
||||
// 获得一个变长链表指针
|
||||
func New(unsafe...bool) *List {
|
||||
|
||||
@ -4,46 +4,34 @@
|
||||
// If a copy of the MIT was not distributed with gm file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gmap provides kinds of concurrent-safe(alternative) maps.
|
||||
//
|
||||
// 并发安全MAP.
|
||||
// Package gmap provides concurrent-safe/unsafe maps.
|
||||
package gmap
|
||||
|
||||
import "github.com/gogf/gf/g/internal/rwmutex"
|
||||
|
||||
// 注意:
|
||||
// 1、这个Map是所有并发安全Map中效率最低的,如果对效率要求比较高的场合,请合理选择对应数据类型的Map;
|
||||
// 2、这个Map的优点是使用简便,由于键值都是interface{}类型,因此对键值的数据类型要求不高;
|
||||
// 3、底层实现比较类似于sync.Map;
|
||||
type Map struct {
|
||||
mu *rwmutex.RWMutex
|
||||
m map[interface{}]interface{}
|
||||
}
|
||||
|
||||
// Create an empty hash map.
|
||||
// New returns an empty hash map.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe in default.
|
||||
//
|
||||
// 创建一个空的哈希表,参数unsafe用于指定是否用于非并发安全场景,默认为false,表示并发安全。
|
||||
func New(unsafe...bool) *Map {
|
||||
// which is false in default, means concurrent-safe.
|
||||
func New(unsafe ...bool) *Map {
|
||||
return NewMap(unsafe...)
|
||||
}
|
||||
|
||||
// See New.
|
||||
//
|
||||
// 同New方法。
|
||||
func NewMap(unsafe...bool) *Map {
|
||||
// Alias of New. See New.
|
||||
func NewMap(unsafe ...bool) *Map {
|
||||
return &Map{
|
||||
m : make(map[interface{}]interface{}),
|
||||
mu : rwmutex.New(unsafe...),
|
||||
}
|
||||
}
|
||||
|
||||
// Create a hash map from given map.
|
||||
// Be aware that, the param map is a type of pointer,
|
||||
// NewFrom returns a hash map from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
//
|
||||
// 基于给定的map变量创建哈希表对象,注意由于map是指针类型,外部对map有操作时会有并发安全问题。
|
||||
func NewFrom(m map[interface{}]interface{}, unsafe...bool) *Map {
|
||||
return &Map{
|
||||
m : m,
|
||||
@ -51,12 +39,12 @@ func NewFrom(m map[interface{}]interface{}, unsafe...bool) *Map {
|
||||
}
|
||||
}
|
||||
|
||||
// Create a hash map from given arrays.
|
||||
// NewFromArray returns a hash map from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as the corresponding values.
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// 基于给定的数组变量创建哈希表对象,keys作为键名, values作为键值。
|
||||
// 当keys数组大小比values数组大时,多余的键名将会使用对应类型默认的键值。
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewFromArray(keys []interface{}, values []interface{}, unsafe...bool) *Map {
|
||||
m := make(map[interface{}]interface{})
|
||||
l := len(values)
|
||||
@ -73,10 +61,8 @@ func NewFromArray(keys []interface{}, values []interface{}, unsafe...bool) *Map
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate the hash map with custom callback function <f>.
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
//
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
func (gm *Map) Iterator(f func (k interface{}, v interface{}) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -87,17 +73,12 @@ func (gm *Map) Iterator(f func (k interface{}, v interface{}) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// Clone current hash map with copy of underlying data,
|
||||
// return a new hash map.
|
||||
//
|
||||
// 哈希表克隆.
|
||||
func (gm *Map) Clone() *Map {
|
||||
return NewFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *Map) Clone(unsafe ...bool) *Map {
|
||||
return NewFrom(gm.Map(), unsafe ...)
|
||||
}
|
||||
|
||||
// Returns copy of the data of the hash map.
|
||||
//
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *Map) Map() map[interface{}]interface{} {
|
||||
m := make(map[interface{}]interface{})
|
||||
gm.mu.RLock()
|
||||
@ -108,18 +89,14 @@ func (gm *Map) Map() map[interface{}]interface{} {
|
||||
return m
|
||||
}
|
||||
|
||||
// Set key-value to the hash map.
|
||||
//
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *Map) Set(key interface{}, val interface{}) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// Batch set key-values to the hash map.
|
||||
//
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *Map) BatchSet(m map[interface{}]interface{}) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -128,9 +105,7 @@ func (gm *Map) BatchSet(m map[interface{}]interface{}) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// Get value by key.
|
||||
//
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *Map) Get(key interface{}) interface{} {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -138,8 +113,15 @@ func (gm *Map) Get(key interface{}) interface{} {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// When setting value, if <value> is type of <func() interface {}>,
|
||||
// it will be executed with mutex.Lock of the hash map,
|
||||
// and its return value will be set to the map with <key>.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *Map) doSetWithLockCheck(key interface{}, value interface{}) interface{} {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -153,9 +135,8 @@ func (gm *Map) doSetWithLockCheck(key interface{}, value interface{}) interface{
|
||||
return value
|
||||
}
|
||||
|
||||
// Get the value by key, or set it with given key-value if not exist.
|
||||
//
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *Map) GetOrSet(key interface{}, value interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, value)
|
||||
@ -164,9 +145,9 @@ func (gm *Map) GetOrSet(key interface{}, value interface{}) interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// Get the value by key, or set the it with return of callback function <f> if not exist.
|
||||
//
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
func (gm *Map) GetOrSetFunc(key interface{}, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f())
|
||||
@ -175,10 +156,12 @@ func (gm *Map) GetOrSetFunc(key interface{}, f func() interface{}) interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// Get the value by key, or set the it with return of callback function <f> if not exist.
|
||||
// The difference with GetOrSetFunc is, it locks in executing callback function <f>.
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
//
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *Map) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f)
|
||||
@ -187,9 +170,8 @@ func (gm *Map) GetOrSetFuncLock(key interface{}, f func() interface{}) interface
|
||||
}
|
||||
}
|
||||
|
||||
// Set key-value if the key does not exist, then return true; or else return false.
|
||||
//
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *Map) SetIfNotExist(key interface{}, value interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -198,9 +180,30 @@ func (gm *Map) SetIfNotExist(key interface{}, value interface{}) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Batch remove by keys.
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *Map) SetIfNotExistFunc(key interface{}, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *Map) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *Map) BatchRemove(keys []interface{}) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -209,9 +212,7 @@ func (gm *Map) BatchRemove(keys []interface{}) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// Remove by given key.
|
||||
//
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *Map) Remove(key interface{}) interface{} {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -222,9 +223,7 @@ func (gm *Map) Remove(key interface{}) interface{} {
|
||||
return val
|
||||
}
|
||||
|
||||
// Return all the keys of hash map as a slice.
|
||||
//
|
||||
// 返回键列表.
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *Map) Keys() []interface{} {
|
||||
gm.mu.RLock()
|
||||
keys := make([]interface{}, 0)
|
||||
@ -235,9 +234,7 @@ func (gm *Map) Keys() []interface{} {
|
||||
return keys
|
||||
}
|
||||
|
||||
// Return all the values of hash map as a slice.
|
||||
//
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *Map) Values() []interface{} {
|
||||
gm.mu.RLock()
|
||||
vals := make([]interface{}, 0)
|
||||
@ -248,9 +245,8 @@ func (gm *Map) Values() []interface{} {
|
||||
return vals
|
||||
}
|
||||
|
||||
// Check whether a key exist.
|
||||
//
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *Map) Contains(key interface{}) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -258,9 +254,7 @@ func (gm *Map) Contains(key interface{}) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// Get the size of hash map.
|
||||
//
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *Map) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -268,9 +262,8 @@ func (gm *Map) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// Check whether the hash map is empty.
|
||||
//
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *Map) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -278,36 +271,28 @@ func (gm *Map) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// Clear the hash map, it will remake a new underlying map data map.
|
||||
//
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *Map) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[interface{}]interface{})
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// Lock writing with given callback <f>.
|
||||
//
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *Map) LockFunc(f func(m map[interface{}]interface{})) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// Lock reading with given callback <f>.
|
||||
//
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *Map) RLockFunc(f func(m map[interface{}]interface{})) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// Exchange key-value in the hash map, it will change key-value to value-key.
|
||||
//
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *Map) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -318,17 +303,16 @@ func (gm *Map) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// Merge two hash maps.
|
||||
//
|
||||
// 合并两个Map.
|
||||
func (gm *Map) Merge(m *Map) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *Map) Merge(other *Map) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,9 @@ type IntBoolMap struct {
|
||||
mu *rwmutex.RWMutex
|
||||
}
|
||||
|
||||
// NewIntBoolMap returns an empty IntBoolMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewIntBoolMap(unsafe...bool) *IntBoolMap {
|
||||
return &IntBoolMap{
|
||||
m : make(map[int]bool),
|
||||
@ -23,6 +26,9 @@ func NewIntBoolMap(unsafe...bool) *IntBoolMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntBoolMapFrom returns an IntBoolMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewIntBoolMapFrom(m map[int]bool, unsafe...bool) *IntBoolMap {
|
||||
return &IntBoolMap{
|
||||
m : m,
|
||||
@ -30,6 +36,12 @@ func NewIntBoolMapFrom(m map[int]bool, unsafe...bool) *IntBoolMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntBoolMapFromArray returns an IntBoolMap from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewIntBoolMapFromArray(keys []int, values []bool, unsafe...bool) *IntBoolMap {
|
||||
m := make(map[int]bool)
|
||||
l := len(values)
|
||||
@ -46,12 +58,12 @@ func NewIntBoolMapFromArray(keys []int, values []bool, unsafe...bool) *IntBoolMa
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *IntBoolMap) Clone() *IntBoolMap {
|
||||
return NewIntBoolMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *IntBoolMap) Map() map[int]bool {
|
||||
m := make(map[int]bool)
|
||||
gm.mu.RLock()
|
||||
@ -62,7 +74,8 @@ func (gm *IntBoolMap) Map() map[int]bool {
|
||||
return m
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *IntBoolMap) Iterator(f func (k int, v bool) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -73,14 +86,14 @@ func (gm *IntBoolMap) Iterator(f func (k int, v bool) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *IntBoolMap) Set(key int, val bool) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *IntBoolMap) BatchSet(m map[int]bool) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -89,7 +102,7 @@ func (gm *IntBoolMap) BatchSet(m map[int]bool) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *IntBoolMap) Get(key int) bool {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -97,8 +110,11 @@ func (gm *IntBoolMap) Get(key int) bool {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *IntBoolMap) doSetWithLockCheck(key int, value bool) bool {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -110,7 +126,8 @@ func (gm *IntBoolMap) doSetWithLockCheck(key int, value bool) bool {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *IntBoolMap) GetOrSet(key int, value bool) bool {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -122,7 +139,8 @@ func (gm *IntBoolMap) GetOrSet(key int, value bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
func (gm *IntBoolMap) GetOrSetFunc(key int, f func() bool) bool {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -134,7 +152,11 @@ func (gm *IntBoolMap) GetOrSetFunc(key int, f func() bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *IntBoolMap) GetOrSetFuncLock(key int, f func() bool) bool {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -143,10 +165,9 @@ func (gm *IntBoolMap) GetOrSetFuncLock(key int, f func() bool) bool {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
val = f()
|
||||
gm.m[key] = val
|
||||
return val
|
||||
} else {
|
||||
@ -154,7 +175,8 @@ func (gm *IntBoolMap) GetOrSetFuncLock(key int, f func() bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntBoolMap) SetIfNotExist(key int, value bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -163,7 +185,34 @@ func (gm *IntBoolMap) SetIfNotExist(key int, value bool) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntBoolMap) SetIfNotExistFunc(key int, f func() bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *IntBoolMap) SetIfNotExistFuncLock(key int, f func() bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *IntBoolMap) BatchRemove(keys []int) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -172,7 +221,7 @@ func (gm *IntBoolMap) BatchRemove(keys []int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *IntBoolMap) Remove(key int) bool {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -183,7 +232,7 @@ func (gm *IntBoolMap) Remove(key int) bool {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *IntBoolMap) Keys() []int {
|
||||
gm.mu.RLock()
|
||||
keys := make([]int, 0)
|
||||
@ -194,18 +243,8 @@ func (gm *IntBoolMap) Keys() []int {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
//func (gm *IntBoolMap) Values() []bool {
|
||||
// gm.mu.RLock()
|
||||
// vals := make([]bool, 0)
|
||||
// for _, val := range gm.m {
|
||||
// vals = append(vals, val)
|
||||
// }
|
||||
// gm.mu.RUnlock()
|
||||
// return vals
|
||||
//}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *IntBoolMap) Contains(key int) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -213,7 +252,7 @@ func (gm *IntBoolMap) Contains(key int) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *IntBoolMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -221,7 +260,8 @@ func (gm *IntBoolMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *IntBoolMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -229,36 +269,37 @@ func (gm *IntBoolMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *IntBoolMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[int]bool)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *IntBoolMap) LockFunc(f func(m map[int]bool)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *IntBoolMap) RLockFunc(f func(m map[int]bool)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *IntBoolMap) Merge(m *IntBoolMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *IntBoolMap) Merge(other *IntBoolMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,9 @@ type IntIntMap struct {
|
||||
m map[int]int
|
||||
}
|
||||
|
||||
// NewIntIntMap returns an empty IntIntMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewIntIntMap(unsafe...bool) *IntIntMap {
|
||||
return &IntIntMap{
|
||||
m : make(map[int]int),
|
||||
@ -23,6 +26,9 @@ func NewIntIntMap(unsafe...bool) *IntIntMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntIntMapFrom returns an IntIntMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewIntIntMapFrom(m map[int]int, unsafe...bool) *IntIntMap {
|
||||
return &IntIntMap{
|
||||
m : m,
|
||||
@ -30,6 +36,12 @@ func NewIntIntMapFrom(m map[int]int, unsafe...bool) *IntIntMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntIntMapFromArray returns an IntIntMap object from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewIntIntMapFromArray(keys []int, values []int, unsafe...bool) *IntIntMap {
|
||||
m := make(map[int]int)
|
||||
l := len(values)
|
||||
@ -46,7 +58,8 @@ func NewIntIntMapFromArray(keys []int, values []int, unsafe...bool) *IntIntMap {
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *IntIntMap) Iterator(f func (k int, v int) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -57,12 +70,12 @@ func (gm *IntIntMap) Iterator(f func (k int, v int) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *IntIntMap) Clone() *IntIntMap {
|
||||
return NewIntIntMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *IntIntMap) Map() map[int]int {
|
||||
m := make(map[int]int)
|
||||
gm.mu.RLock()
|
||||
@ -73,14 +86,14 @@ func (gm *IntIntMap) Map() map[int]int {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *IntIntMap) Set(key int, val int) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *IntIntMap) BatchSet(m map[int]int) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -89,7 +102,7 @@ func (gm *IntIntMap) BatchSet(m map[int]int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *IntIntMap) Get(key int) (int) {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -97,8 +110,11 @@ func (gm *IntIntMap) Get(key int) (int) {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *IntIntMap) doSetWithLockCheck(key int, value int) int {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -110,7 +126,8 @@ func (gm *IntIntMap) doSetWithLockCheck(key int, value int) int {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *IntIntMap) GetOrSet(key int, value int) int {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -122,7 +139,8 @@ func (gm *IntIntMap) GetOrSet(key int, value int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
func (gm *IntIntMap) GetOrSetFunc(key int, f func() int) int {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -134,7 +152,11 @@ func (gm *IntIntMap) GetOrSetFunc(key int, f func() int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *IntIntMap) GetOrSetFuncLock(key int, f func() int) int {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -143,7 +165,6 @@ func (gm *IntIntMap) GetOrSetFuncLock(key int, f func() int) int {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
@ -154,7 +175,8 @@ func (gm *IntIntMap) GetOrSetFuncLock(key int, f func() int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntIntMap) SetIfNotExist(key int, value int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -163,7 +185,34 @@ func (gm *IntIntMap) SetIfNotExist(key int, value int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntIntMap) SetIfNotExistFunc(key int, f func() int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *IntIntMap) SetIfNotExistFuncLock(key int, f func() int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *IntIntMap) BatchRemove(keys []int) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -172,7 +221,7 @@ func (gm *IntIntMap) BatchRemove(keys []int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *IntIntMap) Remove(key int) int {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -183,7 +232,7 @@ func (gm *IntIntMap) Remove(key int) int {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *IntIntMap) Keys() []int {
|
||||
gm.mu.RLock()
|
||||
keys := make([]int, 0)
|
||||
@ -194,7 +243,7 @@ func (gm *IntIntMap) Keys() []int {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *IntIntMap) Values() []int {
|
||||
gm.mu.RLock()
|
||||
vals := make([]int, 0)
|
||||
@ -205,7 +254,8 @@ func (gm *IntIntMap) Values() []int {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *IntIntMap) Contains(key int) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -213,7 +263,7 @@ func (gm *IntIntMap) Contains(key int) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *IntIntMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -221,7 +271,8 @@ func (gm *IntIntMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *IntIntMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -229,28 +280,28 @@ func (gm *IntIntMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *IntIntMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[int]int)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *IntIntMap) LockFunc(f func(m map[int]int)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *IntIntMap) RLockFunc(f func(m map[int]int)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *IntIntMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -261,15 +312,16 @@ func (gm *IntIntMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *IntIntMap) Merge(m *IntIntMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *IntIntMap) Merge(other *IntIntMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,6 +17,9 @@ type IntInterfaceMap struct {
|
||||
m map[int]interface{}
|
||||
}
|
||||
|
||||
// NewIntInterfaceMap returns an empty IntInterfaceMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewIntInterfaceMap(unsafe...bool) *IntInterfaceMap {
|
||||
return &IntInterfaceMap{
|
||||
m : make(map[int]interface{}),
|
||||
@ -24,6 +27,9 @@ func NewIntInterfaceMap(unsafe...bool) *IntInterfaceMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntInterfaceMapFrom returns an IntInterfaceMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewIntInterfaceMapFrom(m map[int]interface{}, unsafe...bool) *IntInterfaceMap {
|
||||
return &IntInterfaceMap{
|
||||
m : m,
|
||||
@ -31,6 +37,12 @@ func NewIntInterfaceMapFrom(m map[int]interface{}, unsafe...bool) *IntInterfaceM
|
||||
}
|
||||
}
|
||||
|
||||
// NewFromArray returns a hash map from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewIntInterfaceMapFromArray(keys []int, values []interface{}, unsafe...bool) *IntInterfaceMap {
|
||||
m := make(map[int]interface{})
|
||||
l := len(values)
|
||||
@ -47,7 +59,8 @@ func NewIntInterfaceMapFromArray(keys []int, values []interface{}, unsafe...bool
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *IntInterfaceMap) Iterator(f func (k int, v interface{}) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -58,12 +71,12 @@ func (gm *IntInterfaceMap) Iterator(f func (k int, v interface{}) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *IntInterfaceMap) Clone() *IntInterfaceMap {
|
||||
return NewIntInterfaceMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *IntInterfaceMap) Map() map[int]interface{} {
|
||||
m := make(map[int]interface{})
|
||||
gm.mu.RLock()
|
||||
@ -74,14 +87,14 @@ func (gm *IntInterfaceMap) Map() map[int]interface{} {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *IntInterfaceMap) Set(key int, val interface{}) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *IntInterfaceMap) BatchSet(m map[int]interface{}) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -90,7 +103,7 @@ func (gm *IntInterfaceMap) BatchSet(m map[int]interface{}) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *IntInterfaceMap) Get(key int) (interface{}) {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -98,8 +111,16 @@ func (gm *IntInterfaceMap) Get(key int) (interface{}) {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// When setting value, if <value> is type of <func() interface {}>,
|
||||
// it will be executed with mutex.Lock of the hash map,
|
||||
// and its return value will be set to the map with <key>.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *IntInterfaceMap) doSetWithLockCheck(key int, value interface{}) interface{} {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -109,11 +130,14 @@ func (gm *IntInterfaceMap) doSetWithLockCheck(key int, value interface{}) interf
|
||||
if f, ok := value.(func() interface {}); ok {
|
||||
value = f()
|
||||
}
|
||||
gm.m[key] = value
|
||||
if value != nil {
|
||||
gm.m[key] = value
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *IntInterfaceMap) GetOrSet(key int, value interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, value)
|
||||
@ -122,7 +146,8 @@ func (gm *IntInterfaceMap) GetOrSet(key int, value interface{}) interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
func (gm *IntInterfaceMap) GetOrSetFunc(key int, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f())
|
||||
@ -131,7 +156,11 @@ func (gm *IntInterfaceMap) GetOrSetFunc(key int, f func() interface{}) interface
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *IntInterfaceMap) GetOrSetFuncLock(key int, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f)
|
||||
@ -140,7 +169,8 @@ func (gm *IntInterfaceMap) GetOrSetFuncLock(key int, f func() interface{}) inter
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntInterfaceMap) SetIfNotExist(key int, value interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -149,7 +179,31 @@ func (gm *IntInterfaceMap) SetIfNotExist(key int, value interface{}) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntInterfaceMap) SetIfNotExistFunc(key int, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *IntInterfaceMap) SetIfNotExistFuncLock(key int, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *IntInterfaceMap) BatchRemove(keys []int) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -158,7 +212,7 @@ func (gm *IntInterfaceMap) BatchRemove(keys []int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *IntInterfaceMap) Remove(key int) interface{} {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -169,7 +223,7 @@ func (gm *IntInterfaceMap) Remove(key int) interface{} {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *IntInterfaceMap) Keys() []int {
|
||||
gm.mu.RLock()
|
||||
keys := make([]int, 0)
|
||||
@ -180,7 +234,7 @@ func (gm *IntInterfaceMap) Keys() []int {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *IntInterfaceMap) Values() []interface{} {
|
||||
gm.mu.RLock()
|
||||
vals := make([]interface{}, 0)
|
||||
@ -191,7 +245,8 @@ func (gm *IntInterfaceMap) Values() []interface{} {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *IntInterfaceMap) Contains(key int) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -199,7 +254,7 @@ func (gm *IntInterfaceMap) Contains(key int) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *IntInterfaceMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -207,7 +262,8 @@ func (gm *IntInterfaceMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *IntInterfaceMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -215,28 +271,28 @@ func (gm *IntInterfaceMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *IntInterfaceMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[int]interface{})
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *IntInterfaceMap) LockFunc(f func(m map[int]interface{})) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *IntInterfaceMap) RLockFunc(f func(m map[int]interface{})) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *IntInterfaceMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -247,15 +303,16 @@ func (gm *IntInterfaceMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *IntInterfaceMap) Merge(m *IntInterfaceMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *IntInterfaceMap) Merge(other *IntInterfaceMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,9 @@ type IntStringMap struct {
|
||||
m map[int]string
|
||||
}
|
||||
|
||||
// NewIntStringMap returns an empty IntStringMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewIntStringMap(unsafe...bool) *IntStringMap {
|
||||
return &IntStringMap{
|
||||
m : make(map[int]string),
|
||||
@ -24,6 +27,9 @@ func NewIntStringMap(unsafe...bool) *IntStringMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntStringMapFrom returns an IntStringMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewIntStringMapFrom(m map[int]string, unsafe...bool) *IntStringMap {
|
||||
return &IntStringMap{
|
||||
m : m,
|
||||
@ -31,6 +37,12 @@ func NewIntStringMapFrom(m map[int]string, unsafe...bool) *IntStringMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewIntStringMapFromArray returns an IntStringMap object from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewIntStringMapFromArray(keys []int, values []string, unsafe...bool) *IntStringMap {
|
||||
m := make(map[int]string)
|
||||
l := len(values)
|
||||
@ -47,7 +59,8 @@ func NewIntStringMapFromArray(keys []int, values []string, unsafe...bool) *IntSt
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *IntStringMap) Iterator(f func (k int, v string) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -58,12 +71,12 @@ func (gm *IntStringMap) Iterator(f func (k int, v string) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *IntStringMap) Clone() *IntStringMap {
|
||||
return NewIntStringMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *IntStringMap) Map() map[int]string {
|
||||
m := make(map[int]string)
|
||||
gm.mu.RLock()
|
||||
@ -74,14 +87,14 @@ func (gm *IntStringMap) Map() map[int]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *IntStringMap) Set(key int, val string) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *IntStringMap) BatchSet(m map[int]string) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -90,7 +103,7 @@ func (gm *IntStringMap) BatchSet(m map[int]string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *IntStringMap) Get(key int) string {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -98,8 +111,11 @@ func (gm *IntStringMap) Get(key int) string {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *IntStringMap) doSetWithLockCheck(key int, value string) string {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -111,7 +127,8 @@ func (gm *IntStringMap) doSetWithLockCheck(key int, value string) string {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *IntStringMap) GetOrSet(key int, value string) string {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -123,7 +140,8 @@ func (gm *IntStringMap) GetOrSet(key int, value string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
func (gm *IntStringMap) GetOrSetFunc(key int, f func() string) string {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -135,7 +153,11 @@ func (gm *IntStringMap) GetOrSetFunc(key int, f func() string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *IntStringMap) GetOrSetFuncLock(key int, f func() string) string {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -144,10 +166,9 @@ func (gm *IntStringMap) GetOrSetFuncLock(key int, f func() string) string {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
val = f()
|
||||
gm.m[key] = val
|
||||
return val
|
||||
} else {
|
||||
@ -155,7 +176,8 @@ func (gm *IntStringMap) GetOrSetFuncLock(key int, f func() string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntStringMap) SetIfNotExist(key int, value string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -164,7 +186,35 @@ func (gm *IntStringMap) SetIfNotExist(key int, value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *IntStringMap) SetIfNotExistFunc(key int, f func() string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *IntStringMap) SetIfNotExistFuncLock(key int, f func() string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *IntStringMap) BatchRemove(keys []int) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -173,7 +223,7 @@ func (gm *IntStringMap) BatchRemove(keys []int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *IntStringMap) Remove(key int) string {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -184,7 +234,7 @@ func (gm *IntStringMap) Remove(key int) string {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *IntStringMap) Keys() []int {
|
||||
gm.mu.RLock()
|
||||
keys := make([]int, 0)
|
||||
@ -195,7 +245,7 @@ func (gm *IntStringMap) Keys() []int {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *IntStringMap) Values() []string {
|
||||
gm.mu.RLock()
|
||||
vals := make([]string, 0)
|
||||
@ -206,7 +256,8 @@ func (gm *IntStringMap) Values() []string {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *IntStringMap) Contains(key int) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -214,7 +265,7 @@ func (gm *IntStringMap) Contains(key int) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *IntStringMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -222,7 +273,8 @@ func (gm *IntStringMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *IntStringMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -230,28 +282,28 @@ func (gm *IntStringMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *IntStringMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[int]string)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *IntStringMap) LockFunc(f func(m map[int]string)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *IntStringMap) RLockFunc(f func(m map[int]string)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *IntStringMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -262,15 +314,16 @@ func (gm *IntStringMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *IntStringMap) Merge(m *IntStringMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *IntStringMap) Merge(other *IntStringMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,9 @@ type StringBoolMap struct {
|
||||
m map[string]bool
|
||||
}
|
||||
|
||||
// NewStringBoolMap returns an empty StringBoolMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewStringBoolMap(unsafe...bool) *StringBoolMap {
|
||||
return &StringBoolMap{
|
||||
m : make(map[string]bool),
|
||||
@ -23,6 +26,9 @@ func NewStringBoolMap(unsafe...bool) *StringBoolMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringBoolMapFrom returns an StringBoolMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewStringBoolMapFrom(m map[string]bool, unsafe...bool) *StringBoolMap {
|
||||
return &StringBoolMap{
|
||||
m : m,
|
||||
@ -30,6 +36,12 @@ func NewStringBoolMapFrom(m map[string]bool, unsafe...bool) *StringBoolMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewFromArray returns a hash map from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewStringBoolMapFromArray(keys []string, values []bool, unsafe...bool) *StringBoolMap {
|
||||
m := make(map[string]bool)
|
||||
l := len(values)
|
||||
@ -46,7 +58,8 @@ func NewStringBoolMapFromArray(keys []string, values []bool, unsafe...bool) *Str
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *StringBoolMap) Iterator(f func (k string, v bool) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -57,12 +70,12 @@ func (gm *StringBoolMap) Iterator(f func (k string, v bool) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *StringBoolMap) Clone() *StringBoolMap {
|
||||
return NewStringBoolMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *StringBoolMap) Map() map[string]bool {
|
||||
m := make(map[string]bool)
|
||||
gm.mu.RLock()
|
||||
@ -73,14 +86,14 @@ func (gm *StringBoolMap) Map() map[string]bool {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *StringBoolMap) Set(key string, val bool) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *StringBoolMap) BatchSet(m map[string]bool) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -89,7 +102,7 @@ func (gm *StringBoolMap) BatchSet(m map[string]bool) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *StringBoolMap) Get(key string) bool {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -97,8 +110,11 @@ func (gm *StringBoolMap) Get(key string) bool {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *StringBoolMap) doSetWithLockCheck(key string, value bool) bool {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -110,7 +126,8 @@ func (gm *StringBoolMap) doSetWithLockCheck(key string, value bool) bool {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *StringBoolMap) GetOrSet(key string, value bool) bool {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -122,7 +139,9 @@ func (gm *StringBoolMap) GetOrSet(key string, value bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
func (gm *StringBoolMap) GetOrSetFunc(key string, f func() bool) bool {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -134,7 +153,12 @@ func (gm *StringBoolMap) GetOrSetFunc(key string, f func() bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *StringBoolMap) GetOrSetFuncLock(key string, f func() bool) bool {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -143,7 +167,6 @@ func (gm *StringBoolMap) GetOrSetFuncLock(key string, f func() bool) bool {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
@ -154,7 +177,9 @@ func (gm *StringBoolMap) GetOrSetFuncLock(key string, f func() bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringBoolMap) SetIfNotExist(key string, value bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -163,7 +188,34 @@ func (gm *StringBoolMap) SetIfNotExist(key string, value bool) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringBoolMap) SetIfNotExistFunc(key string, f func() bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *StringBoolMap) SetIfNotExistFuncLock(key string, f func() bool) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *StringBoolMap) BatchRemove(keys []string) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -172,7 +224,7 @@ func (gm *StringBoolMap) BatchRemove(keys []string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *StringBoolMap) Remove(key string) bool {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -183,7 +235,7 @@ func (gm *StringBoolMap) Remove(key string) bool {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *StringBoolMap) Keys() []string {
|
||||
gm.mu.RLock()
|
||||
keys := make([]string, 0)
|
||||
@ -194,18 +246,8 @@ func (gm *StringBoolMap) Keys() []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
//func (gm *StringBoolMap) Values() []bool {
|
||||
// gm.mu.RLock()
|
||||
// vals := make([]bool, 0)
|
||||
// for _, val := range gm.m {
|
||||
// vals = append(vals, val)
|
||||
// }
|
||||
// gm.mu.RUnlock()
|
||||
// return vals
|
||||
//}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *StringBoolMap) Contains(key string) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -213,7 +255,7 @@ func (gm *StringBoolMap) Contains(key string) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *StringBoolMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -221,7 +263,8 @@ func (gm *StringBoolMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *StringBoolMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -229,36 +272,37 @@ func (gm *StringBoolMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *StringBoolMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[string]bool)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *StringBoolMap) LockFunc(f func(m map[string]bool)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *StringBoolMap) RLockFunc(f func(m map[string]bool)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *StringBoolMap) Merge(m *StringBoolMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *StringBoolMap) Merge(other *StringBoolMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,9 @@ type StringIntMap struct {
|
||||
m map[string]int
|
||||
}
|
||||
|
||||
// NewStringIntMap returns an empty StringIntMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewStringIntMap(unsafe...bool) *StringIntMap {
|
||||
return &StringIntMap{
|
||||
m : make(map[string]int),
|
||||
@ -24,6 +27,9 @@ func NewStringIntMap(unsafe...bool) *StringIntMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringIntMapFrom returns an StringIntMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewStringIntMapFrom(m map[string]int, unsafe...bool) *StringIntMap {
|
||||
return &StringIntMap{
|
||||
m : m,
|
||||
@ -31,6 +37,12 @@ func NewStringIntMapFrom(m map[string]int, unsafe...bool) *StringIntMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringIntMapFromArray returns an StringIntMap object from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewStringIntMapFromArray(keys []string, values []int, unsafe...bool) *StringIntMap {
|
||||
m := make(map[string]int)
|
||||
l := len(values)
|
||||
@ -47,7 +59,8 @@ func NewStringIntMapFromArray(keys []string, values []int, unsafe...bool) *Strin
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *StringIntMap) Iterator(f func (k string, v int) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -58,12 +71,12 @@ func (gm *StringIntMap) Iterator(f func (k string, v int) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *StringIntMap) Clone() *StringIntMap {
|
||||
return NewStringIntMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *StringIntMap) Map() map[string]int {
|
||||
m := make(map[string]int)
|
||||
gm.mu.RLock()
|
||||
@ -74,14 +87,14 @@ func (gm *StringIntMap) Map() map[string]int {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *StringIntMap) Set(key string, val int) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *StringIntMap) BatchSet(m map[string]int) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -90,7 +103,7 @@ func (gm *StringIntMap) BatchSet(m map[string]int) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *StringIntMap) Get(key string) int {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -98,8 +111,11 @@ func (gm *StringIntMap) Get(key string) int {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *StringIntMap) doSetWithLockCheck(key string, value int) int {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -111,7 +127,8 @@ func (gm *StringIntMap) doSetWithLockCheck(key string, value int) int {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *StringIntMap) GetOrSet(key string, value int) int {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -123,7 +140,9 @@ func (gm *StringIntMap) GetOrSet(key string, value int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
func (gm *StringIntMap) GetOrSetFunc(key string, f func() int) int {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -135,7 +154,12 @@ func (gm *StringIntMap) GetOrSetFunc(key string, f func() int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *StringIntMap) GetOrSetFuncLock(key string, f func() int) int {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -144,10 +168,9 @@ func (gm *StringIntMap) GetOrSetFuncLock(key string, f func() int) int {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
val = f()
|
||||
gm.m[key] = val
|
||||
return val
|
||||
} else {
|
||||
@ -155,7 +178,8 @@ func (gm *StringIntMap) GetOrSetFuncLock(key string, f func() int) int {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringIntMap) SetIfNotExist(key string, value int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -164,7 +188,34 @@ func (gm *StringIntMap) SetIfNotExist(key string, value int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringIntMap) SetIfNotExistFunc(key string, f func() int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *StringIntMap) SetIfNotExistFuncLock(key string, f func() int) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *StringIntMap) BatchRemove(keys []string) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -173,7 +224,7 @@ func (gm *StringIntMap) BatchRemove(keys []string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *StringIntMap) Remove(key string) int {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -184,7 +235,7 @@ func (gm *StringIntMap) Remove(key string) int {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *StringIntMap) Keys() []string {
|
||||
gm.mu.RLock()
|
||||
keys := make([]string, 0)
|
||||
@ -195,7 +246,7 @@ func (gm *StringIntMap) Keys() []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *StringIntMap) Values() []int {
|
||||
gm.mu.RLock()
|
||||
vals := make([]int, 0)
|
||||
@ -206,7 +257,8 @@ func (gm *StringIntMap) Values() []int {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *StringIntMap) Contains(key string) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -214,7 +266,7 @@ func (gm *StringIntMap) Contains(key string) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *StringIntMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -222,7 +274,8 @@ func (gm *StringIntMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *StringIntMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -230,28 +283,28 @@ func (gm *StringIntMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *StringIntMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[string]int)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全写锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *StringIntMap) LockFunc(f func(m map[string]int)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全读锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *StringIntMap) RLockFunc(f func(m map[string]int)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *StringIntMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -262,15 +315,16 @@ func (gm *StringIntMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *StringIntMap) Merge(m *StringIntMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *StringIntMap) Merge(other *StringIntMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,9 @@ type StringInterfaceMap struct {
|
||||
m map[string]interface{}
|
||||
}
|
||||
|
||||
// NewStringInterfaceMap returns an empty StringInterfaceMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewStringInterfaceMap(unsafe...bool) *StringInterfaceMap {
|
||||
return &StringInterfaceMap{
|
||||
m : make(map[string]interface{}),
|
||||
@ -24,6 +27,9 @@ func NewStringInterfaceMap(unsafe...bool) *StringInterfaceMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringInterfaceMapFrom returns an StringInterfaceMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewStringInterfaceMapFrom(m map[string]interface{}, unsafe...bool) *StringInterfaceMap {
|
||||
return &StringInterfaceMap{
|
||||
m : m,
|
||||
@ -31,6 +37,12 @@ func NewStringInterfaceMapFrom(m map[string]interface{}, unsafe...bool) *StringI
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringInterfaceMapFromArray returns an StringInterfaceMap object from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewStringInterfaceMapFromArray(keys []string, values []interface{}, unsafe...bool) *StringInterfaceMap {
|
||||
m := make(map[string]interface{})
|
||||
l := len(values)
|
||||
@ -47,7 +59,8 @@ func NewStringInterfaceMapFromArray(keys []string, values []interface{}, unsafe.
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *StringInterfaceMap) Iterator(f func (k string, v interface{}) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -58,12 +71,12 @@ func (gm *StringInterfaceMap) Iterator(f func (k string, v interface{}) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *StringInterfaceMap) Clone() *StringInterfaceMap {
|
||||
return NewStringInterfaceMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *StringInterfaceMap) Map() map[string]interface{} {
|
||||
m := make(map[string]interface{})
|
||||
gm.mu.RLock()
|
||||
@ -74,14 +87,14 @@ func (gm *StringInterfaceMap) Map() map[string]interface{} {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *StringInterfaceMap) Set(key string, val interface{}) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *StringInterfaceMap) BatchSet(m map[string]interface{}) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -90,7 +103,7 @@ func (gm *StringInterfaceMap) BatchSet(m map[string]interface{}) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *StringInterfaceMap) Get(key string) interface{} {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -98,8 +111,15 @@ func (gm *StringInterfaceMap) Get(key string) interface{} {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// When setting value, if <value> is type of <func() interface {}>,
|
||||
// it will be executed with mutex.Lock of the hash map,
|
||||
// and its return value will be set to the map with <key>.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *StringInterfaceMap) doSetWithLockCheck(key string, value interface{}) interface{} {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -109,11 +129,14 @@ func (gm *StringInterfaceMap) doSetWithLockCheck(key string, value interface{})
|
||||
if f, ok := value.(func() interface {}); ok {
|
||||
value = f()
|
||||
}
|
||||
gm.m[key] = value
|
||||
if value != nil {
|
||||
gm.m[key] = value
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *StringInterfaceMap) GetOrSet(key string, value interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, value)
|
||||
@ -122,7 +145,9 @@ func (gm *StringInterfaceMap) GetOrSet(key string, value interface{}) interface{
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
func (gm *StringInterfaceMap) GetOrSetFunc(key string, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f())
|
||||
@ -131,7 +156,12 @@ func (gm *StringInterfaceMap) GetOrSetFunc(key string, f func() interface{}) int
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *StringInterfaceMap) GetOrSetFuncLock(key string, f func() interface{}) interface{} {
|
||||
if v := gm.Get(key); v == nil {
|
||||
return gm.doSetWithLockCheck(key, f)
|
||||
@ -140,7 +170,8 @@ func (gm *StringInterfaceMap) GetOrSetFuncLock(key string, f func() interface{})
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringInterfaceMap) SetIfNotExist(key string, value interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -149,7 +180,30 @@ func (gm *StringInterfaceMap) SetIfNotExist(key string, value interface{}) bool
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringInterfaceMap) SetIfNotExistFunc(key string, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *StringInterfaceMap) SetIfNotExistFuncLock(key string, f func() interface{}) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *StringInterfaceMap) BatchRemove(keys []string) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -158,7 +212,7 @@ func (gm *StringInterfaceMap) BatchRemove(keys []string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *StringInterfaceMap) Remove(key string) interface{} {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -169,7 +223,7 @@ func (gm *StringInterfaceMap) Remove(key string) interface{} {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *StringInterfaceMap) Keys() []string {
|
||||
gm.mu.RLock()
|
||||
keys := make([]string, 0)
|
||||
@ -180,7 +234,7 @@ func (gm *StringInterfaceMap) Keys() []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *StringInterfaceMap) Values() []interface{} {
|
||||
gm.mu.RLock()
|
||||
vals := make([]interface{}, 0)
|
||||
@ -191,7 +245,8 @@ func (gm *StringInterfaceMap) Values() []interface{} {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *StringInterfaceMap) Contains(key string) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -199,7 +254,7 @@ func (gm *StringInterfaceMap) Contains(key string) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *StringInterfaceMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -207,7 +262,8 @@ func (gm *StringInterfaceMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *StringInterfaceMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -215,28 +271,28 @@ func (gm *StringInterfaceMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *StringInterfaceMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[string]interface{})
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全写锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *StringInterfaceMap) LockFunc(f func(m map[string]interface{})) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全读锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *StringInterfaceMap) RLockFunc(f func(m map[string]interface{})) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *StringInterfaceMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -247,15 +303,16 @@ func (gm *StringInterfaceMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *StringInterfaceMap) Merge(m *StringInterfaceMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *StringInterfaceMap) Merge(other *StringInterfaceMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,9 @@ type StringStringMap struct {
|
||||
m map[string]string
|
||||
}
|
||||
|
||||
// NewStringStringMap returns an empty StringStringMap object.
|
||||
// The param <unsafe> used to specify whether using map with un-concurrent-safety,
|
||||
// which is false in default, means concurrent-safe.
|
||||
func NewStringStringMap(unsafe...bool) *StringStringMap {
|
||||
return &StringStringMap{
|
||||
m : make(map[string]string),
|
||||
@ -23,6 +26,9 @@ func NewStringStringMap(unsafe...bool) *StringStringMap {
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringStringMapFrom returns an StringStringMap object from given map <m>.
|
||||
// Notice that, the param map is a type of pointer,
|
||||
// there might be some concurrent-safe issues when changing the map outside.
|
||||
func NewStringStringMapFrom(m map[string]string, unsafe...bool) *StringStringMap {
|
||||
return &StringStringMap{
|
||||
m : m,
|
||||
@ -30,6 +36,12 @@ func NewStringStringMapFrom(m map[string]string, unsafe...bool) *StringStringMap
|
||||
}
|
||||
}
|
||||
|
||||
// NewStringStringMapFromArray returns an StringStringMap object from given array.
|
||||
// The param <keys> given as the keys of the map,
|
||||
// and <values> as its corresponding values.
|
||||
//
|
||||
// If length of <keys> is greater than that of <values>,
|
||||
// the corresponding overflow map values will be the default value of its type.
|
||||
func NewStringStringMapFromArray(keys []string, values []string, unsafe...bool) *StringStringMap {
|
||||
m := make(map[string]string)
|
||||
l := len(values)
|
||||
@ -46,7 +58,8 @@ func NewStringStringMapFromArray(keys []string, values []string, unsafe...bool)
|
||||
}
|
||||
}
|
||||
|
||||
// 给定回调函数对原始内容进行遍历,回调函数返回true表示继续遍历,否则停止遍历
|
||||
// Iterator iterates the hash map with custom callback function <f>.
|
||||
// If f returns true, then continue iterating; or false to stop.
|
||||
func (gm *StringStringMap) Iterator(f func (k string, v string) bool) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
@ -57,12 +70,12 @@ func (gm *StringStringMap) Iterator(f func (k string, v string) bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// 哈希表克隆.
|
||||
// Clone returns a new hash map with copy of current map data.
|
||||
func (gm *StringStringMap) Clone() *StringStringMap {
|
||||
return NewStringStringMapFrom(gm.Map(), !gm.mu.IsSafe())
|
||||
}
|
||||
|
||||
// 返回当前哈希表的数据Map.
|
||||
// Map returns a copy of the data of the hash map.
|
||||
func (gm *StringStringMap) Map() map[string]string {
|
||||
m := make(map[string]string)
|
||||
gm.mu.RLock()
|
||||
@ -73,14 +86,14 @@ func (gm *StringStringMap) Map() map[string]string {
|
||||
return m
|
||||
}
|
||||
|
||||
// 设置键值对
|
||||
// Set sets key-value to the hash map.
|
||||
func (gm *StringStringMap) Set(key string, val string) {
|
||||
gm.mu.Lock()
|
||||
gm.m[key] = val
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 批量设置键值对
|
||||
// BatchSet batch sets key-values to the hash map.
|
||||
func (gm *StringStringMap) BatchSet(m map[string]string) {
|
||||
gm.mu.Lock()
|
||||
for k, v := range m {
|
||||
@ -89,7 +102,7 @@ func (gm *StringStringMap) BatchSet(m map[string]string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 获取键值
|
||||
// Get returns the value by given <key>.
|
||||
func (gm *StringStringMap) Get(key string) string {
|
||||
gm.mu.RLock()
|
||||
val, _ := gm.m[key]
|
||||
@ -97,8 +110,11 @@ func (gm *StringStringMap) Get(key string) string {
|
||||
return val
|
||||
}
|
||||
|
||||
// 设置kv缓存键值对,内部会对键名的存在性使用写锁进行二次检索确认,如果存在则不再写入;返回键名对应的键值。
|
||||
// 在高并发下有用,防止数据写入的并发逻辑错误。
|
||||
// doSetWithLockCheck checks whether value of the key exists with mutex.Lock,
|
||||
// if not exists, set value to the map with given <key>,
|
||||
// or else just return the existing value.
|
||||
//
|
||||
// It returns value with given <key>.
|
||||
func (gm *StringStringMap) doSetWithLockCheck(key string, value string) string {
|
||||
gm.mu.Lock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
@ -110,7 +126,8 @@ func (gm *StringStringMap) doSetWithLockCheck(key string, value string) string {
|
||||
return value
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值
|
||||
// GetOrSet returns the value by key,
|
||||
// or set value with given <value> if not exist and returns this value.
|
||||
func (gm *StringStringMap) GetOrSet(key string, value string) string {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -122,7 +139,9 @@ func (gm *StringStringMap) GetOrSet(key string, value string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名存在时返回其键值,否则写入指定的键值,键值由指定的函数生成
|
||||
// GetOrSetFunc returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
func (gm *StringStringMap) GetOrSetFunc(key string, f func() string) string {
|
||||
gm.mu.RLock()
|
||||
v, ok := gm.m[key]
|
||||
@ -134,7 +153,12 @@ func (gm *StringStringMap) GetOrSetFunc(key string, f func() string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 与GetOrSetFunc不同的是,f是在写锁机制内执行
|
||||
// GetOrSetFuncLock returns the value by key,
|
||||
// or sets value with return value of callback function <f> if not exist
|
||||
// and returns this value.
|
||||
//
|
||||
// GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function <f>
|
||||
// with mutex.Lock of the hash map.
|
||||
func (gm *StringStringMap) GetOrSetFuncLock(key string, f func() string) string {
|
||||
gm.mu.RLock()
|
||||
val, ok := gm.m[key]
|
||||
@ -143,10 +167,9 @@ func (gm *StringStringMap) GetOrSetFuncLock(key string, f func() string) string
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if v, ok := gm.m[key]; ok {
|
||||
gm.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
val = f()
|
||||
val = f()
|
||||
gm.m[key] = val
|
||||
return val
|
||||
} else {
|
||||
@ -154,7 +177,8 @@ func (gm *StringStringMap) GetOrSetFuncLock(key string, f func() string) string
|
||||
}
|
||||
}
|
||||
|
||||
// 当键名不存在时写入,并返回true;否则返回false。
|
||||
// SetIfNotExist sets <value> to the map if the <key> does not exist, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringStringMap) SetIfNotExist(key string, value string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, value)
|
||||
@ -163,7 +187,34 @@ func (gm *StringStringMap) SetIfNotExist(key string, value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 批量删除键值对
|
||||
// SetIfNotExistFunc sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
func (gm *StringStringMap) SetIfNotExistFunc(key string, f func() string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.doSetWithLockCheck(key, f())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetIfNotExistFuncLock sets value with return value of callback function <f>, then return true.
|
||||
// It returns false if <key> exists, and <value> would be ignored.
|
||||
//
|
||||
// SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
|
||||
// it executes function <f> with mutex.Lock of the hash map.
|
||||
func (gm *StringStringMap) SetIfNotExistFuncLock(key string, f func() string) bool {
|
||||
if !gm.Contains(key) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if _, ok := gm.m[key]; !ok {
|
||||
gm.m[key] = f()
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchRemove batch deletes values of the map by keys.
|
||||
func (gm *StringStringMap) BatchRemove(keys []string) {
|
||||
gm.mu.Lock()
|
||||
for _, key := range keys {
|
||||
@ -172,7 +223,7 @@ func (gm *StringStringMap) BatchRemove(keys []string) {
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 返回对应的键值,并删除该键值
|
||||
// Remove deletes value from map by given <key>, and return this deleted value.
|
||||
func (gm *StringStringMap) Remove(key string) string {
|
||||
gm.mu.Lock()
|
||||
val, exists := gm.m[key]
|
||||
@ -183,7 +234,7 @@ func (gm *StringStringMap) Remove(key string) string {
|
||||
return val
|
||||
}
|
||||
|
||||
// 返回键列表
|
||||
// Keys returns all keys of the map as a slice.
|
||||
func (gm *StringStringMap) Keys() []string {
|
||||
gm.mu.RLock()
|
||||
keys := make([]string, 0)
|
||||
@ -194,7 +245,7 @@ func (gm *StringStringMap) Keys() []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
// 返回值列表(注意是随机排序)
|
||||
// Values returns all values of the map as a slice.
|
||||
func (gm *StringStringMap) Values() []string {
|
||||
gm.mu.RLock()
|
||||
vals := make([]string, 0)
|
||||
@ -205,7 +256,8 @@ func (gm *StringStringMap) Values() []string {
|
||||
return vals
|
||||
}
|
||||
|
||||
// 是否存在某个键
|
||||
// Contains checks whether a key exists.
|
||||
// It returns true if the <key> exists, or else false.
|
||||
func (gm *StringStringMap) Contains(key string) bool {
|
||||
gm.mu.RLock()
|
||||
_, exists := gm.m[key]
|
||||
@ -213,7 +265,7 @@ func (gm *StringStringMap) Contains(key string) bool {
|
||||
return exists
|
||||
}
|
||||
|
||||
// 哈希表大小
|
||||
// Size returns the size of the map.
|
||||
func (gm *StringStringMap) Size() int {
|
||||
gm.mu.RLock()
|
||||
length := len(gm.m)
|
||||
@ -221,7 +273,8 @@ func (gm *StringStringMap) Size() int {
|
||||
return length
|
||||
}
|
||||
|
||||
// 哈希表是否为空
|
||||
// IsEmpty checks whether the map is empty.
|
||||
// It returns true if map is empty, or else false.
|
||||
func (gm *StringStringMap) IsEmpty() bool {
|
||||
gm.mu.RLock()
|
||||
empty := len(gm.m) == 0
|
||||
@ -229,28 +282,28 @@ func (gm *StringStringMap) IsEmpty() bool {
|
||||
return empty
|
||||
}
|
||||
|
||||
// 清空哈希表
|
||||
// Clear deletes all data of the map, it will remake a new underlying map data map.
|
||||
func (gm *StringStringMap) Clear() {
|
||||
gm.mu.Lock()
|
||||
gm.m = make(map[string]string)
|
||||
gm.mu.Unlock()
|
||||
}
|
||||
|
||||
// 并发安全写锁操作,使用自定义方法执行加锁修改操作
|
||||
// LockFunc locks writing with given callback function <f> and mutex.Lock.
|
||||
func (gm *StringStringMap) LockFunc(f func(m map[string]string)) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 并发安全读锁操作,使用自定义方法执行加锁读取操作
|
||||
// RLockFunc locks reading with given callback function <f> and mutex.RLock.
|
||||
func (gm *StringStringMap) RLockFunc(f func(m map[string]string)) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
f(gm.m)
|
||||
}
|
||||
|
||||
// 交换Map中的键和值.
|
||||
// Flip exchanges key-value of the map, it will change key-value to value-key.
|
||||
func (gm *StringStringMap) Flip() {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
@ -261,15 +314,16 @@ func (gm *StringStringMap) Flip() {
|
||||
gm.m = n
|
||||
}
|
||||
|
||||
// 合并两个Map.
|
||||
func (gm *StringStringMap) Merge(m *StringStringMap) {
|
||||
// Merge merges two hash maps.
|
||||
// The <other> map will be merged into the map <gm>.
|
||||
func (gm *StringStringMap) Merge(other *StringStringMap) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
if m != gm {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if other != gm {
|
||||
other.mu.RLock()
|
||||
defer other.mu.RUnlock()
|
||||
}
|
||||
for k, v := range m.m {
|
||||
for k, v := range other.m {
|
||||
gm.m[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,8 +5,6 @@
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gpool provides a object-reusable concurrent-safe pool.
|
||||
//
|
||||
// 对象复用池.
|
||||
package gpool
|
||||
|
||||
import (
|
||||
|
||||
@ -4,9 +4,7 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gring provides a concurrent-safe(alternative) ring(circular lists).
|
||||
//
|
||||
// 并发安全环.
|
||||
// Package gring provides a concurrent-safe/unsafe ring(circular lists).
|
||||
package gring
|
||||
|
||||
import (
|
||||
|
||||
229
g/container/gring/gring_unit_test.go
Normal file
229
g/container/gring/gring_unit_test.go
Normal file
@ -0,0 +1,229 @@
|
||||
package gring_test
|
||||
|
||||
import (
|
||||
"container/ring"
|
||||
"github.com/gogf/gf/g"
|
||||
"github.com/gogf/gf/g/container/gring"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
type Student struct {
|
||||
position int
|
||||
name string
|
||||
upgrade bool
|
||||
}
|
||||
|
||||
func TestRing_Val(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
//定义cap 为3的ring类型数据
|
||||
r := gring.New(3, true)
|
||||
//分别给3个元素初始化赋值
|
||||
r.Put(&Student{1,"jimmy", true})
|
||||
r.Put(&Student{2,"tom", true})
|
||||
r.Put(&Student{3,"alon", false})
|
||||
|
||||
//元素取值并判断和预设值是否相等
|
||||
gtest.Assert(r.Val().(*Student).name,"jimmy")
|
||||
//从当前位置往后移两个元素
|
||||
r.Move(2)
|
||||
gtest.Assert(r.Val().(*Student).name,"alon")
|
||||
//更新元素值
|
||||
//测试 value == nil
|
||||
r.Set(nil)
|
||||
gtest.Assert(r.Val(),nil)
|
||||
//测试value != nil
|
||||
r.Set(&Student{3, "jack", true})
|
||||
})
|
||||
}
|
||||
func TestRing_CapLen(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
r := gring.New(10)
|
||||
r.Put("goframe")
|
||||
//cap长度 10
|
||||
gtest.Assert(r.Cap(), 10)
|
||||
//已有数据项 1
|
||||
gtest.Assert(r.Len(), 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_Position(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
r := gring.New(2)
|
||||
r.Put(1)
|
||||
r.Put(2)
|
||||
//往后移动1个元素
|
||||
r.Next()
|
||||
gtest.Assert(r.Val(),2)
|
||||
//往前移动1个元素
|
||||
r.Prev()
|
||||
gtest.Assert(r.Val(),1)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_Link(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
r := gring.New(3)
|
||||
r.Put(1)
|
||||
r.Put(2)
|
||||
r.Put(3)
|
||||
s := gring.New(2)
|
||||
s.Put("a")
|
||||
s.Put("b")
|
||||
|
||||
rs := r.Link(s)
|
||||
gtest.Assert(rs.Move(2).Val(), "b")
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_Unlink(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
r := gring.New(5)
|
||||
for i := 0; i< 5; i++ {
|
||||
r.Put(i+1)
|
||||
}
|
||||
// 1 2 3 4
|
||||
// 删除当前位置往后的2个数据,返回被删除的数据
|
||||
// 重新计算s len
|
||||
s := r.Unlink(2) // 2 3
|
||||
gtest.Assert(s.Val(), 2)
|
||||
gtest.Assert(s.Len(), 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_Slice(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
ringLen := 5
|
||||
r := gring.New(ringLen)
|
||||
for i := 0; i< ringLen; i++ {
|
||||
r.Put(i+1)
|
||||
}
|
||||
r.Move(2) // 3
|
||||
array := r.SliceNext() // [3 4 5 1 2]
|
||||
gtest.Assert(array[0], 3)
|
||||
gtest.Assert(len(array), 5)
|
||||
|
||||
//判断array是否等于[3 4 5 1 2]
|
||||
ra := []int{3,4,5,1,2}
|
||||
gtest.Assert(ra, array)
|
||||
|
||||
//第3个元素设为nil
|
||||
r.Set(nil)
|
||||
array2 := r.SliceNext() //[4 5 1 2]
|
||||
//返回当前位置往后不为空的元素数组,长度为4
|
||||
gtest.Assert(array2, g.Slice{4,5,1,2})
|
||||
|
||||
array3 := r.SlicePrev() //[2 1 5 4]
|
||||
gtest.Assert(array3, g.Slice{2,1,5,4})
|
||||
|
||||
s := gring.New(ringLen)
|
||||
for i := 0; i< ringLen; i++ {
|
||||
s.Put(i+1)
|
||||
}
|
||||
array4 := s.SlicePrev() // []
|
||||
gtest.Assert(array4, g.Slice{1,5,4,3,2})
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_RLockIterator(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
ringLen := 5
|
||||
r := gring.New(ringLen)
|
||||
|
||||
//ring不存在有值元素
|
||||
r.RLockIteratorNext(func(v interface{}) bool {
|
||||
gtest.Assert(v, nil)
|
||||
return false
|
||||
})
|
||||
r.RLockIteratorNext(func(v interface{}) bool {
|
||||
gtest.Assert(v, nil)
|
||||
return true
|
||||
})
|
||||
|
||||
r.RLockIteratorPrev(func(v interface{}) bool {
|
||||
gtest.Assert(v, nil)
|
||||
return true
|
||||
})
|
||||
|
||||
for i := 0; i< ringLen; i++ {
|
||||
r.Put(i+1)
|
||||
}
|
||||
|
||||
//回调函数返回true,RLockIteratorNext遍历5次,期望值分别是1、2、3、4、5
|
||||
i := 0
|
||||
r.RLockIteratorNext(func(v interface{}) bool {
|
||||
gtest.Assert(v, i+1)
|
||||
i++;
|
||||
return true
|
||||
})
|
||||
|
||||
//RLockIteratorPrev遍历1次返回 false,退出遍历
|
||||
r.RLockIteratorPrev(func(v interface{}) bool {
|
||||
gtest.Assert(v, 1)
|
||||
return false
|
||||
})
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func TestRing_LockIterator(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
ringLen := 5
|
||||
r := gring.New(ringLen)
|
||||
|
||||
//不存在有值元素
|
||||
r.LockIteratorNext(func(item *ring.Ring) bool {
|
||||
gtest.Assert(item.Value, nil)
|
||||
return false
|
||||
})
|
||||
r.LockIteratorNext(func(item *ring.Ring) bool {
|
||||
gtest.Assert(item.Value, nil)
|
||||
return false
|
||||
})
|
||||
r.LockIteratorNext(func(item *ring.Ring) bool {
|
||||
gtest.Assert(item.Value, nil)
|
||||
return true
|
||||
})
|
||||
|
||||
r.LockIteratorPrev(func(item *ring.Ring) bool {
|
||||
gtest.Assert(item.Value, nil)
|
||||
return false
|
||||
})
|
||||
r.LockIteratorPrev(func(item *ring.Ring) bool {
|
||||
gtest.Assert(item.Value, nil)
|
||||
return true
|
||||
})
|
||||
|
||||
//ring初始化元素值
|
||||
for i := 0; i< ringLen; i++ {
|
||||
r.Put(i+1)
|
||||
}
|
||||
|
||||
//往后遍历组成数据 [1,2,3,4,5]
|
||||
array1 := g.Slice{1,2,3,4,5}
|
||||
ii := 0
|
||||
r.LockIteratorNext(func(item *ring.Ring) bool {
|
||||
//校验每一次遍历取值是否是期望值
|
||||
gtest.Assert(item.Value, array1[ii])
|
||||
ii++;
|
||||
return true
|
||||
})
|
||||
|
||||
//往后取3个元素组成数组
|
||||
//获得 [1,5,4]
|
||||
i := 0
|
||||
a := g.Slice{1,5,4}
|
||||
r.LockIteratorPrev(func(item *ring.Ring) bool {
|
||||
if i > 2 {
|
||||
return false
|
||||
}
|
||||
gtest.Assert(item.Value, a[i])
|
||||
i++;
|
||||
return true
|
||||
})
|
||||
|
||||
|
||||
})
|
||||
}
|
||||
@ -4,9 +4,7 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gset provides kinds of concurrent-safe(alternative) sets.
|
||||
//
|
||||
// 并发安全集合.
|
||||
// Package gset provides kinds of concurrent-safe/unsafe sets.
|
||||
package gset
|
||||
|
||||
import (
|
||||
|
||||
@ -4,9 +4,7 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gtype provides kinds of high performance, concurrent-safe basic variable types.
|
||||
//
|
||||
// 并发安全基本类型.
|
||||
// Package gtype provides kinds of high performance, concurrent-safe/unsafe basic variable types.
|
||||
package gtype
|
||||
|
||||
type Type = Interface
|
||||
|
||||
@ -5,8 +5,6 @@
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gvar provides an universal variable type, like generics.
|
||||
//
|
||||
// 通用动态变量.
|
||||
package gvar
|
||||
|
||||
import (
|
||||
@ -18,7 +16,7 @@ import (
|
||||
|
||||
type Var struct {
|
||||
value interface{} // 变量值
|
||||
safe bool // 当为true时,value为 *gtype.Interface 类型
|
||||
safe bool // 当为true时, value为 *gtype.Interface 类型
|
||||
}
|
||||
|
||||
// 创建一个动态变量,value参数可以为nil
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package crypto
|
||||
@ -1,7 +0,0 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package database
|
||||
@ -14,6 +14,7 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/g/container/gring"
|
||||
"github.com/gogf/gf/g/container/gtype"
|
||||
"github.com/gogf/gf/g/container/gvar"
|
||||
@ -147,30 +148,34 @@ type Map = map[string]interface{}
|
||||
type List = []Map
|
||||
|
||||
const (
|
||||
OPTION_INSERT = 0
|
||||
OPTION_REPLACE = 1
|
||||
OPTION_SAVE = 2
|
||||
OPTION_IGNORE = 3
|
||||
// 默认批量操作的数量值(Batch*操作)
|
||||
gDEFAULT_BATCH_NUM = 10
|
||||
// 默认的连接池连接存活时间(秒)
|
||||
gDEFAULT_CONN_MAX_LIFE_TIME = 30
|
||||
|
||||
OPTION_INSERT = 0
|
||||
OPTION_REPLACE = 1
|
||||
OPTION_SAVE = 2
|
||||
OPTION_IGNORE = 3
|
||||
gDEFAULT_BATCH_NUM = 10 // Per count for batch insert/replace/save
|
||||
gDEFAULT_CONN_MAX_LIFE_TIME = 30 // Max life time for per connection in pool.
|
||||
)
|
||||
|
||||
// 使用默认/指定分组配置进行连接,数据库集群配置项:default
|
||||
func New(groupName ...string) (db DB, err error) {
|
||||
group := config.d
|
||||
if len(groupName) > 0 {
|
||||
group = groupName[0]
|
||||
}
|
||||
config.RLock()
|
||||
defer config.RUnlock()
|
||||
var (
|
||||
// Instance map.
|
||||
instances = gmap.NewStringInterfaceMap()
|
||||
)
|
||||
|
||||
if len(config.c) < 1 {
|
||||
// New creates ORM DB object with global configurations.
|
||||
// The param <name> specifies the configuration group name,
|
||||
// which is DEFAULT_GROUP_NAME in default.
|
||||
func New(name ...string) (db DB, err error) {
|
||||
group := configs.defaultGroup
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
configs.RLock()
|
||||
defer configs.RUnlock()
|
||||
|
||||
if len(configs.config) < 1 {
|
||||
return nil, errors.New("empty database configuration")
|
||||
}
|
||||
if _, ok := config.c[group]; ok {
|
||||
if _, ok := configs.config[group]; ok {
|
||||
if node, err := getConfigNodeByGroup(group, true); err == nil {
|
||||
base := &dbBase {
|
||||
group : group,
|
||||
@ -204,9 +209,27 @@ func New(groupName ...string) (db DB, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Instance returns an instance for DB operations.
|
||||
// The param <name> specifies the configuration group name,
|
||||
// which is DEFAULT_GROUP_NAME in default.
|
||||
func Instance(name ...string) (db DB, err error) {
|
||||
group := configs.defaultGroup
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
v := instances.GetOrSetFuncLock(group, func() interface{} {
|
||||
db, err = New(group)
|
||||
return db
|
||||
})
|
||||
if v != nil {
|
||||
return v.(DB), nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 获取指定数据库角色的一个配置项,内部根据权重计算负载均衡
|
||||
func getConfigNodeByGroup(group string, master bool) (*ConfigNode, error) {
|
||||
if list, ok := config.c[group]; ok {
|
||||
if list, ok := configs.config[group]; ok {
|
||||
// 将master, slave集群列表拆分出来
|
||||
masterList := make(ConfigGroup, 0)
|
||||
slaveList := make(ConfigGroup, 0)
|
||||
@ -319,17 +342,17 @@ func (bs *dbBase) getSqlDb(master bool) (sqlDb *sql.DB, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// 切换操作的数据库(注意该切换是全局的)
|
||||
// 切换当前数据库对象操作的数据库。
|
||||
func (bs *dbBase) SetSchema(schema string) {
|
||||
bs.schema.Set(schema)
|
||||
}
|
||||
|
||||
// 创建底层数据库master链接对象
|
||||
// 创建底层数据库master链接对象。
|
||||
func (bs *dbBase) Master() (*sql.DB, error) {
|
||||
return bs.getSqlDb(true)
|
||||
}
|
||||
|
||||
// 创建底层数据库slave链接对象
|
||||
// 创建底层数据库slave链接对象。
|
||||
func (bs *dbBase) Slave() (*sql.DB, error) {
|
||||
return bs.getSqlDb(false)
|
||||
}
|
||||
|
||||
@ -17,14 +17,7 @@ const (
|
||||
DEFAULT_GROUP_NAME = "default" // 默认配置名称
|
||||
)
|
||||
|
||||
// 数据库配置包内对象
|
||||
var config struct {
|
||||
sync.RWMutex
|
||||
c Config // 数据库配置
|
||||
d string // 默认数据库分组名称
|
||||
}
|
||||
|
||||
// 数据库配置
|
||||
// 数据库分组配置
|
||||
type Config map[string]ConfigGroup
|
||||
|
||||
// 数据库集群配置
|
||||
@ -41,12 +34,19 @@ type ConfigNode struct {
|
||||
Role string // (可选,默认为master)数据库的角色,用于主从操作分离,至少需要有一个master,参数值:master, slave
|
||||
Charset string // (可选,默认为 utf8)编码,默认为 utf8
|
||||
Priority int // (可选)用于负载均衡的权重计算,当集群中只有一个节点时,权重没有任何意义
|
||||
Linkinfo string // (可选)自定义链接信息,当该字段被设置值时,以上链接字段(Host,Port,User,Pass,Name)将失效(该字段是一个扩展功能)
|
||||
LinkInfo string // (可选)自定义链接信息,当该字段被设置值时,以上链接字段(Host,Port,User,Pass,Name)将失效(该字段是一个扩展功能)
|
||||
MaxIdleConnCount int // (可选)连接池最大限制的连接数
|
||||
MaxOpenConnCount int // (可选)连接池最大打开的连接数
|
||||
MaxConnLifetime int // (可选,单位秒)连接对象可重复使用的时间长度
|
||||
}
|
||||
|
||||
// 数据库配置包内对象
|
||||
var configs struct {
|
||||
sync.RWMutex // 并发安全互斥锁
|
||||
config Config // 数据库分组配置
|
||||
defaultGroup string // 默认数据库分组名称
|
||||
}
|
||||
|
||||
// 数据库集群配置示例,支持主从处理,多数据库集群支持
|
||||
/*
|
||||
var DatabaseConfiguration = Config {
|
||||
@ -80,29 +80,32 @@ var DatabaseConfiguration = Config {
|
||||
|
||||
// 包初始化
|
||||
func init() {
|
||||
config.c = make(Config)
|
||||
config.d = DEFAULT_GROUP_NAME
|
||||
configs.config = make(Config)
|
||||
configs.defaultGroup = DEFAULT_GROUP_NAME
|
||||
}
|
||||
|
||||
// 设置当前应用的数据库配置信息,进行全局数据库配置覆盖操作
|
||||
func SetConfig (c Config) {
|
||||
config.Lock()
|
||||
defer config.Unlock()
|
||||
config.c = c
|
||||
func SetConfig (config Config) {
|
||||
defer instances.Clear()
|
||||
configs.Lock()
|
||||
defer configs.Unlock()
|
||||
configs.config = config
|
||||
}
|
||||
|
||||
// 添加数据库服务器集群配置
|
||||
func AddConfigGroup (group string, nodes ConfigGroup) {
|
||||
config.Lock()
|
||||
config.c[group] = nodes
|
||||
config.Unlock()
|
||||
defer instances.Clear()
|
||||
configs.Lock()
|
||||
defer configs.Unlock()
|
||||
configs.config[group] = nodes
|
||||
}
|
||||
|
||||
// 添加一台数据库服务器配置
|
||||
func AddConfigNode (group string, node ConfigNode) {
|
||||
config.Lock()
|
||||
config.c[group] = append(config.c[group], node)
|
||||
config.Unlock()
|
||||
defer instances.Clear()
|
||||
configs.Lock()
|
||||
defer configs.Unlock()
|
||||
configs.config[group] = append(configs.config[group], node)
|
||||
}
|
||||
|
||||
// 添加默认链接的一台数据库服务器配置
|
||||
@ -117,16 +120,25 @@ func AddDefaultConfigGroup (nodes ConfigGroup) {
|
||||
|
||||
// 添加一台数据库服务器配置
|
||||
func GetConfig (group string) ConfigGroup {
|
||||
config.RLock()
|
||||
defer config.RUnlock()
|
||||
return config.c[group]
|
||||
configs.RLock()
|
||||
defer configs.RUnlock()
|
||||
return configs.config[group]
|
||||
}
|
||||
|
||||
// 设置默认链接的数据库链接配置项(默认是 default)
|
||||
func SetDefaultGroup (groupName string) {
|
||||
config.Lock()
|
||||
config.d = groupName
|
||||
config.Unlock()
|
||||
func SetDefaultGroup (name string) {
|
||||
defer instances.Clear()
|
||||
configs.Lock()
|
||||
defer configs.Unlock()
|
||||
configs.defaultGroup = name
|
||||
}
|
||||
|
||||
// 获取默认链接的数据库链接配置项(默认是 default)
|
||||
func GetDefaultGroup() string {
|
||||
defer instances.Clear()
|
||||
configs.Lock()
|
||||
defer configs.Unlock()
|
||||
return configs.defaultGroup
|
||||
}
|
||||
|
||||
// 设置数据库连接池中空闲链接的大小
|
||||
@ -147,8 +159,8 @@ func (bs *dbBase) SetConnMaxLifetime(n int) {
|
||||
|
||||
// 节点配置转换为字符串
|
||||
func (node *ConfigNode) String() string {
|
||||
if node.Linkinfo != "" {
|
||||
return node.Linkinfo
|
||||
if node.LinkInfo != "" {
|
||||
return node.LinkInfo
|
||||
}
|
||||
return fmt.Sprintf(`%s@%s:%s,%s,%s,%s,%s,%d-%d-%d`, node.User, node.Host, node.Port,
|
||||
node.Name, node.Type, node.Role, node.Charset,
|
||||
|
||||
@ -30,8 +30,8 @@ type dbMssql struct {
|
||||
// 创建SQL操作对象
|
||||
func (db *dbMssql) Open(config *ConfigNode) (*sql.DB, error) {
|
||||
source := ""
|
||||
if config.Linkinfo != "" {
|
||||
source = config.Linkinfo
|
||||
if config.LinkInfo != "" {
|
||||
source = config.LinkInfo
|
||||
} else {
|
||||
source = fmt.Sprintf("user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable",
|
||||
config.User, config.Pass, config.Host, config.Port, config.Name)
|
||||
|
||||
@ -20,8 +20,8 @@ type dbMysql struct {
|
||||
// 创建SQL操作对象,内部采用了lazy link处理
|
||||
func (db *dbMysql) Open (config *ConfigNode) (*sql.DB, error) {
|
||||
var source string
|
||||
if config.Linkinfo != "" {
|
||||
source = config.Linkinfo
|
||||
if config.LinkInfo != "" {
|
||||
source = config.LinkInfo
|
||||
} else {
|
||||
source = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&multiStatements=true",
|
||||
config.User, config.Pass, config.Host, config.Port, config.Name, config.Charset)
|
||||
|
||||
@ -30,8 +30,8 @@ type dbOracle struct {
|
||||
// 创建SQL操作对象
|
||||
func (db *dbOracle) Open(config *ConfigNode) (*sql.DB, error) {
|
||||
var source string
|
||||
if config.Linkinfo != "" {
|
||||
source = config.Linkinfo
|
||||
if config.LinkInfo != "" {
|
||||
source = config.LinkInfo
|
||||
} else {
|
||||
source = fmt.Sprintf("%s/%s@%s", config.User, config.Pass, config.Name)
|
||||
}
|
||||
|
||||
@ -26,8 +26,8 @@ type dbPgsql struct {
|
||||
// 创建SQL操作对象,内部采用了lazy link处理
|
||||
func (db *dbPgsql) Open (config *ConfigNode) (*sql.DB, error) {
|
||||
var source string
|
||||
if config.Linkinfo != "" {
|
||||
source = config.Linkinfo
|
||||
if config.LinkInfo != "" {
|
||||
source = config.LinkInfo
|
||||
} else {
|
||||
source = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s", config.User, config.Pass, config.Host, config.Port, config.Name)
|
||||
}
|
||||
|
||||
@ -24,8 +24,8 @@ type dbSqlite struct {
|
||||
|
||||
func (db *dbSqlite) Open(config *ConfigNode) (*sql.DB, error) {
|
||||
var source string
|
||||
if config.Linkinfo != "" {
|
||||
source = config.Linkinfo
|
||||
if config.LinkInfo != "" {
|
||||
source = config.LinkInfo
|
||||
} else {
|
||||
source = config.Name
|
||||
}
|
||||
|
||||
28
g/database/gdb/gdb_unit_basic_test.go
Normal file
28
g/database/gdb/gdb_unit_basic_test.go
Normal file
@ -0,0 +1,28 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gdb_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/database/gdb"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Instance(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
_, err := gdb.Instance("none")
|
||||
gtest.AssertNE(err, nil)
|
||||
|
||||
db, err := gdb.Instance()
|
||||
gtest.Assert(err, nil)
|
||||
|
||||
err1 := db.PingMaster()
|
||||
err2 := db.PingSlave()
|
||||
gtest.Assert(err1, nil)
|
||||
gtest.Assert(err2, nil)
|
||||
})
|
||||
}
|
||||
@ -1,3 +1,9 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gdb_test
|
||||
|
||||
import (
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
// 方法操作
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gdb_test
|
||||
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
// 链式操作
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gdb_test
|
||||
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
// 事务操作
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gdb_test
|
||||
|
||||
|
||||
@ -4,37 +4,45 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gredis provides client for redis server.
|
||||
// Package gredis provides convenient client for redis server.
|
||||
//
|
||||
// Redis客户端.
|
||||
// Redis中文手册文档请参考:http://redisdoc.com/ , Redis官方命令请参考:https://redis.io/commands
|
||||
// Redis中文手册请参考:http://redisdoc.com/
|
||||
// Redis官方命令请参考:https://redis.io/commands
|
||||
package gredis
|
||||
|
||||
import (
|
||||
"time"
|
||||
"github.com/gogf/gf/third/github.com/gomodule/redigo/redis"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/third/github.com/gomodule/redigo/redis"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
gDEFAULT_POOL_MAX_IDLE = 1
|
||||
gDEFAULT_POOL_MAX_ACTIVE = 10
|
||||
gDEFAULT_POOL_IDLE_TIMEOUT = 180 * time.Second
|
||||
gDEFAULT_POOL_MAX_LIFE_TIME = 60 * time.Second
|
||||
gDEFAULT_POOL_IDLE_TIMEOUT = 60 * time.Second
|
||||
gDEFAULT_POOL_MAX_LIFE_TIME = 60 * time.Second
|
||||
)
|
||||
|
||||
// Redis客户端
|
||||
// Redis客户端(管理连接池)
|
||||
type Redis struct {
|
||||
pool *redis.Pool
|
||||
pool *redis.Pool // 底层连接池
|
||||
group string // 配置分组
|
||||
config Config // 配置对象
|
||||
}
|
||||
|
||||
// Redis连接对象(连接池中的单个连接)
|
||||
type Conn redis.Conn
|
||||
|
||||
// Redis服务端但节点连接配置信息
|
||||
type Config struct {
|
||||
Host string // IP/域名
|
||||
Port int // 端口
|
||||
Db int // db
|
||||
Pass string // 密码
|
||||
Host string // 地址
|
||||
Port int // 端口
|
||||
Db int // 数据库
|
||||
Pass string // 授权密码
|
||||
MaxIdle int // 最大允许空闲存在的连接数(默认为0表示不存在闲置连接)
|
||||
MaxActive int // 最大连接数量限制(默认为0表示不限制)
|
||||
IdleTimeout time.Duration // 连接最大空闲时间(默认为60秒,不允许设置为0)
|
||||
MaxConnLifetime time.Duration // 连接最长存活时间(默认为60秒,不允许设置为0)
|
||||
}
|
||||
|
||||
// Redis链接池统计信息
|
||||
@ -42,91 +50,160 @@ type PoolStats struct {
|
||||
redis.PoolStats
|
||||
}
|
||||
|
||||
// 连接池map
|
||||
var pools = gmap.NewStringInterfaceMap()
|
||||
var (
|
||||
// 单例对象Map
|
||||
instances = gmap.NewStringInterfaceMap()
|
||||
// 连接池Map
|
||||
pools = gmap.NewStringInterfaceMap()
|
||||
)
|
||||
|
||||
// 创建redis操作对象.
|
||||
// New creates a redis client object with given configuration.
|
||||
// Redis client maintains a connection pool automatically.
|
||||
//
|
||||
// 创建redis操作对象,底层根据配置信息公用的连接池(连接池单例)。
|
||||
func New(config Config) *Redis {
|
||||
r := &Redis{}
|
||||
poolKey := fmt.Sprintf("%s:%d,%d", config.Host, config.Port, config.Db)
|
||||
if v := pools.Get(poolKey); v == nil {
|
||||
pool := &redis.Pool {
|
||||
MaxIdle : gDEFAULT_POOL_MAX_IDLE,
|
||||
MaxActive : gDEFAULT_POOL_MAX_ACTIVE,
|
||||
IdleTimeout : gDEFAULT_POOL_IDLE_TIMEOUT,
|
||||
MaxConnLifetime : gDEFAULT_POOL_MAX_LIFE_TIME,
|
||||
Dial : func() (redis.Conn, error) {
|
||||
c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", config.Host, config.Port))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(config.Pass) > 0 {
|
||||
if _, err := c.Do("AUTH", config.Pass); err != nil {
|
||||
if config.IdleTimeout == 0 {
|
||||
config.IdleTimeout = gDEFAULT_POOL_IDLE_TIMEOUT
|
||||
}
|
||||
if config.MaxConnLifetime == 0 {
|
||||
config.MaxConnLifetime = gDEFAULT_POOL_MAX_LIFE_TIME
|
||||
}
|
||||
return &Redis{
|
||||
config : config,
|
||||
pool : pools.GetOrSetFuncLock(fmt.Sprintf("%v", config), func() interface{} {
|
||||
return &redis.Pool {
|
||||
IdleTimeout : config.IdleTimeout,
|
||||
MaxConnLifetime : config.MaxConnLifetime,
|
||||
Dial : func() (redis.Conn, error) {
|
||||
c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", config.Host, config.Port))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if _, err := c.Do("SELECT", config.Db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
},
|
||||
// 用来测试连接是否可用
|
||||
TestOnBorrow: func(c redis.Conn, t time.Time) error {
|
||||
_, err := c.Do("PING")
|
||||
return err
|
||||
},
|
||||
}
|
||||
pools.Set(poolKey, pool)
|
||||
r.pool = pool
|
||||
} else {
|
||||
r.pool = v.(*redis.Pool)
|
||||
// 密码设置
|
||||
if len(config.Pass) > 0 {
|
||||
if _, err := c.Do("AUTH", config.Pass); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// 数据库设置
|
||||
if _, err := c.Do("SELECT", config.Db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
},
|
||||
// 在被应用从连接池中获取出来之后,用以测试连接是否可用,
|
||||
// 如果返回error那么关闭该连接对象重新创建新的连接。
|
||||
TestOnBorrow: func(c redis.Conn, t time.Time) error {
|
||||
_, err := c.Do("PING")
|
||||
return err
|
||||
},
|
||||
}
|
||||
}).(*redis.Pool),
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// 关闭redis管理对象,将会关闭底层的
|
||||
// Instance returns an instance of redis client with specified group.
|
||||
// The <group> param is unnecessary, if <group> is not passed,
|
||||
// return redis instance with default group.
|
||||
//
|
||||
// 获取指定分组名称的Redis单例对象,底层根据配置信息公用的连接池(连接池单例)。
|
||||
func Instance(name ...string) *Redis {
|
||||
group := DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
v := instances.GetOrSetFuncLock(group, func() interface{} {
|
||||
if config, ok := GetConfig(group); ok {
|
||||
r := New(config)
|
||||
r.group = group
|
||||
return r
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if v != nil {
|
||||
return v.(*Redis)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the redis connection pool,
|
||||
// it will release all connections reserved by this pool.
|
||||
// It always not necessary to call Close manually.
|
||||
//
|
||||
// 关闭redis管理对象,将会关闭底层的连接池。
|
||||
// 往往没必要手动调用,跟随进程销毁即可。
|
||||
func (r *Redis) Close() error {
|
||||
if r.group != "" {
|
||||
// 如果是单例对象,那么需要从单例对象Map中删除
|
||||
instances.Remove(r.group)
|
||||
}
|
||||
pools.Remove(fmt.Sprintf("%v", r.config))
|
||||
return r.pool.Close()
|
||||
}
|
||||
|
||||
// 获得一个原生的redis连接对象,用于自定义连接操作,
|
||||
// 但是需要注意的是如果不再使用该连接对象时,需要手动Close连接,否则会造成连接数超限。
|
||||
func (r *Redis) GetConn() redis.Conn {
|
||||
return r.pool.Get()
|
||||
// See GetConn.
|
||||
func (r *Redis) Conn() Conn {
|
||||
return r.GetConn()
|
||||
}
|
||||
|
||||
// GetConn returns a raw connection object,
|
||||
// which expose more methods communication with server.
|
||||
// **You should call Close function manually if you do not use this connection any further.**
|
||||
//
|
||||
// 获得一个原生的redis连接对象,用于自定义连接操作,
|
||||
// 但是需要注意的是如果不再使用该连接对象时,需要手动Close连接,否则会造成连接数超限。
|
||||
func (r *Redis) GetConn() Conn {
|
||||
return r.pool.Get().(Conn)
|
||||
}
|
||||
|
||||
// SetMaxIdle sets the MaxIdle attribute of the connection pool.
|
||||
//
|
||||
// 设置属性 - MaxIdle
|
||||
func (r *Redis) SetMaxIdle(value int) {
|
||||
r.pool.MaxIdle = value
|
||||
}
|
||||
|
||||
// SetMaxIdle sets the MaxActive attribute of the connection pool.
|
||||
//
|
||||
// 设置属性 - MaxActive
|
||||
func (r *Redis) SetMaxActive(value int) {
|
||||
r.pool.MaxActive = value
|
||||
}
|
||||
|
||||
// SetMaxIdle sets the IdleTimeout attribute of the connection pool.
|
||||
//
|
||||
// 设置属性 - IdleTimeout
|
||||
func (r *Redis) SetIdleTimeout(value time.Duration) {
|
||||
r.pool.IdleTimeout = value
|
||||
}
|
||||
|
||||
// SetMaxIdle sets the MaxConnLifetime attribute of the connection pool.
|
||||
//
|
||||
// 设置属性 - MaxConnLifetime
|
||||
func (r *Redis) SetMaxConnLifetime(value time.Duration) {
|
||||
r.pool.MaxConnLifetime = value
|
||||
}
|
||||
|
||||
// 获取当前连接池统计信息
|
||||
// Stats returns pool's statistics.
|
||||
//
|
||||
// 获取当前连接池统计信息。
|
||||
func (r *Redis) Stats() *PoolStats {
|
||||
return &PoolStats{r.pool.Stats()}
|
||||
}
|
||||
|
||||
// 执行同步命令 - Do
|
||||
// Do sends a command to the server and returns the received reply.
|
||||
// Do automatically get a connection from pool, and close it when reply received.
|
||||
//
|
||||
// 执行同步命令,自动从连接池中获取连接,使用完毕后关闭连接(丢回连接池),开发者不用自行Close.
|
||||
func (r *Redis) Do(command string, args ...interface{}) (interface{}, error) {
|
||||
conn := r.pool.Get()
|
||||
defer conn.Close()
|
||||
return conn.Do(command, args...)
|
||||
}
|
||||
|
||||
// Deprecated.
|
||||
// Send writes the command to the client's output buffer.
|
||||
//
|
||||
// 执行异步命令 - Send
|
||||
func (r *Redis) Send(command string, args ...interface{}) error {
|
||||
conn := r.pool.Get()
|
||||
|
||||
61
g/database/gredis/gredis_config.go
Normal file
61
g/database/gredis/gredis_config.go
Normal file
@ -0,0 +1,61 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gredis
|
||||
|
||||
import "github.com/gogf/gf/g/container/gmap"
|
||||
|
||||
const (
|
||||
// Default configuration group name.
|
||||
DEFAULT_GROUP_NAME = "default"
|
||||
)
|
||||
var (
|
||||
// Configuration groups.
|
||||
configs = gmap.NewStringInterfaceMap()
|
||||
)
|
||||
|
||||
// SetConfig sets the global configuration for specified group.
|
||||
// If <name> is not passed, it sets configuration for the default group name.
|
||||
func SetConfig(config Config, name...string) {
|
||||
group := DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
configs.Set(group, config)
|
||||
instances.Remove(group)
|
||||
}
|
||||
|
||||
// GetConfig returns the global configuration with specified group name.
|
||||
// If <name> is not passed, it returns configuration of the default group name.
|
||||
func GetConfig(name...string) (config Config, ok bool) {
|
||||
group := DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
if v := configs.Get(group); v != nil {
|
||||
return v.(Config), true
|
||||
}
|
||||
return Config{}, false
|
||||
}
|
||||
|
||||
// RemoveConfig removes the global configuration with specified group.
|
||||
// If <name> is not passed, it removes configuration of the default group name.
|
||||
func RemoveConfig(name...string) {
|
||||
group := DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
configs.Remove(group)
|
||||
instances.Remove(group)
|
||||
}
|
||||
|
||||
// ClearConfig removes all configurations and instances of redis.
|
||||
func ClearConfig() {
|
||||
configs.Clear()
|
||||
instances.Clear()
|
||||
}
|
||||
|
||||
|
||||
139
g/database/gredis/gredis_unit_test.go
Normal file
139
g/database/gredis/gredis_unit_test.go
Normal file
@ -0,0 +1,139 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gredis_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/database/gredis"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
config = gredis.Config{
|
||||
Host : "127.0.0.1",
|
||||
Port : 6379,
|
||||
Db : 1,
|
||||
}
|
||||
)
|
||||
|
||||
func Test_NewClose(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
redis := gredis.New(config)
|
||||
gtest.AssertNE(redis, nil)
|
||||
err := redis.Close()
|
||||
gtest.Assert(err, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Do(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
redis := gredis.New(config)
|
||||
defer redis.Close()
|
||||
_, err := redis.Do("SET", "k", "v")
|
||||
gtest.Assert(err, nil)
|
||||
|
||||
r, err := redis.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, []byte("v"))
|
||||
|
||||
_, err = redis.Do("DEL", "k")
|
||||
gtest.Assert(err, nil)
|
||||
r, err = redis.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Send(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
redis := gredis.New(config)
|
||||
defer redis.Close()
|
||||
err := redis.Send("SET", "k", "v")
|
||||
gtest.Assert(err, nil)
|
||||
|
||||
r, err := redis.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, []byte("v"))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Stats(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
redis := gredis.New(config)
|
||||
defer redis.Close()
|
||||
redis.SetMaxIdle(2)
|
||||
redis.SetMaxActive(100)
|
||||
redis.SetIdleTimeout(500*time.Millisecond)
|
||||
redis.SetMaxConnLifetime(500*time.Millisecond)
|
||||
|
||||
array := make([]gredis.Conn, 0)
|
||||
for i := 0; i < 10; i++ {
|
||||
array = append(array, redis.Conn())
|
||||
}
|
||||
stats := redis.Stats()
|
||||
gtest.Assert(stats.ActiveCount, 10)
|
||||
gtest.Assert(stats.IdleCount, 0)
|
||||
for i := 0; i < 10; i++ {
|
||||
array[i].Close()
|
||||
}
|
||||
stats = redis.Stats()
|
||||
gtest.Assert(stats.ActiveCount, 2)
|
||||
gtest.Assert(stats.IdleCount, 2)
|
||||
//time.Sleep(3000*time.Millisecond)
|
||||
//stats = redis.Stats()
|
||||
//fmt.Println(stats)
|
||||
//gtest.Assert(stats.ActiveCount, 0)
|
||||
//gtest.Assert(stats.IdleCount, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Conn(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
redis := gredis.New(config)
|
||||
defer redis.Close()
|
||||
conn := redis.Conn()
|
||||
defer conn.Close()
|
||||
|
||||
|
||||
r, err := conn.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, []byte("v"))
|
||||
|
||||
_, err = conn.Do("DEL", "k")
|
||||
gtest.Assert(err, nil)
|
||||
r, err = conn.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Instance(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
group := "my-test"
|
||||
gredis.SetConfig(config, group)
|
||||
defer gredis.RemoveConfig(group)
|
||||
redis := gredis.Instance(group)
|
||||
defer redis.Close()
|
||||
|
||||
conn := redis.Conn()
|
||||
defer conn.Close()
|
||||
|
||||
_, err := conn.Do("SET", "k", "v")
|
||||
gtest.Assert(err, nil)
|
||||
|
||||
r, err := conn.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, []byte("v"))
|
||||
|
||||
_, err = conn.Do("DEL", "k")
|
||||
gtest.Assert(err, nil)
|
||||
r, err = conn.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, nil)
|
||||
})
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package encoding
|
||||
@ -51,5 +51,5 @@ func ToUTF8(charset string, src string) (dst string, err error) {
|
||||
|
||||
// UTF8转指定字符集
|
||||
func UTF8To(charset string, src string) (dst string, err error) {
|
||||
return Convert(charset, "UTF-8", src)
|
||||
return Convert(charset, "UTF-8", src)
|
||||
}
|
||||
@ -1,10 +1,16 @@
|
||||
package gcharset
|
||||
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gcharset_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/encoding/gcharset"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
var testData = []struct {
|
||||
utf8, other, otherEncoding string
|
||||
}{
|
||||
@ -52,7 +58,7 @@ var testData = []struct {
|
||||
func TestDecode(t *testing.T) {
|
||||
for _, data := range testData {
|
||||
str := ""
|
||||
str, err := Convert("UTF-8", data.otherEncoding, data.other)
|
||||
str, err := gcharset.Convert("UTF-8", data.otherEncoding, data.other)
|
||||
if err != nil {
|
||||
t.Errorf("Could not create decoder for %v", err)
|
||||
continue
|
||||
@ -68,7 +74,7 @@ func TestDecode(t *testing.T) {
|
||||
func TestEncode(t *testing.T) {
|
||||
for _, data := range testData {
|
||||
str := ""
|
||||
str, err := Convert(data.otherEncoding, "UTF-8", data.utf8)
|
||||
str, err := gcharset.Convert(data.otherEncoding, "UTF-8", data.utf8)
|
||||
if err != nil {
|
||||
t.Errorf("Could not create decoder for %v", err)
|
||||
continue
|
||||
@ -86,7 +92,7 @@ func TestConvert(t *testing.T) {
|
||||
dstCharset := "gbk"
|
||||
dst := "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed"
|
||||
|
||||
str, err := Convert(dstCharset, srcCharset, src)
|
||||
str, err := gcharset.Convert(dstCharset, srcCharset, src)
|
||||
if err != nil {
|
||||
t.Errorf("convert error. %v", err)
|
||||
return
|
||||
|
||||
@ -4,10 +4,11 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gjson provides quite flexible and useful API for JSON/XML/YAML/TOML content handling.
|
||||
// Package gjson provides convenient API for JSON/XML/YAML/TOML data handling.
|
||||
package gjson
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@ -16,42 +17,48 @@ import (
|
||||
"github.com/gogf/gf/g/encoding/gyaml"
|
||||
"github.com/gogf/gf/g/internal/rwmutex"
|
||||
"github.com/gogf/gf/g/os/gfcache"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"github.com/gogf/gf/g/text/gstr"
|
||||
"github.com/gogf/gf/g/util/gconv"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
gDEFAULT_SPLIT_CHAR = '.' // 默认层级分隔符号
|
||||
// Separator char for hierarchical data access.
|
||||
gDEFAULT_SPLIT_CHAR = '.'
|
||||
)
|
||||
|
||||
// json解析结果存放数组
|
||||
// The customized JSON struct.
|
||||
type Json struct {
|
||||
mu *rwmutex.RWMutex
|
||||
p *interface{} // 注意这是一个指针
|
||||
c byte // 层级分隔符,默认为"."
|
||||
vc bool // 层级检索是否执行分隔符冲突检测(默认为false,检测会比较影响检索效率)
|
||||
p *interface{} // Pointer for hierarchical data access, it's the root of data in default.
|
||||
c byte // Char separator('.' in default).
|
||||
vc bool // Violence Check(false in default), which is used to access data
|
||||
// when the hierarchical data key contains separator char.
|
||||
}
|
||||
|
||||
// 将变量转换为Json对象进行处理,该变量至少应当是一个map或者slice,否者转换没有意义
|
||||
func New(value interface{}, unsafe...bool) *Json {
|
||||
// New creates a Json object with any variable type of <data>,
|
||||
// but <data> should be a map or slice for data access reason,
|
||||
// or it will make no sense.
|
||||
// The <unsafe> param specifies whether using this Json object
|
||||
// in un-concurrent-safe context, which is false in default.
|
||||
func New(data interface{}, unsafe...bool) *Json {
|
||||
j := (*Json)(nil)
|
||||
switch value.(type) {
|
||||
switch data.(type) {
|
||||
case map[string]interface{}, []interface{}, nil:
|
||||
j = &Json {
|
||||
p : &value,
|
||||
p : &data,
|
||||
c : byte(gDEFAULT_SPLIT_CHAR),
|
||||
vc : false ,
|
||||
}
|
||||
case string, []byte:
|
||||
j, _ = LoadContent(gconv.Bytes(value))
|
||||
j, _ = LoadContent(gconv.Bytes(data))
|
||||
default:
|
||||
v := (interface{})(nil)
|
||||
if m := gconv.Map(value); m != nil {
|
||||
if m := gconv.Map(data); m != nil {
|
||||
v = m
|
||||
j = &Json {
|
||||
p : &v,
|
||||
@ -59,7 +66,7 @@ func New(value interface{}, unsafe...bool) *Json {
|
||||
vc : false,
|
||||
}
|
||||
} else {
|
||||
v = gconv.Interfaces(value)
|
||||
v = gconv.Interfaces(data)
|
||||
j = &Json {
|
||||
p : &v,
|
||||
c : byte(gDEFAULT_SPLIT_CHAR),
|
||||
@ -71,109 +78,130 @@ func New(value interface{}, unsafe...bool) *Json {
|
||||
return j
|
||||
}
|
||||
|
||||
// 创建一个非并发安全的Json对象
|
||||
func NewUnsafe(value...interface{}) *Json {
|
||||
if len(value) > 0 {
|
||||
return New(value[0], true)
|
||||
// NewUnsafe creates a un-concurrent-safe Json object.
|
||||
func NewUnsafe(data...interface{}) *Json {
|
||||
if len(data) > 0 {
|
||||
return New(data[0], true)
|
||||
}
|
||||
return New(nil, true)
|
||||
}
|
||||
|
||||
// 编码go变量为json字符串,并返回json字符串指针
|
||||
func Encode (v interface{}) ([]byte, error) {
|
||||
return json.Marshal(v)
|
||||
// Valid checks whether <data> is a valid JSON data type.
|
||||
func Valid(data interface{}) bool {
|
||||
return json.Valid(gconv.Bytes(data))
|
||||
}
|
||||
|
||||
// 解码字符串为interface{}变量
|
||||
func Decode (b []byte) (interface{}, error) {
|
||||
var v interface{}
|
||||
if err := DecodeTo(b, &v); err != nil {
|
||||
// Encode encodes <value> to JSON data type of bytes.
|
||||
func Encode(value interface{}) ([]byte, error) {
|
||||
return json.Marshal(value)
|
||||
}
|
||||
|
||||
// Decode decodes <data>(string/[]byte) to golang variable.
|
||||
func Decode(data interface{}) (interface{}, error) {
|
||||
var value interface{}
|
||||
if err := DecodeTo(gconv.Bytes(data), &value); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return v, nil
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 解析json字符串为go变量,注意第二个参数为指针(任意结构的变量)
|
||||
func DecodeTo (b []byte, v interface{}) error {
|
||||
return json.Unmarshal(b, v)
|
||||
// Decode decodes <data>(string/[]byte) to specified golang variable <v>.
|
||||
// The <v> should be a pointer type.
|
||||
func DecodeTo(data interface{}, v interface{}) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(gconv.Bytes(data)))
|
||||
decoder.UseNumber()
|
||||
return decoder.Decode(v)
|
||||
}
|
||||
|
||||
// 解析json字符串为gjson.Json对象,并返回操作对象指针
|
||||
func DecodeToJson (b []byte) (*Json, error) {
|
||||
if v, err := Decode(b); err != nil {
|
||||
// DecodeToJson codes <data>(string/[]byte) to a Json object.
|
||||
func DecodeToJson(data interface{}, unsafe...bool) (*Json, error) {
|
||||
if v, err := Decode(gconv.Bytes(data)); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return New(v), nil
|
||||
return New(v, unsafe...), nil
|
||||
}
|
||||
}
|
||||
|
||||
// 支持多种配置文件类型转换为json格式内容并解析为gjson.Json对象
|
||||
func Load (path string) (*Json, error) {
|
||||
return LoadContent(gfcache.GetBinContents(path), gfile.Ext(path))
|
||||
// Load loads content from specified file <path>,
|
||||
// and creates a Json object from its content.
|
||||
func Load(path string, unsafe...bool) (*Json, error) {
|
||||
return LoadContent(gfcache.GetBinContents(path), unsafe...)
|
||||
}
|
||||
|
||||
// 支持的配置文件格式:xml, json, yaml/yml, toml,
|
||||
// 默认为自动识别,当无法检测成功时使用json解析。
|
||||
func LoadContent(data []byte, dataType...string) (*Json, error) {
|
||||
// LoadContent creates a Json object from given content,
|
||||
// it checks the data type of <content> automatically,
|
||||
// supporting JSON, XML, YAML and TOML types of data.
|
||||
func LoadContent(data interface{}, unsafe...bool) (*Json, error) {
|
||||
var err error
|
||||
var result interface{}
|
||||
b := gconv.Bytes(data)
|
||||
t := "json"
|
||||
if len(dataType) > 0 {
|
||||
t = dataType[0]
|
||||
// auto check data type
|
||||
if json.Valid(b) {
|
||||
t = "json"
|
||||
} else if gregex.IsMatch(`^<.+>.*</.+>$`, b) {
|
||||
t = "xml"
|
||||
} else if gregex.IsMatch(`^[\s\t]*\w+\s*:\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*:\s*.+`, b) {
|
||||
t = "yml"
|
||||
} else if gregex.IsMatch(`^[\s\t]*\w+\s*=\s*.+`, b) || gregex.IsMatch(`\n[\s\t]*\w+\s*=\s*.+`, b) {
|
||||
t = "toml"
|
||||
} else {
|
||||
if gregex.IsMatch(`<.+>.*</.+>`, data) {
|
||||
t = "xml"
|
||||
} else if gregex.IsMatch(`\w+\s*:\s*\w+`, data) {
|
||||
t = "yml"
|
||||
} else if gregex.IsMatch(`\w+\s*=\s*\w+`, data) {
|
||||
t = "toml"
|
||||
}
|
||||
return nil, errors.New("unsupported data type")
|
||||
}
|
||||
// convert to json type data
|
||||
switch t {
|
||||
case "xml", ".xml":
|
||||
data, err = gxml.ToJson(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "json", ".json":
|
||||
// ok
|
||||
case "xml", ".xml":
|
||||
// TODO UseNumber
|
||||
b, err = gxml.ToJson(b)
|
||||
|
||||
case "yml", "yaml", ".yml", ".yaml":
|
||||
data, err = gyaml.ToJson(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "yml", "yaml", ".yml", ".yaml":
|
||||
// TODO UseNumber
|
||||
b, err = gyaml.ToJson(b)
|
||||
|
||||
case "toml", ".toml":
|
||||
data, err = gtoml.ToJson(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "toml", ".toml":
|
||||
// TODO UseNumber
|
||||
b, err = gtoml.ToJson(b)
|
||||
|
||||
default:
|
||||
err = errors.New("nonsupport type " + t)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result == nil {
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
decoder := json.NewDecoder(bytes.NewReader(b))
|
||||
decoder.UseNumber()
|
||||
if err := decoder.Decode(&result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch result.(type) {
|
||||
case string, []byte:
|
||||
return nil, fmt.Errorf(`json decoding failed for content: %s`, string(b))
|
||||
}
|
||||
}
|
||||
return New(result), nil
|
||||
return New(result, unsafe...), nil
|
||||
}
|
||||
|
||||
// 设置自定义的层级分隔符号
|
||||
// SetSplitChar sets the separator char for hierarchical data access.
|
||||
func (j *Json) SetSplitChar(char byte) {
|
||||
j.mu.Lock()
|
||||
j.c = char
|
||||
j.mu.Unlock()
|
||||
}
|
||||
|
||||
// 设置是否执行层级冲突检查,当键名中存在层级符号时需要开启该特性,默认为关闭。
|
||||
// 开启比较耗性能,也不建议允许键名中存在分隔符,最好在应用端避免这种情况。
|
||||
func (j *Json) SetViolenceCheck(check bool) {
|
||||
// SetViolenceCheck enables/disables violence check for hierarchical data access.
|
||||
func (j *Json) SetViolenceCheck(enabled bool) {
|
||||
j.mu.Lock()
|
||||
j.vc = check
|
||||
j.vc = enabled
|
||||
j.mu.Unlock()
|
||||
}
|
||||
|
||||
// 将指定的json内容转换为指定结构返回,查找失败或者转换失败,目标对象转换为nil
|
||||
// 注意第二个参数需要给的是**变量地址**
|
||||
// GetToVar gets the value by specified <pattern>,
|
||||
// and converts it to specified golang variable <v>.
|
||||
// The <v> should be a pointer type.
|
||||
func (j *Json) GetToVar(pattern string, v interface{}) error {
|
||||
r := j.Get(pattern)
|
||||
if r != nil {
|
||||
@ -188,19 +216,18 @@ func (j *Json) GetToVar(pattern string, v interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获得一个键值对关联数组/哈希表,方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
// GetMap gets the value by specified <pattern>,
|
||||
// and converts it to map[string]interface{}.
|
||||
func (j *Json) GetMap(pattern string) map[string]interface{} {
|
||||
result := j.Get(pattern)
|
||||
if result != nil {
|
||||
if r, ok := result.(map[string]interface{}); ok {
|
||||
return r
|
||||
}
|
||||
return gconv.Map(result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 将检索值转换为Json对象指针返回
|
||||
// GetJson gets the value by specified <pattern>,
|
||||
// and converts it to a Json object.
|
||||
func (j *Json) GetJson(pattern string) *Json {
|
||||
result := j.Get(pattern)
|
||||
if result != nil {
|
||||
@ -209,28 +236,39 @@ func (j *Json) GetJson(pattern string) *Json {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获得一个数组[]interface{},方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
func (j *Json) GetArray(pattern string) []interface{} {
|
||||
result := j.Get(pattern)
|
||||
if result != nil {
|
||||
if r, ok := result.([]interface{}); ok {
|
||||
return r
|
||||
// GetJsons gets the value by specified <pattern>,
|
||||
// and converts it to a slice of Json object.
|
||||
func (j *Json) GetJsons(pattern string) []*Json {
|
||||
array := j.GetArray(pattern)
|
||||
if len(array) > 0 {
|
||||
jsons := make([]*Json, len(array))
|
||||
for i := 0; i < len(array); i++ {
|
||||
jsons[i] = New(array[i], !j.mu.IsSafe())
|
||||
}
|
||||
return jsons
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回指定json中的string
|
||||
// GetArray gets the value by specified <pattern>,
|
||||
// and converts it to a slice of []interface{}.
|
||||
func (j *Json) GetArray(pattern string) []interface{} {
|
||||
return gconv.Interfaces(j.Get(pattern))
|
||||
}
|
||||
|
||||
// GetString gets the value by specified <pattern>,
|
||||
// and converts it to string.
|
||||
func (j *Json) GetString(pattern string) string {
|
||||
return gconv.String(j.Get(pattern))
|
||||
}
|
||||
|
||||
// 返回指定json中的strings(转换为[]string数组)
|
||||
// GetStrings gets the value by specified <pattern>,
|
||||
// and converts it to a slice of []string.
|
||||
func (j *Json) GetStrings(pattern string) []string {
|
||||
return gconv.Strings(j.Get(pattern))
|
||||
}
|
||||
|
||||
// See GetArray.
|
||||
func (j *Json) GetInterfaces(pattern string) []interface{} {
|
||||
return gconv.Interfaces(j.Get(pattern))
|
||||
}
|
||||
@ -243,7 +281,10 @@ func (j *Json) GetTimeDuration(pattern string) time.Duration {
|
||||
return gconv.TimeDuration(j.Get(pattern))
|
||||
}
|
||||
|
||||
// 返回指定json中的bool(false:"", 0, false, off)
|
||||
// GetBool gets the value by specified <pattern>,
|
||||
// and converts it to bool.
|
||||
// It returns false when value is: "", 0, false, off, nil;
|
||||
// or returns true instead.
|
||||
func (j *Json) GetBool(pattern string) bool {
|
||||
return gconv.Bool(j.Get(pattern))
|
||||
}
|
||||
@ -304,25 +345,29 @@ func (j *Json) GetFloats(pattern string) []float64 {
|
||||
return gconv.Floats(j.Get(pattern))
|
||||
}
|
||||
|
||||
// 将指定变量转换为struct对象(对象属性赋值)
|
||||
// GetToStruct gets the value by specified <pattern>,
|
||||
// and converts it to specified object <objPointer>.
|
||||
// The <objPointer> should be the pointer to an object.
|
||||
func (j *Json) GetToStruct(pattern string, objPointer interface{}) error {
|
||||
return gconv.Struct(j.Get(pattern), objPointer)
|
||||
}
|
||||
|
||||
// 动态设置层级变量
|
||||
// Set sets value with specified <pattern>.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
func (j *Json) Set(pattern string, value interface{}) error {
|
||||
return j.setValue(pattern, value, false)
|
||||
}
|
||||
|
||||
// 动态删除层级变量
|
||||
// Remove deletes value with specified <pattern>.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
func (j *Json) Remove(pattern string) error {
|
||||
return j.setValue(pattern, nil, true)
|
||||
}
|
||||
|
||||
// 根据pattern查找并设置数据
|
||||
// 注意:
|
||||
// 1、写入的value为nil且removed为true时,表示删除;
|
||||
// 2、里面的层级处理比较复杂,逻辑较复杂的地方在于层级检索及节点创建,叶子赋值;
|
||||
// Set <value> by <pattern>.
|
||||
// Notice:
|
||||
// 1. If value is nil and removed is true, means deleting this value;
|
||||
// 2. It's quite complicated in hierarchical data search, node creating and data assignment;
|
||||
func (j *Json) setValue(pattern string, value interface{}, removed bool) error {
|
||||
array := strings.Split(pattern, string(j.c))
|
||||
length := len(array)
|
||||
@ -341,187 +386,202 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error {
|
||||
defer j.mu.Unlock()
|
||||
for i:= 0; i < length; i++ {
|
||||
switch (*pointer).(type) {
|
||||
case map[string]interface{}:
|
||||
if i == length - 1 {
|
||||
if removed && value == nil {
|
||||
// 删除map元素
|
||||
delete((*pointer).(map[string]interface{}), array[i])
|
||||
} else {
|
||||
(*pointer).(map[string]interface{})[array[i]] = value
|
||||
}
|
||||
} else {
|
||||
// 当键名不存在的情况这里会进行处理
|
||||
if v, ok := (*pointer).(map[string]interface{})[array[i]]; !ok {
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
// 创建新节点
|
||||
if gstr.IsNumeric(array[i + 1]) {
|
||||
// 创建array节点
|
||||
n, _ := strconv.Atoi(array[i + 1])
|
||||
var v interface{} = make([]interface{}, n + 1)
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
} else {
|
||||
// 创建map节点
|
||||
var v interface{} = make(map[string]interface{})
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
}
|
||||
} else {
|
||||
pparent = pointer
|
||||
pointer = &v
|
||||
}
|
||||
}
|
||||
|
||||
case []interface{}:
|
||||
// 键名与当前指针类型不符合,需要执行**覆盖操作**
|
||||
if !gstr.IsNumeric(array[i]) {
|
||||
case map[string]interface{}:
|
||||
if i == length - 1 {
|
||||
*pointer = map[string]interface{}{ array[i] : value }
|
||||
if removed && value == nil {
|
||||
// 删除map元素
|
||||
delete((*pointer).(map[string]interface{}), array[i])
|
||||
} else {
|
||||
(*pointer).(map[string]interface{})[array[i]] = value
|
||||
}
|
||||
} else {
|
||||
var v interface{} = make(map[string]interface{})
|
||||
*pointer = v
|
||||
pparent = pointer
|
||||
pointer = &v
|
||||
// 当键名不存在的情况这里会进行处理
|
||||
if v, ok := (*pointer).(map[string]interface{})[array[i]]; !ok {
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
// 创建新节点
|
||||
if gstr.IsNumeric(array[i + 1]) {
|
||||
// 创建array节点
|
||||
n, _ := strconv.Atoi(array[i + 1])
|
||||
var v interface{} = make([]interface{}, n + 1)
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
} else {
|
||||
// 创建map节点
|
||||
var v interface{} = make(map[string]interface{})
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
}
|
||||
} else {
|
||||
pparent = pointer
|
||||
pointer = &v
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
valn, err := strconv.Atoi(array[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 叶子节点
|
||||
if i == length - 1 {
|
||||
if len((*pointer).([]interface{})) > valn {
|
||||
if removed && value == nil {
|
||||
// 删除数据元素
|
||||
j.setPointerWithValue(pparent, array[i - 1], append((*pointer).([]interface{})[ : valn], (*pointer).([]interface{})[valn + 1 : ]...))
|
||||
case []interface{}:
|
||||
// 键名与当前指针类型不符合,需要执行**覆盖操作**
|
||||
if !gstr.IsNumeric(array[i]) {
|
||||
if i == length - 1 {
|
||||
*pointer = map[string]interface{}{ array[i] : value }
|
||||
} else {
|
||||
(*pointer).([]interface{})[valn] = value
|
||||
}
|
||||
} else {
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
if pparent == nil {
|
||||
// 表示根节点
|
||||
j.setPointerWithValue(pointer, array[i], value)
|
||||
} else {
|
||||
// 非根节点
|
||||
s := make([]interface{}, valn + 1)
|
||||
copy(s, (*pointer).([]interface{}))
|
||||
s[valn] = value
|
||||
j.setPointerWithValue(pparent, array[i - 1], s)
|
||||
var v interface{} = make(map[string]interface{})
|
||||
*pointer = v
|
||||
pparent = pointer
|
||||
pointer = &v
|
||||
}
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if gstr.IsNumeric(array[i + 1]) {
|
||||
n, _ := strconv.Atoi(array[i + 1])
|
||||
|
||||
valn, err := strconv.Atoi(array[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 叶子节点
|
||||
if i == length - 1 {
|
||||
if len((*pointer).([]interface{})) > valn {
|
||||
(*pointer).([]interface{})[valn] = make([]interface{}, n + 1)
|
||||
pparent = pointer
|
||||
pointer = &(*pointer).([]interface{})[valn]
|
||||
if removed && value == nil {
|
||||
// 删除数据元素
|
||||
j.setPointerWithValue(pparent, array[i - 1], append((*pointer).([]interface{})[ : valn], (*pointer).([]interface{})[valn + 1 : ]...))
|
||||
} else {
|
||||
(*pointer).([]interface{})[valn] = value
|
||||
}
|
||||
} else {
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
var v interface{} = make([]interface{}, n + 1)
|
||||
if pparent == nil {
|
||||
// 表示根节点
|
||||
j.setPointerWithValue(pointer, array[i], value)
|
||||
} else {
|
||||
// 非根节点
|
||||
s := make([]interface{}, valn + 1)
|
||||
copy(s, (*pointer).([]interface{}))
|
||||
s[valn] = value
|
||||
j.setPointerWithValue(pparent, array[i - 1], s)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if gstr.IsNumeric(array[i + 1]) {
|
||||
n, _ := strconv.Atoi(array[i + 1])
|
||||
if len((*pointer).([]interface{})) > valn {
|
||||
(*pointer).([]interface{})[valn] = make([]interface{}, n + 1)
|
||||
pparent = pointer
|
||||
pointer = &(*pointer).([]interface{})[valn]
|
||||
} else {
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
var v interface{} = make([]interface{}, n + 1)
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
}
|
||||
} else {
|
||||
var v interface{} = make(map[string]interface{})
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
}
|
||||
} else {
|
||||
var v interface{} = make(map[string]interface{})
|
||||
pparent = j.setPointerWithValue(pointer, array[i], v)
|
||||
pointer = &v
|
||||
}
|
||||
}
|
||||
|
||||
// 如果当前指针指向的变量不是引用类型的,
|
||||
// 那么修改变量必须通过父级进行修改,即 pparent
|
||||
default:
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
if gstr.IsNumeric(array[i]) {
|
||||
n, _ := strconv.Atoi(array[i])
|
||||
s := make([]interface{}, n + 1)
|
||||
if i == length - 1 {
|
||||
s[n] = value
|
||||
default:
|
||||
if removed && value == nil {
|
||||
goto done
|
||||
}
|
||||
if pparent != nil {
|
||||
pparent = j.setPointerWithValue(pparent, array[i - 1], s)
|
||||
} else {
|
||||
*pointer = s
|
||||
pparent = pointer
|
||||
}
|
||||
} else {
|
||||
var v interface{} = make(map[string]interface{})
|
||||
if i == length - 1 {
|
||||
v = map[string]interface{}{
|
||||
array[i] : value,
|
||||
if gstr.IsNumeric(array[i]) {
|
||||
n, _ := strconv.Atoi(array[i])
|
||||
s := make([]interface{}, n + 1)
|
||||
if i == length - 1 {
|
||||
s[n] = value
|
||||
}
|
||||
if pparent != nil {
|
||||
pparent = j.setPointerWithValue(pparent, array[i - 1], s)
|
||||
} else {
|
||||
*pointer = s
|
||||
pparent = pointer
|
||||
}
|
||||
}
|
||||
if pparent != nil {
|
||||
pparent = j.setPointerWithValue(pparent, array[i - 1], v)
|
||||
} else {
|
||||
*pointer = v
|
||||
pparent = pointer
|
||||
var v interface{} = make(map[string]interface{})
|
||||
if i == length - 1 {
|
||||
v = map[string]interface{}{
|
||||
array[i] : value,
|
||||
}
|
||||
}
|
||||
if pparent != nil {
|
||||
pparent = j.setPointerWithValue(pparent, array[i - 1], v)
|
||||
} else {
|
||||
*pointer = v
|
||||
pparent = pointer
|
||||
}
|
||||
pointer = &v
|
||||
}
|
||||
pointer = &v
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
done:
|
||||
return nil
|
||||
}
|
||||
|
||||
// 数据结构转换,map参数必须转换为map[string]interface{},数组参数必须转换为[]interface{}
|
||||
// Convert <value> to map[string]interface{} or []interface{},
|
||||
// which can be supported for hierarchical data access.
|
||||
func (j *Json) convertValue(value interface{}) interface{} {
|
||||
switch value.(type) {
|
||||
case map[string]interface{}:
|
||||
return value
|
||||
case []interface{}:
|
||||
return value
|
||||
default:
|
||||
// 这里效率会比较低,当然比直接用反射也不会差到哪儿去
|
||||
// 为了操作的灵活性,牺牲了一定的效率
|
||||
b, _ := Encode(value)
|
||||
v, _ := Decode(b)
|
||||
return v
|
||||
case map[string]interface{}:
|
||||
return value
|
||||
case []interface{}:
|
||||
return value
|
||||
default:
|
||||
rv := reflect.ValueOf(value)
|
||||
kind := rv.Kind()
|
||||
if kind == reflect.Ptr {
|
||||
rv = rv.Elem()
|
||||
kind = rv.Kind()
|
||||
}
|
||||
switch kind {
|
||||
case reflect.Array: return gconv.Interfaces(value)
|
||||
case reflect.Slice: return gconv.Interfaces(value)
|
||||
case reflect.Map: return gconv.Map(value)
|
||||
case reflect.Struct: return gconv.Map(value)
|
||||
default:
|
||||
// Use json decode/encode at last.
|
||||
b, _ := Encode(value)
|
||||
v, _ := Decode(b)
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 用于Set方法中,对指针指向的内存地址进行赋值
|
||||
// 返回修改后的父级指针
|
||||
// Set <key>:<value> to <pointer>, the <key> may be a map key or slice index.
|
||||
// It returns the pointer to the new value set.
|
||||
func (j *Json) setPointerWithValue(pointer *interface{}, key string, value interface{}) *interface{} {
|
||||
switch (*pointer).(type) {
|
||||
case map[string]interface{}:
|
||||
(*pointer).(map[string]interface{})[key] = value
|
||||
return &value
|
||||
case []interface{}:
|
||||
n, _ := strconv.Atoi(key)
|
||||
if len((*pointer).([]interface{})) > n {
|
||||
(*pointer).([]interface{})[n] = value
|
||||
return &(*pointer).([]interface{})[n]
|
||||
} else {
|
||||
s := make([]interface{}, n + 1)
|
||||
copy(s, (*pointer).([]interface{}))
|
||||
s[n] = value
|
||||
*pointer = s
|
||||
return &s[n]
|
||||
}
|
||||
default:
|
||||
*pointer = value
|
||||
case map[string]interface{}:
|
||||
(*pointer).(map[string]interface{})[key] = value
|
||||
return &value
|
||||
case []interface{}:
|
||||
n, _ := strconv.Atoi(key)
|
||||
if len((*pointer).([]interface{})) > n {
|
||||
(*pointer).([]interface{})[n] = value
|
||||
return &(*pointer).([]interface{})[n]
|
||||
} else {
|
||||
s := make([]interface{}, n + 1)
|
||||
copy(s, (*pointer).([]interface{}))
|
||||
s[n] = value
|
||||
*pointer = s
|
||||
return &s[n]
|
||||
}
|
||||
default:
|
||||
*pointer = value
|
||||
}
|
||||
return pointer
|
||||
}
|
||||
|
||||
// 根据约定字符串方式访问json解析数据,参数形如: "items.name.first", "list.0"; 当pattern为空时,表示获取所有数据;
|
||||
// 返回的结果类型的interface{},因此需要自己做类型转换;
|
||||
// 如果找不到对应节点的数据,返回nil;
|
||||
// Get returns value by specified <pattern>.
|
||||
// It returns all values of current Json object, if <pattern> is empty or not specified.
|
||||
// It returns nil if no value found by <pattern>.
|
||||
//
|
||||
// We can also access slice item by its index number in <pattern>,
|
||||
// eg: "items.name.first", "list.10".
|
||||
func (j *Json) Get(pattern...string) interface{} {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
@ -534,7 +594,7 @@ func (j *Json) Get(pattern...string) interface{} {
|
||||
if j.vc {
|
||||
result = j.getPointerByPattern(queryPattern)
|
||||
} else {
|
||||
result = j.getPointerByPatternWithoutSplitCharViolenceCheck(queryPattern)
|
||||
result = j.getPointerByPatternWithoutViolenceCheck(queryPattern)
|
||||
}
|
||||
if result != nil {
|
||||
return *result
|
||||
@ -542,49 +602,57 @@ func (j *Json) Get(pattern...string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 判断锁给定pattern是否数据存在
|
||||
// Contains checks whether the value by specified <pattern> exist.
|
||||
func (j *Json) Contains(pattern...string) bool {
|
||||
return j.Get(pattern...) != nil
|
||||
}
|
||||
|
||||
// 计算指定pattern的元素长度(pattern对应数据类型为map[string]interface{}/[]interface{}时有效)
|
||||
// Len returns the length/size of the value by specified <pattern>.
|
||||
// The target value by <pattern> should be type of slice or map.
|
||||
// It returns -1 if the target value is not found, or its type is invalid.
|
||||
func (j *Json) Len(pattern string) int {
|
||||
p := j.getPointerByPattern(pattern)
|
||||
if p != nil {
|
||||
switch (*p).(type) {
|
||||
case map[string]interface{}:
|
||||
return len((*p).(map[string]interface{}))
|
||||
case []interface{}:
|
||||
return len((*p).([]interface{}))
|
||||
default:
|
||||
return -1
|
||||
case map[string]interface{}:
|
||||
return len((*p).(map[string]interface{}))
|
||||
case []interface{}:
|
||||
return len((*p).([]interface{}))
|
||||
default:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// 指定pattern追加元素
|
||||
// Append appends value to the value by specified <pattern>.
|
||||
// The target value by <pattern> should be type of slice.
|
||||
func (j *Json) Append(pattern string, value interface{}) error {
|
||||
length := j.Len(pattern)
|
||||
if length != -1 {
|
||||
return j.Set(fmt.Sprintf("%s.%d", pattern, length), value)
|
||||
p := j.getPointerByPattern(pattern)
|
||||
if p == nil {
|
||||
return j.Set(fmt.Sprintf("%s.0", pattern), value)
|
||||
}
|
||||
return errors.New(fmt.Sprintf("cannot find item for pattern: %s", pattern))
|
||||
switch (*p).(type) {
|
||||
case []interface{}:
|
||||
return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value)
|
||||
}
|
||||
return fmt.Errorf("invalid variable type of %s", pattern)
|
||||
}
|
||||
|
||||
// 根据pattern层级查找**变量指针**
|
||||
// 检索方式:例如检索 a.a.a ,值为1
|
||||
// 1. 检索 a.a.a.a 是否存在对应map的键名;
|
||||
// 2. 检索 a.a.a 是否存在对应map的键名;
|
||||
// 3. 检索 a.a 是否存在对应map的键名;
|
||||
// 4. 检索 a 是否存在对应map的键名,如果检索出这是一个map,假如为变量m1;
|
||||
// 5. 在m1中检索 a.a.a 否存在对应map的键名;
|
||||
// 6. 在m1中检索 a.a 否存在对应map的键名;
|
||||
// 7. 在m1中检索 a 否存在对应map的键名,如果检索出这是一个map,假如为变量m2;
|
||||
// 8. 在m2中检索 a.a 否存在对应map的键名;
|
||||
// 9. 在m2中检索 a 否存在对应map的键名,检索到有值,值为1;
|
||||
// 这样检索的复杂度很高,主要是为了避免键名中存在分隔符号(默认为".")的情况,避免歧义。
|
||||
// Get a pointer to the value by specified <pattern>.
|
||||
func (j *Json) getPointerByPattern(pattern string) *interface{} {
|
||||
if j.vc {
|
||||
return j.getPointerByPatternWithViolenceCheck(pattern)
|
||||
} else {
|
||||
return j.getPointerByPatternWithoutViolenceCheck(pattern)
|
||||
}
|
||||
}
|
||||
|
||||
// Get a pointer to the value of specified <pattern> with violence check.
|
||||
func (j *Json) getPointerByPatternWithViolenceCheck(pattern string) *interface{} {
|
||||
if !j.vc {
|
||||
return j.getPointerByPatternWithoutViolenceCheck(pattern)
|
||||
}
|
||||
index := len(pattern)
|
||||
start := 0
|
||||
length := 0
|
||||
@ -606,7 +674,7 @@ func (j *Json) getPointerByPattern(pattern string) *interface{} {
|
||||
pointer = r
|
||||
}
|
||||
} else {
|
||||
// 查找下一个分割符号的索引位置
|
||||
// Get the position for next separator char.
|
||||
index = strings.LastIndexByte(pattern[start:index], j.c)
|
||||
if index != -1 && length > 0 {
|
||||
index += length + 1
|
||||
@ -619,8 +687,11 @@ func (j *Json) getPointerByPattern(pattern string) *interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 层级检索,内部不执行分隔符冲突检查,检索效率会有所提高,但是冲突需要开发者自己根据自定义的分隔符来进行解决
|
||||
func (j *Json) getPointerByPatternWithoutSplitCharViolenceCheck(pattern string) *interface{} {
|
||||
// Get a pointer to the value of specified <pattern>, with no violence check.
|
||||
func (j *Json) getPointerByPatternWithoutViolenceCheck(pattern string) *interface{} {
|
||||
if j.vc {
|
||||
return j.getPointerByPatternWithViolenceCheck(pattern)
|
||||
}
|
||||
pointer := j.p
|
||||
if len(pattern) == 0 {
|
||||
return pointer
|
||||
@ -640,26 +711,27 @@ func (j *Json) getPointerByPatternWithoutSplitCharViolenceCheck(pattern string)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 判断给定的key在当前的pointer下是否有值,并返回对应的pointer
|
||||
// 注意这里返回的指针都是临时变量的内存地址
|
||||
// Check whether there's value by <key> in specified <pointer>.
|
||||
// It returns a pointer to the value.
|
||||
func (j *Json) checkPatternByPointer(key string, pointer *interface{}) *interface{} {
|
||||
switch (*pointer).(type) {
|
||||
case map[string]interface{}:
|
||||
if v, ok := (*pointer).(map[string]interface{})[key]; ok {
|
||||
return &v
|
||||
}
|
||||
case []interface{}:
|
||||
if gstr.IsNumeric(key) {
|
||||
n, err := strconv.Atoi(key)
|
||||
if err == nil && len((*pointer).([]interface{})) > n {
|
||||
return &(*pointer).([]interface{})[n]
|
||||
case map[string]interface{}:
|
||||
if v, ok := (*pointer).(map[string]interface{})[key]; ok {
|
||||
return &v
|
||||
}
|
||||
case []interface{}:
|
||||
if gstr.IsNumeric(key) {
|
||||
n, err := strconv.Atoi(key)
|
||||
if err == nil && len((*pointer).([]interface{})) > n {
|
||||
return &(*pointer).([]interface{})[n]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 转换为map[string]interface{}类型,如果转换失败,返回nil
|
||||
// ToMap converts current Json object to map[string]interface{}.
|
||||
// It returns nil if fails.
|
||||
func (j *Json) ToMap() map[string]interface{} {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
@ -671,15 +743,16 @@ func (j *Json) ToMap() map[string]interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// 转换为[]interface{}类型,如果转换失败,返回nil
|
||||
// ToArray converts current Json object to []interface{}.
|
||||
// It returns nil if fails.
|
||||
func (j *Json) ToArray() []interface{} {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
switch (*(j.p)).(type) {
|
||||
case []interface{}:
|
||||
return (*(j.p)).([]interface{})
|
||||
default:
|
||||
return nil
|
||||
case []interface{}:
|
||||
return (*(j.p)).([]interface{})
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@ -687,42 +760,73 @@ func (j *Json) ToXml(rootTag...string) ([]byte, error) {
|
||||
return gxml.Encode(j.ToMap(), rootTag...)
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlString(rootTag...string) (string, error) {
|
||||
b, e := j.ToXml(rootTag...)
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlIndent(rootTag...string) ([]byte, error) {
|
||||
return gxml.EncodeWithIndent(j.ToMap(), rootTag...)
|
||||
}
|
||||
|
||||
func (j *Json) ToXmlIndentString(rootTag...string) (string, error) {
|
||||
b, e := j.ToXmlIndent(rootTag...)
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
func (j *Json) ToJson() ([]byte, error) {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return Encode(*(j.p))
|
||||
}
|
||||
|
||||
func (j *Json) ToJsonString() (string, error) {
|
||||
b, e := j.ToJson()
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
func (j *Json) ToJsonIndent() ([]byte, error) {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return json.MarshalIndent(*(j.p), "", "\t")
|
||||
}
|
||||
|
||||
func (j *Json) ToJsonIndentString() (string, error) {
|
||||
b, e := j.ToJsonIndent()
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
func (j *Json) ToYaml() ([]byte, error) {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gyaml.Encode(*(j.p))
|
||||
}
|
||||
|
||||
func (j *Json) ToYamlString() (string, error) {
|
||||
b, e := j.ToYaml()
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
func (j *Json) ToToml() ([]byte, error) {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gtoml.Encode(*(j.p))
|
||||
}
|
||||
|
||||
// 转换为指定的struct对象
|
||||
func (j *Json) ToStruct(o interface{}) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Struct(*(j.p), o)
|
||||
func (j *Json) ToTomlString() (string, error) {
|
||||
b, e := j.ToToml()
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
// 打印Json对象
|
||||
// ToStruct converts current Json object to specified object.
|
||||
// The <objPointer> should be a pointer type.
|
||||
func (j *Json) ToStruct(objPointer interface{}) error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return gconv.Struct(*(j.p), objPointer)
|
||||
}
|
||||
|
||||
// Dump prints current Json object with more manually readable.
|
||||
func (j *Json) Dump() error {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
|
||||
30
g/encoding/gjson/gjson_bench_test.go
Normal file
30
g/encoding/gjson/gjson_bench_test.go
Normal file
@ -0,0 +1,30 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gjson_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Benchmark_Set1(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
p := gjson.New(map[string]string{
|
||||
"k1" : "v1",
|
||||
"k2" : "v2",
|
||||
})
|
||||
p.Set("k1.k11", []int{1,2,3})
|
||||
}
|
||||
}
|
||||
|
||||
func Benchmark_Set2(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", []int{1,2,3})
|
||||
}
|
||||
}
|
||||
|
||||
253
g/encoding/gjson/gjson_unit_basic_test.go
Normal file
253
g/encoding/gjson/gjson_unit_basic_test.go
Normal file
@ -0,0 +1,253 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gjson_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g"
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_New(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gjson.New(data)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_NewUnsafe(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gjson.NewUnsafe(data)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Valid(t *testing.T) {
|
||||
data1 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
data2 := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]`)
|
||||
gtest.Case(t, func() {
|
||||
gtest.Assert(gjson.Valid(data1), true)
|
||||
gtest.Assert(gjson.Valid(data2), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Encode(t *testing.T) {
|
||||
value := g.Slice{1, 2, 3}
|
||||
gtest.Case(t, func() {
|
||||
b, err := gjson.Encode(value)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(b, []byte(`[1,2,3]`))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Decode(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
v, err := gjson.Decode(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(v, g.Map{
|
||||
"n" : 123456789,
|
||||
"a" : g.Slice{1, 2, 3},
|
||||
"m" : g.Map{
|
||||
"k" : "v",
|
||||
},
|
||||
})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
var v interface{}
|
||||
err := gjson.DecodeTo(data, &v)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(v, g.Map{
|
||||
"n" : 123456789,
|
||||
"a" : g.Slice{1, 2, 3},
|
||||
"m" : g.Map{
|
||||
"k" : "v",
|
||||
},
|
||||
})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_SplitChar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
j.SetSplitChar(byte('#'))
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m#k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a#1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ViolenceCheck(t *testing.T) {
|
||||
data := []byte(`{"m":{"a":[1,2,3], "v1.v2":"4"}}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("m.a.2"), 3)
|
||||
gtest.Assert(j.Get("m.v1.v2"), nil)
|
||||
j.SetViolenceCheck(true)
|
||||
gtest.Assert(j.Get("m.v1.v2"), 4)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetToVar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
var m map[string]string
|
||||
var n int
|
||||
var a []int
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
|
||||
j.GetToVar("n", &n)
|
||||
j.GetToVar("m", &m)
|
||||
j.GetToVar("a", &a)
|
||||
|
||||
gtest.Assert(n, "123456789")
|
||||
gtest.Assert(m, g.Map{"k" : "v"})
|
||||
gtest.Assert(a, g.Slice{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetMap(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.GetMap("n"), nil)
|
||||
gtest.Assert(j.GetMap("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.GetMap("a"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetJson(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
j2 := j.GetJson("m")
|
||||
gtest.AssertNE(j2, nil)
|
||||
gtest.Assert(j2.Get("k"), "v")
|
||||
gtest.Assert(j2.Get("a"), nil)
|
||||
gtest.Assert(j2.Get("n"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetArray(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.GetArray("n"), g.Array{123456789})
|
||||
gtest.Assert(j.GetArray("m"), g.Array{g.Map{"k":"v"}})
|
||||
gtest.Assert(j.GetArray("a"), g.Array{1,2,3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetString(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.AssertEQ(j.GetString("n"), "123456789")
|
||||
gtest.AssertEQ(j.GetString("m"), `{"k":"v"}`)
|
||||
gtest.AssertEQ(j.GetString("a"), `[1,2,3]`)
|
||||
gtest.AssertEQ(j.GetString("i"), "")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetStrings(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.AssertEQ(j.GetStrings("n"), g.SliceStr{"123456789"})
|
||||
gtest.AssertEQ(j.GetStrings("m"), g.SliceStr{`{"k":"v"}`})
|
||||
gtest.AssertEQ(j.GetStrings("a"), g.SliceStr{"1", "2", "3"})
|
||||
gtest.AssertEQ(j.GetStrings("i"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetInterfaces(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.DecodeToJson(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.AssertEQ(j.GetInterfaces("n"), g.Array{123456789})
|
||||
gtest.AssertEQ(j.GetInterfaces("m"), g.Array{g.Map{"k":"v"}})
|
||||
gtest.AssertEQ(j.GetInterfaces("a"), g.Array{1,2,3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Len(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
gtest.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
gtest.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Set("a", 1)
|
||||
gtest.Assert(p.Len("a"), -1)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Append(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
gtest.Assert(p.Get("a"), g.Slice{1, 2})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
gtest.Assert(p.Get("a"), g.Map{
|
||||
"b" : g.Slice{1},
|
||||
"c" : g.Slice{2},
|
||||
})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gjson.New(nil)
|
||||
p.Set("a", 1)
|
||||
err := p.Append("a", 2)
|
||||
gtest.AssertNE(err, nil)
|
||||
gtest.Assert(p.Get("a"), 1)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
156
g/encoding/gjson/gjson_unit_load_test.go
Normal file
156
g/encoding/gjson/gjson_unit_load_test.go
Normal file
@ -0,0 +1,156 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gjson_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g"
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
func Test_Load_JSON(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
// JSON
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// JSON
|
||||
gtest.Case(t, func() {
|
||||
path := "test.json"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_XML(t *testing.T) {
|
||||
data := []byte(`<doc><a>1</a><a>2</a><a>3</a><m><k>v</k></m><n>123456789</n></doc>`)
|
||||
// XML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("doc.n"), "123456789")
|
||||
gtest.Assert(j.Get("doc.m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("doc.m.k"), "v")
|
||||
gtest.Assert(j.Get("doc.a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
// XML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.xml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("doc.n"), "123456789")
|
||||
gtest.Assert(j.Get("doc.m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("doc.m.k"), "v")
|
||||
gtest.Assert(j.Get("doc.a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
m:
|
||||
k: v
|
||||
"n": 123456789
|
||||
`)
|
||||
// YAML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// YAML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.yaml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML2(t *testing.T) {
|
||||
data := []byte("i : 123456789")
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a = ["1", "2", "3"]
|
||||
n = "123456789"
|
||||
|
||||
[m]
|
||||
k = "v"
|
||||
`)
|
||||
// TOML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// TOML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.toml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gjson.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML2(t *testing.T) {
|
||||
data := []byte("i=123456789")
|
||||
gtest.Case(t, func() {
|
||||
j, err := gjson.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
230
g/encoding/gjson/gjson_unit_set_test.go
Normal file
230
g/encoding/gjson/gjson_unit_set_test.go
Normal file
@ -0,0 +1,230 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gjson_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Set1(t *testing.T) {
|
||||
e := []byte(`{"k1":{"k11":[1,2,3]},"k2":"v2"}`)
|
||||
p := gjson.New(map[string]string{
|
||||
"k1" : "v1",
|
||||
"k2" : "v2",
|
||||
})
|
||||
p.Set("k1.k11", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, []byte(`{"k1":{"k11":[1,2,3]},"k2":"v2"}`)) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set2(t *testing.T) {
|
||||
e := []byte(`[[null,1]]`)
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("0.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set3(t *testing.T) {
|
||||
e := []byte(`{"kv":{"k1":"v1"}}`)
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("kv", map[string]string {
|
||||
"k1" : "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set4(t *testing.T) {
|
||||
e := []byte(`["a",[{"k1":"v1"}]]`)
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("1.0", map[string]string{
|
||||
"k1" : "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set5(t *testing.T) {
|
||||
e := []byte(`[[[[[[[[[[[[[[[[[[[[[1,2,3]]]]]]]]]]]]]]]]]]]]]`)
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set6(t *testing.T) {
|
||||
e := []byte(`["a",[1,2,3]]`)
|
||||
p := gjson.New([]string{"a"})
|
||||
p.Set("1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set7(t *testing.T) {
|
||||
e := []byte(`{"0":[null,[1,2,3]],"k1":"v1","k2":"v2"}`)
|
||||
p := gjson.New(map[string]string{
|
||||
"k1" : "v1",
|
||||
"k2" : "v2",
|
||||
})
|
||||
p.Set("0.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set8(t *testing.T) {
|
||||
e := []byte(`{"0":[[[[[[null,[1,2,3]]]]]]],"k1":"v1","k2":"v2"}`)
|
||||
p := gjson.New(map[string]string{
|
||||
"k1" : "v1",
|
||||
"k2" : "v2",
|
||||
})
|
||||
p.Set("0.0.0.0.0.0.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set9(t *testing.T) {
|
||||
e := []byte(`{"k1":[null,[1,2,3]],"k2":"v2"}`)
|
||||
p := gjson.New(map[string]string{
|
||||
"k1" : "v1",
|
||||
"k2" : "v2",
|
||||
})
|
||||
p.Set("k1.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func Test_Set10(t *testing.T) {
|
||||
e := []byte(`{"a":{"b":{"c":1}}}`)
|
||||
p := gjson.New(nil)
|
||||
p.Set("a.b.c", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func Test_Set11(t *testing.T) {
|
||||
e := []byte(`{"a":{"b":{}}}`)
|
||||
p, _ := gjson.LoadContent([]byte(`{"a":{"b":{"c":1}}}`))
|
||||
p.Remove("a.b.c")
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set12(t *testing.T) {
|
||||
e := []byte(`[0,1]`)
|
||||
p := gjson.New(nil)
|
||||
p.Set("0", 0)
|
||||
p.Set("1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set13(t *testing.T) {
|
||||
e := []byte(`{"array":[0,1]}`)
|
||||
p := gjson.New(nil)
|
||||
p.Set("array.0", 0)
|
||||
p.Set("array.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Set14(t *testing.T) {
|
||||
e := []byte(`{"f":{"a":1}}`)
|
||||
p := gjson.New(nil)
|
||||
p.Set("f", "m")
|
||||
p.Set("f.a", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,7 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://gitee.com/johng/gp.
|
||||
|
||||
// Package gparser provides a flexible and easy way for accessing/converting variable and JSON/XML/YAML/TOML contents.
|
||||
// Package gparser provides convenient API for accessing/converting variable and JSON/XML/YAML/TOML.
|
||||
package gparser
|
||||
|
||||
import (
|
||||
@ -16,13 +16,16 @@ type Parser struct {
|
||||
json *gjson.Json
|
||||
}
|
||||
|
||||
// 将变量转换为Parser对象进行处理,该变量至少应当是一个map或者array,否者转换没有意义
|
||||
// value可以传递nil, 表示创建一个空的Parser对象
|
||||
func New (value interface{}, unsafe...bool) *Parser {
|
||||
// New creates a Parser object with any variable type of <data>,
|
||||
// but <data> should be a map or slice for data access reason,
|
||||
// or it will make no sense.
|
||||
// The <unsafe> param specifies whether using this Parser object
|
||||
// in un-concurrent-safe context, which is false in default.
|
||||
func New(value interface{}, unsafe...bool) *Parser {
|
||||
return &Parser{gjson.New(value, unsafe...)}
|
||||
}
|
||||
|
||||
// 非并发安全Parser对象
|
||||
// NewUnsafe creates a un-concurrent-safe Parser object.
|
||||
func NewUnsafe (value...interface{}) *Parser {
|
||||
if len(value) > 0 {
|
||||
return &Parser{gjson.New(value[0], false)}
|
||||
@ -30,57 +33,64 @@ func NewUnsafe (value...interface{}) *Parser {
|
||||
return &Parser{gjson.New(nil, false)}
|
||||
}
|
||||
|
||||
func Load (path string) (*Parser, error) {
|
||||
if j, e := gjson.Load(path); e == nil {
|
||||
// Load loads content from specified file <path>,
|
||||
// and creates a Parser object from its content.
|
||||
func Load (path string, unsafe...bool) (*Parser, error) {
|
||||
if j, e := gjson.Load(path, unsafe...); e == nil {
|
||||
return &Parser{j}, nil
|
||||
} else {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
|
||||
// 支持的数据内容格式:json(默认), xml, yaml/yml, toml
|
||||
func LoadContent (data []byte, dataType...string) (*Parser, error) {
|
||||
if j, e := gjson.LoadContent(data, dataType...); e == nil {
|
||||
// LoadContent creates a Parser object from given content,
|
||||
// it checks the data type of <content> automatically,
|
||||
// supporting JSON, XML, YAML and TOML types of data.
|
||||
func LoadContent (data []byte, unsafe...bool) (*Parser, error) {
|
||||
if j, e := gjson.LoadContent(data, unsafe...); e == nil {
|
||||
return &Parser{j}, nil
|
||||
} else {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
|
||||
// 设置自定义的层级分隔符号
|
||||
// SetSplitChar sets the separator char for hierarchical data access.
|
||||
func (p *Parser) SetSplitChar(char byte) {
|
||||
p.json.SetSplitChar(char)
|
||||
}
|
||||
|
||||
// 设置是否执行层级冲突检查,当键名中存在层级符号时需要开启该特性,默认为关闭。
|
||||
// 开启比较耗性能,也不建议允许键名中存在分隔符,最好在应用端避免这种情况。
|
||||
// SetViolenceCheck enables/disables violence check for hierarchical data access.
|
||||
func (p *Parser) SetViolenceCheck(check bool) {
|
||||
p.json.SetViolenceCheck(check)
|
||||
}
|
||||
|
||||
// 将指定的json内容转换为指定结构返回,查找失败或者转换失败,目标对象转换为nil
|
||||
// 注意第二个参数需要给的是变量地址
|
||||
// GetToVar gets the value by specified <pattern>,
|
||||
// and converts it to specified golang variable <v>.
|
||||
// The <v> should be a pointer type.
|
||||
func (p *Parser) GetToVar(pattern string, v interface{}) error {
|
||||
return p.json.GetToVar(pattern, v)
|
||||
}
|
||||
|
||||
// 获得一个键值对关联数组/哈希表,方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
// GetMap gets the value by specified <pattern>,
|
||||
// and converts it to map[string]interface{}.
|
||||
func (p *Parser) GetMap(pattern string) map[string]interface{} {
|
||||
return p.json.GetMap(pattern)
|
||||
}
|
||||
|
||||
// 获得一个数组[]interface{},方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
// GetArray gets the value by specified <pattern>,
|
||||
// and converts it to a slice of []interface{}.
|
||||
func (p *Parser) GetArray(pattern string) []interface{} {
|
||||
return p.json.GetArray(pattern)
|
||||
}
|
||||
|
||||
// 返回指定json中的string
|
||||
// GetString gets the value by specified <pattern>,
|
||||
// and converts it to string.
|
||||
func (p *Parser) GetString(pattern string) string {
|
||||
return p.json.GetString(pattern)
|
||||
}
|
||||
|
||||
// GetStrings gets the value by specified <pattern>,
|
||||
// and converts it to a slice of []string.
|
||||
func (p *Parser) GetStrings(pattern string) []string {
|
||||
return p.json.GetStrings(pattern)
|
||||
}
|
||||
@ -97,7 +107,10 @@ func (p *Parser) GetTimeDuration(pattern string) time.Duration {
|
||||
return p.json.GetTimeDuration(pattern)
|
||||
}
|
||||
|
||||
// 返回指定json中的bool(false:"", 0, false, off)
|
||||
// GetBool gets the value by specified <pattern>,
|
||||
// and converts it to bool.
|
||||
// It returns false when value is: "", 0, false, off, nil;
|
||||
// or returns true instead.
|
||||
func (p *Parser) GetBool(pattern string) bool {
|
||||
return p.json.GetBool(pattern)
|
||||
}
|
||||
@ -158,51 +171,60 @@ func (p *Parser) GetFloats(pattern string) []float64 {
|
||||
return p.json.GetFloats(pattern)
|
||||
}
|
||||
|
||||
// 将指定变量转换为struct对象(对象属性赋值)
|
||||
// GetToStruct gets the value by specified <pattern>,
|
||||
// and converts it to specified object <objPointer>.
|
||||
// The <objPointer> should be the pointer to an object.
|
||||
func (p *Parser) GetToStruct(pattern string, objPointer interface{}) error {
|
||||
return p.json.GetToStruct(pattern, objPointer)
|
||||
}
|
||||
|
||||
// 根据pattern查找并设置数据
|
||||
// 注意:写入的时候"."符号只能表示层级,不能使用带"."符号的键名
|
||||
// Set sets value with specified <pattern>.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
func (p *Parser) Set(pattern string, value interface{}) error {
|
||||
return p.json.Set(pattern, value)
|
||||
}
|
||||
|
||||
// 计算指定pattern的元素长度(pattern对应数据类型为map[string]interface{}/[]interface{}时有效)
|
||||
// Len returns the length/size of the value by specified <pattern>.
|
||||
// The target value by <pattern> should be type of slice or map.
|
||||
// It returns -1 if the target value is not found, or its type is invalid.
|
||||
func (p *Parser) Len(pattern string) int {
|
||||
return p.json.Len(pattern)
|
||||
}
|
||||
|
||||
// 指定pattern追加元素
|
||||
// Append appends value to the value by specified <pattern>.
|
||||
// The target value by <pattern> should be type of slice.
|
||||
func (p *Parser) Append(pattern string, value interface{}) error {
|
||||
return p.json.Append(pattern, value)
|
||||
}
|
||||
|
||||
// 动态删除变量节点
|
||||
// Remove deletes value with specified <pattern>.
|
||||
// It supports hierarchical data access by char separator, which is '.' in default.
|
||||
func (p *Parser) Remove(pattern string) error {
|
||||
return p.json.Remove(pattern)
|
||||
}
|
||||
|
||||
// 根据约定字符串方式访问json解析数据,参数形如: "items.name.first", "list.0"; 当pattern为空时,表示获取所有数据
|
||||
// 返回的结果类型的interface{},因此需要自己做类型转换;
|
||||
// 如果找不到对应节点的数据,返回nil;
|
||||
// Get returns value by specified <pattern>.
|
||||
// It returns all values of current Json object, if <pattern> is empty or not specified.
|
||||
// It returns nil if no value found by <pattern>.
|
||||
//
|
||||
// We can also access slice item by its index number in <pattern>,
|
||||
// eg: "items.name.first", "list.10".
|
||||
func (p *Parser) Get(pattern...string) interface{} {
|
||||
return p.json.Get(pattern...)
|
||||
}
|
||||
|
||||
// 转换为map[string]interface{}类型,如果转换失败,返回nil
|
||||
// ToMap converts current object values to map[string]interface{}.
|
||||
// It returns nil if fails.
|
||||
func (p *Parser) ToMap() map[string]interface{} {
|
||||
return p.json.ToMap()
|
||||
}
|
||||
|
||||
// 转换为[]interface{}类型,如果转换失败,返回nil
|
||||
// ToArray converts current object values to []interface{}.
|
||||
// It returns nil if fails.
|
||||
func (p *Parser) ToArray() []interface{} {
|
||||
return p.json.ToArray()
|
||||
}
|
||||
|
||||
/* 以下为数据文件格式转换,支持类型:xml, json, yaml/yml, toml */
|
||||
|
||||
func (p *Parser) ToXml(rootTag...string) ([]byte, error) {
|
||||
return p.json.ToXml(rootTag...)
|
||||
}
|
||||
@ -227,12 +249,13 @@ func (p *Parser) ToToml() ([]byte, error) {
|
||||
return p.json.ToToml()
|
||||
}
|
||||
|
||||
// 打印Json对象
|
||||
// Dump prints current Json object with more manually readable.
|
||||
func (p *Parser) Dump() error {
|
||||
return p.json.Dump()
|
||||
}
|
||||
|
||||
// 将变量解析为对应的struct对象,注意传递的参数为struct对象指针
|
||||
// ToStruct converts current Json object to specified object.
|
||||
// The <objPointer> should be a pointer type.
|
||||
func (p *Parser) ToStruct(o interface{}) error {
|
||||
return p.json.ToStruct(o)
|
||||
}
|
||||
@ -261,7 +284,6 @@ func VarToToml(value interface{}) ([]byte, error) {
|
||||
return New(value).ToToml()
|
||||
}
|
||||
|
||||
// 将变量解析为对应的struct对象,注意传递的参数为struct对象指针
|
||||
func VarToStruct(value interface{}, obj interface{}) error {
|
||||
return New(value).ToStruct(obj)
|
||||
}
|
||||
|
||||
208
g/encoding/gparser/gparser_unit_basic_test.go
Normal file
208
g/encoding/gparser/gparser_unit_basic_test.go
Normal file
@ -0,0 +1,208 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g"
|
||||
"github.com/gogf/gf/g/encoding/gparser"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_New(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_NewUnsafe(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.NewUnsafe(data)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Encode(t *testing.T) {
|
||||
value := g.Slice{1, 2, 3}
|
||||
gtest.Case(t, func() {
|
||||
b, err := gparser.VarToJson(value)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(b, []byte(`[1,2,3]`))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Decode(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_SplitChar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
j.SetSplitChar(byte('#'))
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m#k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a#1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_ViolenceCheck(t *testing.T) {
|
||||
data := []byte(`{"m":{"a":[1,2,3], "v1.v2":"4"}}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.Assert(j.Get("m.a.2"), 3)
|
||||
gtest.Assert(j.Get("m.v1.v2"), nil)
|
||||
j.SetViolenceCheck(true)
|
||||
gtest.Assert(j.Get("m.v1.v2"), 4)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetToVar(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
var m map[string]string
|
||||
var n int
|
||||
var a []int
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
|
||||
j.GetToVar("n", &n)
|
||||
j.GetToVar("m", &m)
|
||||
j.GetToVar("a", &a)
|
||||
|
||||
gtest.Assert(n, "123456789")
|
||||
gtest.Assert(m, g.Map{"k" : "v"})
|
||||
gtest.Assert(a, g.Slice{1, 2, 3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetMap(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.Assert(j.GetMap("n"), nil)
|
||||
gtest.Assert(j.GetMap("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.GetMap("a"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetArray(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.Assert(j.GetArray("n"), g.Array{123456789})
|
||||
gtest.Assert(j.GetArray("m"), g.Array{g.Map{"k":"v"}})
|
||||
gtest.Assert(j.GetArray("a"), g.Array{1,2,3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetString(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.AssertEQ(j.GetString("n"), "123456789")
|
||||
gtest.AssertEQ(j.GetString("m"), `{"k":"v"}`)
|
||||
gtest.AssertEQ(j.GetString("a"), `[1,2,3]`)
|
||||
gtest.AssertEQ(j.GetString("i"), "")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetStrings(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.AssertEQ(j.GetStrings("n"), g.SliceStr{"123456789"})
|
||||
gtest.AssertEQ(j.GetStrings("m"), g.SliceStr{`{"k":"v"}`})
|
||||
gtest.AssertEQ(j.GetStrings("a"), g.SliceStr{"1", "2", "3"})
|
||||
gtest.AssertEQ(j.GetStrings("i"), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_GetInterfaces(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
gtest.Case(t, func() {
|
||||
j := gparser.New(data)
|
||||
gtest.AssertNE(j, nil)
|
||||
gtest.AssertEQ(j.GetInterfaces("n"), g.Array{123456789})
|
||||
gtest.AssertEQ(j.GetInterfaces("m"), g.Array{g.Map{"k":"v"}})
|
||||
gtest.AssertEQ(j.GetInterfaces("a"), g.Array{1,2,3})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Len(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
gtest.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
gtest.Assert(p.Len("a"), 2)
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Set("a", 1)
|
||||
gtest.Assert(p.Len("a"), -1)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Append(t *testing.T) {
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a", 1)
|
||||
p.Append("a", 2)
|
||||
gtest.Assert(p.Get("a"), g.Slice{1, 2})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Append("a.b", 1)
|
||||
p.Append("a.c", 2)
|
||||
gtest.Assert(p.Get("a"), g.Map{
|
||||
"b" : g.Slice{1},
|
||||
"c" : g.Slice{2},
|
||||
})
|
||||
})
|
||||
gtest.Case(t, func() {
|
||||
p := gparser.New(nil)
|
||||
p.Set("a", 1)
|
||||
err := p.Append("a", 2)
|
||||
gtest.AssertNE(err, nil)
|
||||
gtest.Assert(p.Get("a"), 1)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
156
g/encoding/gparser/gparser_unit_load_test.go
Normal file
156
g/encoding/gparser/gparser_unit_load_test.go
Normal file
@ -0,0 +1,156 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g"
|
||||
"github.com/gogf/gf/g/encoding/gparser"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
func Test_Load_JSON(t *testing.T) {
|
||||
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
|
||||
// JSON
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// JSON
|
||||
gtest.Case(t, func() {
|
||||
path := "test.json"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_XML(t *testing.T) {
|
||||
data := []byte(`<doc><a>1</a><a>2</a><a>3</a><m><k>v</k></m><n>123456789</n></doc>`)
|
||||
// XML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("doc.n"), "123456789")
|
||||
gtest.Assert(j.Get("doc.m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("doc.m.k"), "v")
|
||||
gtest.Assert(j.Get("doc.a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
// XML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.xml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("doc.n"), "123456789")
|
||||
gtest.Assert(j.Get("doc.m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("doc.m.k"), "v")
|
||||
gtest.Assert(j.Get("doc.a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("doc.a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
m:
|
||||
k: v
|
||||
"n": 123456789
|
||||
`)
|
||||
// YAML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// YAML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.yaml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_YAML2(t *testing.T) {
|
||||
data := []byte("i : 123456789")
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML1(t *testing.T) {
|
||||
data := []byte(`
|
||||
a = ["1", "2", "3"]
|
||||
n = "123456789"
|
||||
|
||||
[m]
|
||||
k = "v"
|
||||
`)
|
||||
// TOML
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
// TOML
|
||||
gtest.Case(t, func() {
|
||||
path := "test.toml"
|
||||
gfile.PutBinContents(path, data)
|
||||
defer gfile.Remove(path)
|
||||
j, err := gparser.Load(path)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("n"), "123456789")
|
||||
gtest.Assert(j.Get("m"), g.Map{"k" : "v"})
|
||||
gtest.Assert(j.Get("m.k"), "v")
|
||||
gtest.Assert(j.Get("a"), g.Slice{1, 2, 3})
|
||||
gtest.Assert(j.Get("a.1"), 2)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Load_TOML2(t *testing.T) {
|
||||
data := []byte("i=123456789")
|
||||
gtest.Case(t, func() {
|
||||
j, err := gparser.LoadContent(data)
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(j.Get("i"), "123456789")
|
||||
})
|
||||
}
|
||||
@ -4,15 +4,12 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// 单元测试
|
||||
|
||||
package gparser_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"github.com/gogf/gf/g/encoding/gparser"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Set1(t *testing.T) {
|
||||
@ -23,7 +20,6 @@ func Test_Set1(t *testing.T) {
|
||||
})
|
||||
p.Set("k1.k11", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, []byte(`{"k1":{"k11":[1,2,3]},"k2":"v2"}`)) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -37,7 +33,6 @@ func Test_Set2(t *testing.T) {
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("0.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -49,11 +44,10 @@ func Test_Set2(t *testing.T) {
|
||||
func Test_Set3(t *testing.T) {
|
||||
e := []byte(`{"kv":{"k1":"v1"}}`)
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("kv", map[string]string{
|
||||
p.Set("kv", map[string]string {
|
||||
"k1" : "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -69,7 +63,6 @@ func Test_Set4(t *testing.T) {
|
||||
"k1" : "v1",
|
||||
})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -83,7 +76,6 @@ func Test_Set5(t *testing.T) {
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -97,7 +89,6 @@ func Test_Set6(t *testing.T) {
|
||||
p := gparser.New([]string{"a"})
|
||||
p.Set("1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -114,7 +105,6 @@ func Test_Set7(t *testing.T) {
|
||||
})
|
||||
p.Set("0.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -131,7 +121,6 @@ func Test_Set8(t *testing.T) {
|
||||
})
|
||||
p.Set("0.0.0.0.0.0.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -148,7 +137,6 @@ func Test_Set9(t *testing.T) {
|
||||
})
|
||||
p.Set("k1.1", []int{1,2,3})
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -163,7 +151,6 @@ func Test_Set10(t *testing.T) {
|
||||
p := gparser.New(nil)
|
||||
p.Set("a.b.c", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -175,10 +162,9 @@ func Test_Set10(t *testing.T) {
|
||||
|
||||
func Test_Set11(t *testing.T) {
|
||||
e := []byte(`{"a":{"b":{}}}`)
|
||||
p, _ := gparser.LoadContent([]byte(`{"a":{"b":{"c":1}}}`), "json")
|
||||
p, _ := gparser.LoadContent([]byte(`{"a":{"b":{"c":1}}}`))
|
||||
p.Remove("a.b.c")
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -193,7 +179,6 @@ func Test_Set12(t *testing.T) {
|
||||
p.Set("0", 0)
|
||||
p.Set("1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -208,7 +193,6 @@ func Test_Set13(t *testing.T) {
|
||||
p.Set("array.0", 0)
|
||||
p.Set("array.1", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
fmt.Println(string(c))
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
@ -217,7 +201,16 @@ func Test_Set13(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
func Test_Set14(t *testing.T) {
|
||||
e := []byte(`{"f":{"a":1}}`)
|
||||
p := gparser.New(nil)
|
||||
p.Set("f", "m")
|
||||
p.Set("f.a", 1)
|
||||
if c, err := p.ToJson(); err == nil {
|
||||
if bytes.Compare(c, e) != 0 {
|
||||
t.Error("expect:", string(e))
|
||||
}
|
||||
} else {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
@ -5,75 +5,80 @@
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gxml provides accessing and converting for XML content.
|
||||
//
|
||||
// XML数据格式解析。
|
||||
package gxml
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/third/github.com/clbanning/mxj"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"github.com/gogf/gf/third/github.com/axgle/mahonia"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/third/github.com/clbanning/mxj"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 将XML内容解析为map变量
|
||||
func Decode(xmlbyte []byte) (map[string]interface{}, error) {
|
||||
prepare(xmlbyte)
|
||||
return mxj.NewMapXml(xmlbyte)
|
||||
func Decode(content []byte) (map[string]interface{}, error) {
|
||||
res, err := convert(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return mxj.NewMapXml(res)
|
||||
}
|
||||
|
||||
// 将map变量解析为XML格式内容
|
||||
func Encode(v map[string]interface{}, rootTag...string) ([]byte, error) {
|
||||
return mxj.Map(v).Xml(rootTag...)
|
||||
func Encode(v map[string]interface{}, rootTag ...string) ([]byte, error) {
|
||||
return mxj.Map(v).Xml(rootTag...)
|
||||
}
|
||||
|
||||
func EncodeWithIndent(v map[string]interface{}, rootTag...string) ([]byte, error) {
|
||||
return mxj.Map(v).XmlIndent("", "\t", rootTag...)
|
||||
func EncodeWithIndent(v map[string]interface{}, rootTag ...string) ([]byte, error) {
|
||||
return mxj.Map(v).XmlIndent("", "\t", rootTag...)
|
||||
}
|
||||
|
||||
// XML格式内容直接转换为JSON格式内容
|
||||
func ToJson(xmlbyte []byte) ([]byte, error) {
|
||||
prepare(xmlbyte)
|
||||
mv, err := mxj.NewMapXml(xmlbyte)
|
||||
func ToJson(content []byte) ([]byte, error) {
|
||||
res, err := convert(content)
|
||||
if err != nil {
|
||||
fmt.Println("convert error. ", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mv, err := mxj.NewMapXml(res)
|
||||
if err == nil {
|
||||
return mv.Json()
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
return mv.Json()
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// XML字符集预处理
|
||||
// @author wenzi1
|
||||
// @date 20180604
|
||||
func prepare(xmlbyte []byte) error {
|
||||
// @date 20180604 修复并发安全问题,改为如果非UTF8字符集则先做字符集转换
|
||||
func convert(xmlbyte []byte) (res []byte, err error) {
|
||||
patten := `<\?xml.*encoding\s*=\s*['|"](.*?)['|"].*\?>`
|
||||
charsetReader := func(charset string, input io.Reader) (io.Reader, error) {
|
||||
reader := mahonia.GetCharset(charset)
|
||||
if reader == nil {
|
||||
return nil, errors.New(fmt.Sprintf("not support charset:%s", charset))
|
||||
}
|
||||
return reader.NewDecoder().NewReader(input), nil
|
||||
}
|
||||
|
||||
matchStr, err := gregex.MatchString(patten, string(xmlbyte))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
xmlEncode := "UTF-8"
|
||||
if len(matchStr) == 2 {
|
||||
xmlEncode = matchStr[1]
|
||||
xmlEncode = matchStr[1]
|
||||
}
|
||||
|
||||
charset := mahonia.GetCharset(xmlEncode)
|
||||
if charset == nil {
|
||||
return errors.New(fmt.Sprintf("not support charset:%s", xmlEncode))
|
||||
s := mahonia.GetCharset(xmlEncode)
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("not support charset:%s\n", xmlEncode)
|
||||
}
|
||||
|
||||
if !strings.EqualFold(charset.Name, "UTF-8") {
|
||||
mxj.CustomDecoder = &xml.Decoder{Strict : false, CharsetReader : charsetReader}
|
||||
res, err = gregex.Replace(patten, []byte(""), []byte(xmlbyte))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if !strings.EqualFold(s.Name, "UTF-8") {
|
||||
res = []byte(s.NewDecoder().ConvertString(string(res)))
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
140
g/encoding/gxml/gxml_test.go
Normal file
140
g/encoding/gxml/gxml_test.go
Normal file
@ -0,0 +1,140 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gxml_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/gogf/gf/g/encoding/gcharset"
|
||||
"github.com/gogf/gf/g/encoding/gparser"
|
||||
"github.com/gogf/gf/g/encoding/gxml"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testData = []struct {
|
||||
utf8, other, otherEncoding string
|
||||
}{
|
||||
{"Hello 常用國字標準字體表", "Hello \xb1`\xa5\u03b0\xea\xa6r\xbc\u0437\u01e6r\xc5\xe9\xaa\xed", "big5"},
|
||||
{"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gbk"},
|
||||
{"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gb18030"},
|
||||
}
|
||||
|
||||
func buildXml(charset string, str string) (string, string) {
|
||||
head := `<?xml version="1.0" encoding="UTF-8"?>`
|
||||
srcXml := strings.Replace(head, "UTF-8", charset, -1)
|
||||
|
||||
srcParser := gparser.New(nil)
|
||||
srcParser.Set("name", str)
|
||||
srcParser.Set("age", "12")
|
||||
|
||||
s, err := srcParser.ToXml()
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
srcXml = srcXml + string(s)
|
||||
srcXml, err = gcharset.UTF8To(charset, srcXml)
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
dstXml := head + string(s)
|
||||
|
||||
return srcXml, dstXml
|
||||
}
|
||||
|
||||
//测试XML中字符集的转换
|
||||
func Test_XmlToJson(t *testing.T) {
|
||||
for _, v := range testData {
|
||||
srcXml, dstXml := buildXml(v.otherEncoding, v.utf8)
|
||||
if len(srcXml) == 0 && len(dstXml) == 0 {
|
||||
t.Errorf("build xml string error. srcEncoding:%s, src:%s, utf8:%s", v.otherEncoding, v.other, v.utf8)
|
||||
}
|
||||
|
||||
srcJson, err := gxml.ToJson([]byte(srcXml))
|
||||
if err != nil {
|
||||
t.Errorf("gxml.ToJson error. %s", srcXml)
|
||||
}
|
||||
|
||||
dstJson, err := gxml.ToJson([]byte(dstXml))
|
||||
if err != nil {
|
||||
t.Errorf("dstXml to json error. %s", dstXml)
|
||||
}
|
||||
|
||||
if bytes.Compare(srcJson, dstJson) != 0 {
|
||||
t.Errorf("convert to json error. srcJson:%s, dstJson:%s", string(srcJson), string(dstJson))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Decode(t *testing.T) {
|
||||
for _, v := range testData {
|
||||
srcXml, dstXml := buildXml(v.otherEncoding, v.utf8)
|
||||
if len(srcXml) == 0 && len(dstXml) == 0 {
|
||||
t.Errorf("build xml string error. srcEncoding:%s, src:%s, utf8:%s", v.otherEncoding, v.other, v.utf8)
|
||||
}
|
||||
|
||||
srcMap, err := gxml.Decode([]byte(srcXml))
|
||||
if err != nil {
|
||||
t.Errorf("gxml.Decode error. %s", srcXml)
|
||||
}
|
||||
|
||||
dstMap, err := gxml.Decode([]byte(dstXml))
|
||||
if err != nil {
|
||||
t.Errorf("gxml decode error. %s", dstXml)
|
||||
}
|
||||
s := srcMap["doc"].(map[string]interface{})
|
||||
d := dstMap["doc"].(map[string]interface{})
|
||||
for kk, vv := range s {
|
||||
if vv.(string) != d[kk].(string) {
|
||||
t.Errorf("convert to map error. src:%v, dst:%v", vv, d[kk])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Encode(t *testing.T) {
|
||||
m := make(map[string]interface{})
|
||||
v := map[string]interface{}{
|
||||
"string": "hello world",
|
||||
"int": 123,
|
||||
"float": 100.92,
|
||||
"bool": true,
|
||||
}
|
||||
m["root"] = interface{}(v)
|
||||
|
||||
xmlStr, err := gxml.Encode(m)
|
||||
if err != nil {
|
||||
t.Errorf("encode error.")
|
||||
}
|
||||
t.Logf("%s\n", string(xmlStr))
|
||||
|
||||
res := `<root><bool>true</bool><float>100.92</float><int>123</int><string>hello world</string></root>`
|
||||
if string(xmlStr) != res {
|
||||
t.Errorf("encode error. result: [%s], expect:[%s]", string(xmlStr), res)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_EncodeIndent(t *testing.T) {
|
||||
m := make(map[string]interface{})
|
||||
v := map[string]interface{}{
|
||||
"string": "hello world",
|
||||
"int": 123,
|
||||
"float": 100.92,
|
||||
"bool": true,
|
||||
}
|
||||
m["root"] = interface{}(v)
|
||||
|
||||
xmlStr, err := gxml.EncodeWithIndent(m, "xml")
|
||||
if err != nil {
|
||||
t.Errorf("encodeWithIndent error.")
|
||||
}
|
||||
|
||||
t.Logf("%s\n", string(xmlStr))
|
||||
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package frame
|
||||
@ -4,30 +4,25 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gins provides instances management and some core components.
|
||||
//
|
||||
// 单例对象管理.
|
||||
// 框架内置了一些核心对象获取方法,并且可以通过Set和Get方法实现IoC以及对内置核心对象的自定义替换
|
||||
// Package gins provides instances management and core components management.
|
||||
package gins
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/g/database/gdb"
|
||||
"github.com/gogf/gf/g/database/gredis"
|
||||
"github.com/gogf/gf/g/internal/cmdenv"
|
||||
"github.com/gogf/gf/g/os/gcfg"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gfsnotify"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/os/gview"
|
||||
"github.com/gogf/gf/g/util/gconv"
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/g/database/gdb"
|
||||
"github.com/gogf/gf/g/database/gredis"
|
||||
"github.com/gogf/gf/g/os/gcfg"
|
||||
"github.com/gogf/gf/g/os/gfsnotify"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/os/gview"
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"github.com/gogf/gf/g/text/gstr"
|
||||
"github.com/gogf/gf/g/util/gconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
gFRAME_CORE_COMPONENT_NAME_VIEW = "gf.core.component.view"
|
||||
gFRAME_CORE_COMPONENT_NAME_CONFIG = "gf.core.component.config"
|
||||
gFRAME_CORE_COMPONENT_NAME_REDIS = "gf.core.component.redis"
|
||||
gFRAME_CORE_COMPONENT_NAME_DATABASE = "gf.core.component.database"
|
||||
)
|
||||
@ -65,58 +60,20 @@ func SetIfNotExist(key string, value interface{}) bool {
|
||||
return instances.SetIfNotExist(key, value)
|
||||
}
|
||||
|
||||
// 核心对象:View
|
||||
func View(name...string) *gview.View {
|
||||
group := "default"
|
||||
if len(name) > 0 {
|
||||
group = name[0]
|
||||
}
|
||||
key := fmt.Sprintf("%s.%s", gFRAME_CORE_COMPONENT_NAME_VIEW, group)
|
||||
return instances.GetOrSetFuncLock(key, func() interface{} {
|
||||
path := cmdenv.Get("gf.gview.path", gfile.Pwd()).String()
|
||||
view := gview.New(path)
|
||||
// 添加基于源码的搜索目录检索地址,常用于开发环境调试,只添加入口文件目录
|
||||
if p := gfile.MainPkgPath(); p != "" && gfile.Exists(p) {
|
||||
view.AddPath(p)
|
||||
}
|
||||
// 框架内置函数
|
||||
view.BindFunc("config", funcConfig)
|
||||
return view
|
||||
}).(*gview.View)
|
||||
// View returns an instance of View with default settings.
|
||||
// The param <name> is the name for the instance.
|
||||
func View(name ...string) *gview.View {
|
||||
return gview.Instance(name ...)
|
||||
}
|
||||
|
||||
// 核心对象:Config
|
||||
// 配置文件目录查找依次为:启动参数cfgpath、当前程序运行目录
|
||||
func Config(file...string) *gcfg.Config {
|
||||
configFile := gcfg.DEFAULT_CONFIG_FILE
|
||||
if len(file) > 0 {
|
||||
configFile = file[0]
|
||||
}
|
||||
return instances.GetOrSetFuncLock(fmt.Sprintf("%s.%s", gFRAME_CORE_COMPONENT_NAME_CONFIG, configFile),
|
||||
func() interface{} {
|
||||
pwdPath := gfile.Pwd()
|
||||
envPath := cmdenv.Get("gf.gcfg.path").String()
|
||||
selfPath := gfile.SelfDir()
|
||||
mainPath := gfile.MainPkgPath()
|
||||
config := gcfg.New(pwdPath, configFile)
|
||||
// 自定义的环境变量/启动参数路径,优先级最高,覆盖默认的工作目录
|
||||
if envPath != "" && gfile.Exists(envPath) {
|
||||
config.SetPath(envPath)
|
||||
}
|
||||
// 二进制文件执行目录
|
||||
if selfPath != "" && gfile.Exists(selfPath) {
|
||||
config.AddPath(selfPath)
|
||||
}
|
||||
// 开发环境源码main包目录
|
||||
if mainPath != "" && gfile.Exists(mainPath) {
|
||||
config.AddPath(mainPath)
|
||||
}
|
||||
return config
|
||||
}).(*gcfg.Config)
|
||||
// Config returns an instance of View with default settings.
|
||||
// The param <name> is the name for the instance.
|
||||
func Config(name ...string) *gcfg.Config {
|
||||
return gcfg.Instance(name ...)
|
||||
}
|
||||
|
||||
// 数据库操作对象,使用了连接池
|
||||
func Database(name...string) gdb.DB {
|
||||
func Database(name ...string) gdb.DB {
|
||||
config := Config()
|
||||
group := gdb.DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
@ -133,46 +90,66 @@ func Database(name...string) gdb.DB {
|
||||
for group, v := range m {
|
||||
cg := gdb.ConfigGroup{}
|
||||
if list, ok := v.([]interface{}); ok {
|
||||
for _, nodev := range list {
|
||||
node := gdb.ConfigNode{}
|
||||
nodem := nodev.(map[string]interface{})
|
||||
if value, ok := nodem["host"]; ok {
|
||||
for _, nodeValue := range list {
|
||||
node := gdb.ConfigNode{}
|
||||
nodeMap := nodeValue.(map[string]interface{})
|
||||
if value, ok := nodeMap["host"]; ok {
|
||||
node.Host = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["port"]; ok {
|
||||
if value, ok := nodeMap["port"]; ok {
|
||||
node.Port = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["user"]; ok {
|
||||
if value, ok := nodeMap["user"]; ok {
|
||||
node.User = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["pass"]; ok {
|
||||
if value, ok := nodeMap["pass"]; ok {
|
||||
node.Pass = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["name"]; ok {
|
||||
if value, ok := nodeMap["name"]; ok {
|
||||
node.Name = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["type"]; ok {
|
||||
if value, ok := nodeMap["type"]; ok {
|
||||
node.Type = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["role"]; ok {
|
||||
if value, ok := nodeMap["role"]; ok {
|
||||
node.Role = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["charset"]; ok {
|
||||
if value, ok := nodeMap["charset"]; ok {
|
||||
node.Charset = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["priority"]; ok {
|
||||
if value, ok := nodeMap["priority"]; ok {
|
||||
node.Priority = gconv.Int(value)
|
||||
}
|
||||
if value, ok := nodem["linkinfo"]; ok {
|
||||
node.Linkinfo = gconv.String(value)
|
||||
// Deprecated
|
||||
if value, ok := nodeMap["linkinfo"]; ok {
|
||||
node.LinkInfo = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodem["max-idle"]; ok {
|
||||
// Deprecated
|
||||
if value, ok := nodeMap["link-info"]; ok {
|
||||
node.LinkInfo = gconv.String(value)
|
||||
}
|
||||
if value, ok := nodeMap["linkInfo"]; ok {
|
||||
node.LinkInfo = gconv.String(value)
|
||||
}
|
||||
// Deprecated
|
||||
if value, ok := nodeMap["max-idle"]; ok {
|
||||
node.MaxIdleConnCount = gconv.Int(value)
|
||||
}
|
||||
if value, ok := nodem["max-open"]; ok {
|
||||
if value, ok := nodeMap["maxIdle"]; ok {
|
||||
node.MaxIdleConnCount = gconv.Int(value)
|
||||
}
|
||||
// Deprecated
|
||||
if value, ok := nodeMap["max-open"]; ok {
|
||||
node.MaxOpenConnCount = gconv.Int(value)
|
||||
}
|
||||
if value, ok := nodem["max-lifetime"]; ok {
|
||||
if value, ok := nodeMap["maxOpen"]; ok {
|
||||
node.MaxOpenConnCount = gconv.Int(value)
|
||||
}
|
||||
// Deprecated
|
||||
if value, ok := nodeMap["max-lifetime"]; ok {
|
||||
node.MaxConnLifetime = gconv.Int(value)
|
||||
}
|
||||
if value, ok := nodeMap["maxLifetime"]; ok {
|
||||
node.MaxConnLifetime = gconv.Int(value)
|
||||
}
|
||||
cg = append(cg, node)
|
||||
@ -180,10 +157,7 @@ func Database(name...string) gdb.DB {
|
||||
}
|
||||
gdb.AddConfigGroup(group, cg)
|
||||
}
|
||||
// 使用gfsnotify进行文件监控,当配置文件有任何变化时,清空数据库配置缓存
|
||||
gfsnotify.Add(config.GetFilePath(), func(event *gfsnotify.Event) {
|
||||
instances.Remove(key)
|
||||
})
|
||||
addConfigMonitor(key, config)
|
||||
}
|
||||
if db, err := gdb.New(name...); err == nil {
|
||||
return db
|
||||
@ -208,11 +182,36 @@ func Redis(name...string) *gredis.Redis {
|
||||
key := fmt.Sprintf("%s.%s", gFRAME_CORE_COMPONENT_NAME_REDIS, group)
|
||||
result := instances.GetOrSetFuncLock(key, func() interface{} {
|
||||
if m := config.GetMap("redis"); m != nil {
|
||||
// host:port[,db[,pass]]
|
||||
// host:port[,db,pass?maxIdle=x&maxActive=x&idleTimeout=x&maxConnLifetime=x]
|
||||
if v, ok := m[group]; ok {
|
||||
line := gconv.String(v)
|
||||
array, _ := gregex.MatchString(`(.+):(\d+),{0,1}(\d*),{0,1}(.*)`, line)
|
||||
if len(array) > 4 {
|
||||
line := gconv.String(v)
|
||||
array, _ := gregex.MatchString(`(.+):(\d+),{0,1}(\d*),{0,1}(.*)\?(.+)`, line)
|
||||
if len(array) == 6 {
|
||||
parse, _ := gstr.Parse(array[5])
|
||||
redisConfig := gredis.Config{
|
||||
Host : array[1],
|
||||
Port : gconv.Int(array[2]),
|
||||
Db : gconv.Int(array[3]),
|
||||
Pass : array[4],
|
||||
}
|
||||
if v, ok := parse["maxIdle"]; ok {
|
||||
redisConfig.MaxIdle = gconv.Int(v)
|
||||
}
|
||||
if v, ok := parse["maxActive"]; ok {
|
||||
redisConfig.MaxActive = gconv.Int(v)
|
||||
}
|
||||
if v, ok := parse["idleTimeout"]; ok {
|
||||
redisConfig.IdleTimeout = gconv.TimeDuration(v)*time.Second
|
||||
}
|
||||
if v, ok := parse["maxConnLifetime"]; ok {
|
||||
redisConfig.MaxConnLifetime = gconv.TimeDuration(v)*time.Second
|
||||
}
|
||||
addConfigMonitor(key, config)
|
||||
return gredis.New(redisConfig)
|
||||
}
|
||||
array, _ = gregex.MatchString(`(.+):(\d+),{0,1}(\d*),{0,1}(.*)`, line)
|
||||
if len(array) == 5 {
|
||||
addConfigMonitor(key, config)
|
||||
return gredis.New(gredis.Config{
|
||||
Host : array[1],
|
||||
Port : gconv.Int(array[2]),
|
||||
@ -236,6 +235,16 @@ func Redis(name...string) *gredis.Redis {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 添加对单例对象的配置文件inotify监控
|
||||
func addConfigMonitor(key string, config *gcfg.Config) {
|
||||
// 使用gfsnotify进行文件监控,当配置文件有任何变化时,清空对象单例缓存
|
||||
if path := config.GetFilePath(); path != "" {
|
||||
gfsnotify.Add(path, func(event *gfsnotify.Event) {
|
||||
instances.Remove(key)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 模板内置方法:config
|
||||
func funcConfig(pattern string, file...string) string {
|
||||
return Config().GetString(pattern, file...)
|
||||
|
||||
@ -7,13 +7,13 @@
|
||||
package gins_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/frame/gins"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gtime"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
"time"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/frame/gins"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gtime"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Test_Config(t *testing.T) {
|
||||
@ -51,13 +51,14 @@ test = "v=1"
|
||||
gtest.Case(t, func() {
|
||||
gtest.AssertNE(gins.Config(), nil)
|
||||
})
|
||||
|
||||
// relative path
|
||||
gtest.Case(t, func() {
|
||||
path := "config.toml"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
gtest.Assert(gins.Config().Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config().Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config().Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
@ -71,7 +72,7 @@ test = "v=1"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
gtest.Assert(gins.Config().Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config().Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config().Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
@ -84,10 +85,11 @@ test = "v=1"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
gtest.Assert(gins.Config("test.toml").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
defer gins.Config("test").Clear()
|
||||
gins.Config("test").SetFileName("test.toml")
|
||||
gtest.Assert(gins.Config("test").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
})
|
||||
// for gfsnotify callbacks to refresh cache of config file
|
||||
time.Sleep(500*time.Millisecond)
|
||||
@ -97,10 +99,11 @@ test = "v=1"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
gtest.Assert(gins.Config("test.toml").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
defer gins.Config("test").Clear()
|
||||
gins.Config("test").SetFileName("test.toml")
|
||||
gtest.Assert(gins.Config("test").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
})
|
||||
// for gfsnotify callbacks to refresh cache of config file
|
||||
time.Sleep(500*time.Millisecond)
|
||||
@ -113,7 +116,7 @@ test = "v=1"
|
||||
err := gfile.PutContents(file, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(file)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
gtest.Assert(gins.Config().AddPath(path), nil)
|
||||
gtest.Assert(gins.Config().Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config().Get("database.default.1.host"), "127.0.0.1")
|
||||
@ -127,7 +130,7 @@ test = "v=1"
|
||||
err := gfile.PutContents(file, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(file)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
gtest.Assert(gins.Config().AddPath(path), nil)
|
||||
gtest.Assert(gins.Config().Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config().Get("database.default.1.host"), "127.0.0.1")
|
||||
@ -141,12 +144,12 @@ test = "v=1"
|
||||
err := gfile.PutContents(file, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(file)
|
||||
defer gins.Config("test.toml").Reload()
|
||||
|
||||
gtest.Assert(gins.Config("test.toml").AddPath(path), nil)
|
||||
gtest.Assert(gins.Config("test.toml").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
defer gins.Config("test").Clear()
|
||||
gins.Config("test").SetFileName("test.toml")
|
||||
gtest.Assert(gins.Config("test").AddPath(path), nil)
|
||||
gtest.Assert(gins.Config("test").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
})
|
||||
time.Sleep(500*time.Millisecond)
|
||||
|
||||
@ -156,11 +159,11 @@ test = "v=1"
|
||||
err := gfile.PutContents(file, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(file)
|
||||
defer gins.Config("test.toml").Reload()
|
||||
|
||||
gtest.Assert(gins.Config("test.toml").AddPath(path), nil)
|
||||
gtest.Assert(gins.Config("test.toml").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test.toml").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
defer gins.Config().Clear()
|
||||
gins.Config("test").SetFileName("test.toml")
|
||||
gtest.Assert(gins.Config("test").AddPath(path), nil)
|
||||
gtest.Assert(gins.Config("test").Get("test"), "v=1")
|
||||
gtest.Assert(gins.Config("test").Get("database.default.1.host"), "127.0.0.1")
|
||||
gtest.Assert(gins.Config("test").Get("redis.disk"), "127.0.0.1:6379,0")
|
||||
})
|
||||
}
|
||||
|
||||
@ -53,7 +53,7 @@ test = "v=2"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
|
||||
// for gfsnotify callbacks to refresh cache of config file
|
||||
time.Sleep(500*time.Millisecond)
|
||||
|
||||
@ -7,7 +7,6 @@
|
||||
package gins_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/frame/gins"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
@ -46,25 +45,28 @@ test = "v=3"
|
||||
priority = "1"
|
||||
# Redis数据库配置
|
||||
[redis]
|
||||
default = "127.0.0.1:6379,0"
|
||||
cache = "127.0.0.1:6379,1"
|
||||
default = "127.0.0.1:6379,7"
|
||||
cache = "127.0.0.1:6379,8"
|
||||
disk = "127.0.0.1:6379,9,?maxIdle=1&maxActive=10&idleTimeout=10&maxConnLifetime=10"
|
||||
`
|
||||
path := "config.toml"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
defer gins.Config().Reload()
|
||||
defer gins.Config().Clear()
|
||||
|
||||
// for gfsnotify callbacks to refresh cache of config file
|
||||
time.Sleep(500*time.Millisecond)
|
||||
|
||||
gtest.Case(t, func() {
|
||||
fmt.Println("gins Test_Redis", gins.Config().Get("test"))
|
||||
//fmt.Println("gins Test_Redis", gins.Config().Get("test"))
|
||||
|
||||
redisDefault := gins.Redis()
|
||||
redisCache := gins.Redis("cache")
|
||||
redisDisk := gins.Redis("disk")
|
||||
gtest.AssertNE(redisDefault, nil)
|
||||
gtest.AssertNE(redisCache, nil)
|
||||
gtest.AssertNE(redisDisk, nil)
|
||||
|
||||
r, err := redisDefault.Do("PING")
|
||||
gtest.Assert(err, nil)
|
||||
@ -73,6 +75,12 @@ test = "v=3"
|
||||
r, err = redisCache.Do("PING")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, "PONG")
|
||||
|
||||
_, err = redisDisk.Do("SET", "k", "v")
|
||||
gtest.Assert(err, nil)
|
||||
r, err = redisDisk.Do("GET", "k")
|
||||
gtest.Assert(err, nil)
|
||||
gtest.Assert(r, []byte("v"))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
8
g/g.go
8
g/g.go
@ -9,13 +9,9 @@ package g
|
||||
import "github.com/gogf/gf/g/container/gvar"
|
||||
|
||||
// Universal variable type, like generics.
|
||||
//
|
||||
// 动态变量类型,可以用该类型替代interface{}类型
|
||||
type Var = gvar.Var
|
||||
|
||||
// Frequently-used map type alias.
|
||||
//
|
||||
// 常用map数据结构(使用别名)
|
||||
type Map = map[string]interface{}
|
||||
type MapAnyAny = map[interface{}]interface{}
|
||||
type MapAnyStr = map[interface{}]string
|
||||
@ -28,8 +24,6 @@ type MapIntStr = map[int]string
|
||||
type MapIntInt = map[int]int
|
||||
|
||||
// Frequently-used slice type alias.
|
||||
//
|
||||
// 常用list数据结构(使用别名)
|
||||
type List = []Map
|
||||
type ListAnyStr = []map[interface{}]string
|
||||
type ListAnyInt = []map[interface{}]int
|
||||
@ -41,8 +35,6 @@ type ListIntStr = []map[int]string
|
||||
type ListIntInt = []map[int]int
|
||||
|
||||
// Frequently-used slice type alias.
|
||||
//
|
||||
// 常用slice数据结构(使用别名)
|
||||
type Slice = []interface{}
|
||||
type SliceAny = []interface{}
|
||||
type SliceStr = []string
|
||||
|
||||
38
g/g_func.go
38
g/g_func.go
@ -7,47 +7,34 @@
|
||||
package g
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/container/gvar"
|
||||
"github.com/gogf/gf/g/internal/empty"
|
||||
"github.com/gogf/gf/g/net/ghttp"
|
||||
"github.com/gogf/gf/g/util/gutil"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/container/gvar"
|
||||
)
|
||||
|
||||
const (
|
||||
LOG_LEVEL_ALL = glog.LEVEL_ALL
|
||||
LOG_LEVEL_DEBU = glog.LEVEL_DEBU
|
||||
LOG_LEVEL_INFO = glog.LEVEL_INFO
|
||||
LOG_LEVEL_NOTI = glog.LEVEL_NOTI
|
||||
LOG_LEVEL_WARN = glog.LEVEL_WARN
|
||||
LOG_LEVEL_ERRO = glog.LEVEL_ERRO
|
||||
LOG_LEVEL_CRIT = glog.LEVEL_CRIT
|
||||
)
|
||||
|
||||
// NewVar creates a *Var.
|
||||
//
|
||||
// 动态变量
|
||||
// NewVar returns a *gvar.Var.
|
||||
func NewVar(i interface{}, unsafe...bool) *Var {
|
||||
return gvar.New(i, unsafe...)
|
||||
}
|
||||
|
||||
// Wait blocks until all the web servers shutdown.
|
||||
//
|
||||
// 阻塞等待HTTPServer执行完成(同一进程多HTTPServer情况下)
|
||||
func Wait() {
|
||||
ghttp.Wait()
|
||||
}
|
||||
|
||||
// Dump dumps a variable to stdout with more manually readable.
|
||||
//
|
||||
// 打印变量
|
||||
func Dump(i...interface{}) {
|
||||
gutil.Dump(i...)
|
||||
}
|
||||
|
||||
// Throw throws a exception, which can be caught by Catch function.
|
||||
// Export exports a variable to string with more manually readable.
|
||||
func Export(i...interface{}) string {
|
||||
return gutil.Export(i...)
|
||||
}
|
||||
|
||||
// Throw throws a exception, which can be caught by TryCatch function.
|
||||
// It always be used in TryCatch function.
|
||||
//
|
||||
// 抛出一个异常
|
||||
func Throw(exception interface{}) {
|
||||
gutil.Throw(exception)
|
||||
}
|
||||
@ -55,4 +42,11 @@ func Throw(exception interface{}) {
|
||||
// TryCatch does the try...catch... logic.
|
||||
func TryCatch(try func(), catch ... func(exception interface{})) {
|
||||
gutil.TryCatch(try, catch...)
|
||||
}
|
||||
|
||||
// IsEmpty checks given value empty or not.
|
||||
// It returns false if value is: integer(0), bool(false), slice/map(len=0), nil;
|
||||
// or else true.
|
||||
func IsEmpty(value interface{}) bool {
|
||||
return empty.IsEmpty(value)
|
||||
}
|
||||
@ -10,23 +10,17 @@ import (
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
)
|
||||
|
||||
// Disable/Enabled debug of logging globally.
|
||||
//
|
||||
// 是否显示调试信息
|
||||
// SetDebug disables/enables debug level for logging globally.
|
||||
func SetDebug(debug bool) {
|
||||
glog.SetDebug(debug)
|
||||
}
|
||||
|
||||
// Set the logging level globally.
|
||||
//
|
||||
// 设置日志的显示等级
|
||||
// SetLogLevel sets the logging level globally.
|
||||
func SetLogLevel(level int) {
|
||||
glog.SetLevel(level)
|
||||
}
|
||||
|
||||
// Get the global logging level.
|
||||
//
|
||||
// 获取设置的日志显示等级
|
||||
// GetLogLevel returns the global logging level.
|
||||
func GetLogLevel() int {
|
||||
return glog.GetLevel()
|
||||
}
|
||||
@ -17,59 +17,42 @@ import (
|
||||
"github.com/gogf/gf/g/os/gcfg"
|
||||
)
|
||||
|
||||
// Get an instance of http server with specified name.
|
||||
//
|
||||
// HTTPServer单例对象
|
||||
// Server returns an instance of http server with specified name.
|
||||
func Server(name...interface{}) *ghttp.Server {
|
||||
return ghttp.GetServer(name...)
|
||||
}
|
||||
|
||||
// Get an instance of tcp server with specified name.
|
||||
//
|
||||
// TCPServer单例对象
|
||||
// TCPServer returns an instance of tcp server with specified name.
|
||||
func TCPServer(name...interface{}) *gtcp.Server {
|
||||
return gtcp.GetServer(name...)
|
||||
}
|
||||
|
||||
// Get an instance of udp server with specified name.
|
||||
//
|
||||
// UDPServer单例对象
|
||||
// UDPServer returns an instance of udp server with specified name.
|
||||
func UDPServer(name...interface{}) *gudp.Server {
|
||||
return gudp.GetServer(name...)
|
||||
}
|
||||
|
||||
// Get an instance of template engine object with specified name.
|
||||
//
|
||||
// 核心对象:View
|
||||
// View returns an instance of template engine object with specified name.
|
||||
func View(name...string) *gview.View {
|
||||
return gins.View(name...)
|
||||
}
|
||||
|
||||
// Get an instance of config object with specified default config file name.
|
||||
//
|
||||
// Config配置管理对象,
|
||||
// 配置文件目录查找依次为:启动参数cfgpath、当前程序运行目录
|
||||
// Config returns an instance of config object with specified name.
|
||||
func Config(file...string) *gcfg.Config {
|
||||
return gins.Config(file...)
|
||||
}
|
||||
|
||||
// Get an instance of database ORM object with specified configuration group name.
|
||||
//
|
||||
// 数据库操作对象,使用了连接池
|
||||
// Database returns an instance of database ORM object with specified configuration group name.
|
||||
func Database(name...string) gdb.DB {
|
||||
return gins.Database(name...)
|
||||
}
|
||||
|
||||
// Alias of Database.
|
||||
//
|
||||
// (别名)Database
|
||||
// Alias of Database. See Database.
|
||||
func DB(name...string) gdb.DB {
|
||||
return gins.Database(name...)
|
||||
}
|
||||
|
||||
// Get an instance of redis client with specified configuration group name.
|
||||
//
|
||||
// Redis操作对象,使用了连接池
|
||||
// Redis returns an instance of redis client with specified configuration group name.
|
||||
func Redis(name...string) *gredis.Redis {
|
||||
return gins.Redis(name...)
|
||||
}
|
||||
@ -8,9 +8,8 @@ package g
|
||||
|
||||
import "github.com/gogf/gf/g/net/ghttp"
|
||||
|
||||
// SetServerGraceful enables/disables graceful reload feature of ghttp Web Server.
|
||||
//
|
||||
// 是否开启WebServer的平滑重启特性。
|
||||
// SetServerGraceful enables/disables graceful/hot reload feature of http Web Server.
|
||||
// This feature is disabled in default.
|
||||
func SetServerGraceful(enabled bool) {
|
||||
ghttp.SetGraceful(enabled)
|
||||
}
|
||||
|
||||
96
g/net/ghttp/ghttp_client_config.go
Normal file
96
g/net/ghttp/ghttp_client_config.go
Normal file
@ -0,0 +1,96 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// HTTP客户端请求.
|
||||
|
||||
package ghttp
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 是否模拟浏览器模式(自动保存提交COOKIE)
|
||||
func (c *Client) SetBrowserMode(enabled bool) {
|
||||
c.browserMode = enabled
|
||||
}
|
||||
|
||||
// 设置HTTP Header
|
||||
func (c *Client) SetHeader(key, value string) {
|
||||
c.header[key] = value
|
||||
}
|
||||
|
||||
// 通过字符串设置HTTP Header
|
||||
func (c *Client) SetHeaderRaw(header string) {
|
||||
for _, line := range strings.Split(strings.TrimSpace(header), "\n") {
|
||||
array, _ := gregex.MatchString(`^([\w\-]+):\s*(.+)`, line)
|
||||
if len(array) >= 3 {
|
||||
c.header[array[1]] = array[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置COOKIE
|
||||
func (c *Client) SetCookie(key, value string) {
|
||||
c.cookies[key] = value
|
||||
}
|
||||
|
||||
// 使用Map设置COOKIE
|
||||
func (c *Client) SetCookieMap(cookieMap map[string]string) {
|
||||
for k, v := range cookieMap {
|
||||
c.cookies[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// 设置请求的URL前缀
|
||||
func (c *Client) SetPrefix(prefix string) {
|
||||
c.prefix = prefix
|
||||
}
|
||||
|
||||
// 设置请求过期时间
|
||||
func (c *Client) SetTimeOut(t time.Duration) {
|
||||
c.Timeout = t
|
||||
}
|
||||
|
||||
// 设置HTTP访问账号密码
|
||||
func (c *Client) SetBasicAuth(user, pass string) {
|
||||
c.authUser = user
|
||||
c.authPass = pass
|
||||
}
|
||||
|
||||
// 设置失败重试次数及间隔,失败仅针对网络请求失败情况。
|
||||
// 重试间隔时间单位为秒。
|
||||
func (c *Client) SetRetry(retryCount int, retryInterval int) {
|
||||
c.retryCount = retryCount
|
||||
c.retryInterval = retryInterval
|
||||
}
|
||||
|
||||
// 链式操作, See SetBrowserMode
|
||||
func (c *Client) BrowserMode(enabled bool) *Client {
|
||||
c.browserMode = enabled
|
||||
return c
|
||||
}
|
||||
|
||||
// 链式操作, See SetTimeOut
|
||||
func (c *Client) TimeOut(t time.Duration) *Client {
|
||||
c.Timeout = t
|
||||
return c
|
||||
}
|
||||
|
||||
// 链式操作, See SetBasicAuth
|
||||
func (c *Client) BasicAuth(user, pass string) *Client {
|
||||
c.authUser = user
|
||||
c.authPass = pass
|
||||
return c
|
||||
}
|
||||
|
||||
// 链式操作, See SetRetry
|
||||
func (c *Client) Retry(retryCount int, retryInterval int) *Client {
|
||||
c.retryCount = retryCount
|
||||
c.retryInterval = retryInterval
|
||||
return c
|
||||
}
|
||||
@ -9,89 +9,58 @@
|
||||
package ghttp
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/text/gregex"
|
||||
"time"
|
||||
"bytes"
|
||||
"strings"
|
||||
"net/http"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"io"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// http客户端
|
||||
type Client struct {
|
||||
http.Client // 底层http client对象
|
||||
header map[string]string // HEADER信息Map
|
||||
cookies map[string]string // 自定义COOKIE
|
||||
prefix string // 设置请求的URL前缀
|
||||
authUser string // HTTP基本权限设置:名称
|
||||
authPass string // HTTP基本权限设置:密码
|
||||
browserMode bool // 是否模拟浏览器模式(自动保存提交COOKIE)
|
||||
http.Client // 底层http client对象
|
||||
header map[string]string // HEADER信息Map
|
||||
cookies map[string]string // 自定义COOKIE
|
||||
prefix string // 设置请求的URL前缀
|
||||
authUser string // HTTP基本权限设置:名称
|
||||
authPass string // HTTP基本权限设置:密码
|
||||
browserMode bool // 是否模拟浏览器模式(自动保存提交COOKIE)
|
||||
retryCount int // 失败重试次数(网络失败情况下)
|
||||
retryInterval int // 失败重试间隔
|
||||
}
|
||||
|
||||
// http客户端对象指针
|
||||
func NewClient() (*Client) {
|
||||
func NewClient() *Client {
|
||||
return &Client{
|
||||
Client : http.Client {
|
||||
Transport: &http.Transport {
|
||||
DisableKeepAlives: true,
|
||||
},
|
||||
},
|
||||
header : make(map[string]string),
|
||||
cookies : make(map[string]string),
|
||||
header : make(map[string]string),
|
||||
cookies : make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// 是否模拟浏览器模式(自动保存提交COOKIE)
|
||||
func (c *Client) SetBrowserMode(enabled bool) {
|
||||
c.browserMode = enabled
|
||||
}
|
||||
|
||||
// 设置HTTP Header
|
||||
func (c *Client) SetHeader(key, value string) {
|
||||
c.header[key] = value
|
||||
}
|
||||
|
||||
// 通过字符串设置HTTP Header
|
||||
func (c *Client) SetHeaderRaw(header string) {
|
||||
for _, line := range strings.Split(strings.TrimSpace(header), "\n") {
|
||||
array, _ := gregex.MatchString(`^([\w\-]+):\s*(.+)`, line)
|
||||
if len(array) >= 3 {
|
||||
c.header[array[1]] = array[2]
|
||||
}
|
||||
// 克隆当前客户端对象,复制属性。
|
||||
func (c *Client) Clone() *Client {
|
||||
newClient := NewClient()
|
||||
*newClient = *c
|
||||
newClient.header = make(map[string]string)
|
||||
newClient.cookies = make(map[string]string)
|
||||
for k, v := range c.header {
|
||||
newClient.header[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// 设置COOKIE
|
||||
func (c *Client) SetCookie(key, value string) {
|
||||
c.cookies[key] = value
|
||||
}
|
||||
|
||||
// 使用Map设置COOKIE
|
||||
func (c *Client) SetCookieMap(cookieMap map[string]string) {
|
||||
for k, v := range cookieMap {
|
||||
c.cookies[k] = v
|
||||
for k, v := range c.cookies {
|
||||
newClient.cookies[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// 设置请求的URL前缀
|
||||
func (c *Client) SetPrefix(prefix string) {
|
||||
c.prefix = prefix
|
||||
}
|
||||
|
||||
// 设置请求过期时间
|
||||
func (c *Client) SetTimeOut(t time.Duration) {
|
||||
c.Timeout = t
|
||||
}
|
||||
|
||||
// 设置HTTP访问账号密码
|
||||
func (c *Client) SetBasicAuth(user, pass string) {
|
||||
c.authUser = user
|
||||
c.authPass = pass
|
||||
return newClient
|
||||
}
|
||||
|
||||
// GET请求
|
||||
@ -117,6 +86,7 @@ func (c *Client) Post(url string, data...string) (*ClientResponse, error) {
|
||||
}
|
||||
req := (*http.Request)(nil)
|
||||
if strings.Contains(param, "@file:") {
|
||||
// 文件上传
|
||||
buffer := new(bytes.Buffer)
|
||||
writer := multipart.NewWriter(buffer)
|
||||
for _, item := range strings.Split(param, "&") {
|
||||
@ -150,11 +120,17 @@ func (c *Client) Post(url string, data...string) (*ClientResponse, error) {
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
}
|
||||
} else {
|
||||
if r, err := http.NewRequest("POST", url, bytes.NewReader([]byte(param))); err != nil {
|
||||
// 识别提交数据格式
|
||||
paramBytes := []byte(param)
|
||||
if r, err := http.NewRequest("POST", url, bytes.NewReader(paramBytes)); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
req = r
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if json.Valid(paramBytes) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
} else {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
}
|
||||
}
|
||||
// 自定义header
|
||||
@ -181,9 +157,18 @@ func (c *Client) Post(url string, data...string) (*ClientResponse, error) {
|
||||
req.SetBasicAuth(c.authUser, c.authPass)
|
||||
}
|
||||
// 执行请求
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
resp := (*http.Response)(nil)
|
||||
for {
|
||||
if r, err := c.Do(req); err != nil {
|
||||
if c.retryCount > 0 {
|
||||
c.retryCount--
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
resp = r
|
||||
break
|
||||
}
|
||||
}
|
||||
r := &ClientResponse{
|
||||
cookies : make(map[string]string),
|
||||
@ -303,9 +288,18 @@ func (c *Client) DoRequest(method, url string, data...string) (*ClientResponse,
|
||||
}
|
||||
}
|
||||
// 执行请求
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
resp := (*http.Response)(nil)
|
||||
for {
|
||||
if r, err := c.Do(req); err != nil {
|
||||
if c.retryCount > 0 {
|
||||
c.retryCount--
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
resp = r
|
||||
break
|
||||
}
|
||||
}
|
||||
r := &ClientResponse{
|
||||
cookies : make(map[string]string),
|
||||
@ -57,7 +57,7 @@ func newRequest(s *Server, r *http.Request, w http.ResponseWriter) *Request {
|
||||
return request
|
||||
}
|
||||
|
||||
// 获取Web Socket连接对象(如果是非WS请求会失败,注意检查然会的error结果)
|
||||
// 获取Web Socket连接对象(如果是非WS请求会失败,注意检查返回的error结果)
|
||||
func (r *Request) WebSocket() (*WebSocket, error) {
|
||||
if conn, err := wsUpgrader.Upgrade(r.Response.ResponseWriter.ResponseWriter, r.Request, nil); err == nil {
|
||||
return &WebSocket {
|
||||
@ -81,26 +81,29 @@ func (r *Request) GetVar(key string, def ... interface{}) gvar.VarRead {
|
||||
|
||||
// 获取原始请求输入二进制。
|
||||
func (r *Request) GetRaw() []byte {
|
||||
err := error(nil)
|
||||
if r.rawContent == nil {
|
||||
r.rawContent, _ = ioutil.ReadAll(r.Body)
|
||||
r.rawContent, err = ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
r.Error("error reading request body: ", err)
|
||||
}
|
||||
}
|
||||
return r.rawContent
|
||||
}
|
||||
|
||||
// 获取原始请求输入字符串。
|
||||
func (r *Request) GetRawString() string {
|
||||
if r.rawContent == nil {
|
||||
r.rawContent, _ = ioutil.ReadAll(r.Body)
|
||||
}
|
||||
return string(r.rawContent)
|
||||
return string(r.GetRaw())
|
||||
}
|
||||
|
||||
// 获取原始json请求输入字符串,并解析为json对象
|
||||
func (r *Request) GetJson() *gjson.Json {
|
||||
data := r.GetRaw()
|
||||
if data != nil {
|
||||
if len(data) > 0 {
|
||||
if j, err := gjson.DecodeToJson(data); err == nil {
|
||||
return j
|
||||
} else {
|
||||
r.Error(err, ": ", string(data))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@ -221,14 +224,14 @@ func (r *Request) GetReferer() string {
|
||||
|
||||
// 获得结构体对象的参数名称标签,构成map返回
|
||||
func (r *Request) getStructParamsTagMap(object interface{}) map[string]string {
|
||||
tagmap := make(map[string]string)
|
||||
tagMap := make(map[string]string)
|
||||
fields := structs.Fields(object)
|
||||
for _, field := range fields {
|
||||
if tag := field.Tag("params"); tag != "" {
|
||||
for _, v := range strings.Split(tag, ",") {
|
||||
tagmap[strings.TrimSpace(v)] = field.Name()
|
||||
tagMap[strings.TrimSpace(v)] = field.Name()
|
||||
}
|
||||
}
|
||||
}
|
||||
return tagmap
|
||||
return tagMap
|
||||
}
|
||||
@ -26,21 +26,21 @@ func (r *Request) setBasicAuth(tips...string) {
|
||||
}
|
||||
|
||||
// 设置HTTP基础账号密码认证,如果用户没有提交账号密码,那么提示用户输出信息。
|
||||
// 验证成功之后返回true,否则返回false
|
||||
// 验证成功之后返回true,否则返回false。
|
||||
func (r *Request) BasicAuth(user, pass string, tips...string) bool {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
r.setBasicAuth(tips...)
|
||||
return false
|
||||
}
|
||||
auths := strings.SplitN(auth, " ", 2)
|
||||
if len(auths) != 2 {
|
||||
authArray := strings.SplitN(auth, " ", 2)
|
||||
if len(authArray) != 2 {
|
||||
r.Response.WriteStatus(http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
switch auths[0] {
|
||||
switch authArray[0] {
|
||||
case "Basic":
|
||||
authStr, err := gbase64.Decode(auths[1])
|
||||
authStr, err := gbase64.Decode(authArray[1])
|
||||
if err != nil {
|
||||
r.Response.WriteStatus(http.StatusForbidden, err.Error())
|
||||
return false
|
||||
@ -54,11 +54,12 @@ func (r *Request) BasicAuth(user, pass string, tips...string) bool {
|
||||
r.setBasicAuth(tips...)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
|
||||
default:
|
||||
r.Response.WriteStatus(http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@ -4,4 +4,11 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package container
|
||||
package ghttp
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 打印error日志
|
||||
func (r *Request) Error(value... interface{}) {
|
||||
r.Server.handleErrorLog(fmt.Sprint(value...), r)
|
||||
}
|
||||
@ -169,7 +169,7 @@ func (r *Request) GetPostMap(def...map[string]string) map[string]string {
|
||||
}
|
||||
|
||||
// 将所有的request参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系
|
||||
func (r *Request) GetPostToStruct(object interface{}, mapping...map[string]string) {
|
||||
func (r *Request) GetPostToStruct(object interface{}, mapping...map[string]string) error {
|
||||
tagmap := r.getStructParamsTagMap(object)
|
||||
if len(mapping) > 0 {
|
||||
for k, v := range mapping[0] {
|
||||
@ -180,5 +180,5 @@ func (r *Request) GetPostToStruct(object interface{}, mapping...map[string]strin
|
||||
for k, v := range r.GetPostMap() {
|
||||
params[k] = v
|
||||
}
|
||||
gconv.Struct(params, object, tagmap)
|
||||
return gconv.Struct(params, object, tagmap)
|
||||
}
|
||||
@ -177,7 +177,7 @@ func (r *Request) GetQueryMap(def ... map[string]string) map[string]string {
|
||||
}
|
||||
|
||||
// 将所有的get参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系
|
||||
func (r *Request) GetQueryToStruct(object interface{}, mapping...map[string]string) {
|
||||
func (r *Request) GetQueryToStruct(object interface{}, mapping...map[string]string) error {
|
||||
tagmap := r.getStructParamsTagMap(object)
|
||||
if len(mapping) > 0 {
|
||||
for k, v := range mapping[0] {
|
||||
@ -188,5 +188,5 @@ func (r *Request) GetQueryToStruct(object interface{}, mapping...map[string]stri
|
||||
for k, v := range r.GetQueryMap() {
|
||||
params[k] = v
|
||||
}
|
||||
gconv.Struct(params, object, tagmap)
|
||||
return gconv.Struct(params, object, tagmap)
|
||||
}
|
||||
@ -162,7 +162,7 @@ func (r *Request) GetRequestMap(def...map[string]string) map[string]string {
|
||||
}
|
||||
|
||||
// 将所有的request参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系
|
||||
func (r *Request) GetRequestToStruct(object interface{}, mapping...map[string]string) {
|
||||
func (r *Request) GetRequestToStruct(object interface{}, mapping...map[string]string) error {
|
||||
tagmap := r.getStructParamsTagMap(object)
|
||||
if len(mapping) > 0 {
|
||||
for k, v := range mapping[0] {
|
||||
@ -178,6 +178,6 @@ func (r *Request) GetRequestToStruct(object interface{}, mapping...map[string]st
|
||||
params = j.ToMap()
|
||||
}
|
||||
}
|
||||
gconv.Struct(params, object, tagmap)
|
||||
return gconv.Struct(params, object, tagmap)
|
||||
}
|
||||
|
||||
|
||||
@ -56,7 +56,7 @@ func (r *Response) CORS(options CORSOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
// 允许请求跨域访问(使用more配置).
|
||||
// 允许请求跨域访问(使用默认配置).
|
||||
func (r *Response) CORSDefault() {
|
||||
r.CORS(r.DefaultCORSOptions())
|
||||
}
|
||||
|
||||
@ -15,7 +15,6 @@ import (
|
||||
"github.com/gogf/gf/g/container/gtype"
|
||||
"github.com/gogf/gf/g/os/gcache"
|
||||
"github.com/gogf/gf/g/os/genv"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/os/gproc"
|
||||
"github.com/gogf/gf/g/os/gtimer"
|
||||
@ -108,7 +107,10 @@ const (
|
||||
HOOK_AFTER_SERVE = "AfterServe"
|
||||
HOOK_BEFORE_OUTPUT = "BeforeOutput"
|
||||
HOOK_AFTER_OUTPUT = "AfterOutput"
|
||||
|
||||
// deprecated.
|
||||
HOOK_BEFORE_CLOSE = "BeforeClose"
|
||||
// deprecated.
|
||||
HOOK_AFTER_CLOSE = "AfterClose"
|
||||
|
||||
HTTP_METHODS = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
|
||||
@ -187,9 +189,9 @@ func serverProcessInit() {
|
||||
}
|
||||
|
||||
// 是否处于开发环境
|
||||
if gfile.MainPkgPath() != "" {
|
||||
glog.Debug("GF notices that you're in develop environment, so error logs are auto enabled to stdout.")
|
||||
}
|
||||
//if gfile.MainPkgPath() != "" {
|
||||
// glog.Debug("GF notices that you're in develop environment, so error logs are auto enabled to stdout.")
|
||||
//}
|
||||
}
|
||||
|
||||
// 获取/创建一个默认配置的HTTP Server(默认监听端口是80)
|
||||
@ -217,8 +219,6 @@ func GetServer(name...interface{}) (*Server) {
|
||||
servedCount : gtype.NewInt(),
|
||||
logger : glog.New(),
|
||||
}
|
||||
// 日志的标准输出默认关闭,但是错误信息会特殊处理
|
||||
s.logger.SetStdPrint(false)
|
||||
// 初始化时使用默认配置
|
||||
s.SetConfig(defaultServerConfig)
|
||||
// 记录到全局ServerMap中
|
||||
@ -237,12 +237,17 @@ func (s *Server) Start() error {
|
||||
return errors.New("server is already running")
|
||||
}
|
||||
|
||||
// 没有注册任何路由,且没有开启文件服务,那么提示错误
|
||||
if len(s.routesMap) == 0 && !s.config.FileServerEnabled {
|
||||
glog.Fatal("[ghttp] no router set or static feature enabled, did you forget import the router?")
|
||||
}
|
||||
|
||||
// 底层http server配置
|
||||
if s.config.Handler == nil {
|
||||
s.config.Handler = http.HandlerFunc(s.defaultHttpHandle)
|
||||
}
|
||||
// 不允许访问的路由注册(使用HOOK实现)
|
||||
// @TODO 去掉HOOK的实现方式
|
||||
// TODO 去掉HOOK的实现方式
|
||||
if s.config.DenyRoutes != nil {
|
||||
for _, v := range s.config.DenyRoutes {
|
||||
s.BindHookHandler(v, HOOK_BEFORE_SERVE, func(r *Request) {
|
||||
@ -277,7 +282,7 @@ func (s *Server) Start() error {
|
||||
if gproc.IsChild() {
|
||||
gtimer.SetTimeout(2*time.Second, func() {
|
||||
if err := gproc.Send(gproc.PPid(), []byte("exit"), gADMIN_GPROC_COMM_GROUP); err != nil {
|
||||
glog.Error("ghttp server error in process communication:", err)
|
||||
glog.Error("[ghttp] server error in process communication:", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -350,7 +355,10 @@ func (s *Server) GetRouteMap() string {
|
||||
}
|
||||
addr := s.config.Addr
|
||||
if s.config.HTTPSAddr != "" {
|
||||
addr += ",tls" + s.config.HTTPSAddr
|
||||
if len(addr) > 0 {
|
||||
addr += ","
|
||||
}
|
||||
addr += "tls" + s.config.HTTPSAddr
|
||||
}
|
||||
for _, a := range m {
|
||||
data := make([]string, 8)
|
||||
@ -398,7 +406,8 @@ func Wait() {
|
||||
// 开启底层Web Server执行
|
||||
func (s *Server) startServer(fdMap listenerFdMap) {
|
||||
var httpsEnabled bool
|
||||
if len(s.config.HTTPSCertPath) > 0 && len(s.config.HTTPSKeyPath) > 0 {
|
||||
// 判断是否启用HTTPS
|
||||
if len(s.config.TLSConfig.Certificates) > 0 || (len(s.config.HTTPSCertPath) > 0 && len(s.config.HTTPSKeyPath) > 0) {
|
||||
// ================
|
||||
// HTTPS
|
||||
// ================
|
||||
@ -479,7 +488,7 @@ func (s *Server) startServer(fdMap listenerFdMap) {
|
||||
s.serverCount.Add(1)
|
||||
err := (error)(nil)
|
||||
if server.isHttps {
|
||||
err = server.ListenAndServeTLS(s.config.HTTPSCertPath, s.config.HTTPSKeyPath)
|
||||
err = server.ListenAndServeTLS(s.config.HTTPSCertPath, s.config.HTTPSKeyPath, &s.config.TLSConfig)
|
||||
} else {
|
||||
err = server.ListenAndServe()
|
||||
}
|
||||
|
||||
@ -168,7 +168,7 @@ func getServerFdMap() map[string]listenerFdMap {
|
||||
func bufferToServerFdMap(buffer []byte) map[string]listenerFdMap {
|
||||
sfm := make(map[string]listenerFdMap)
|
||||
if len(buffer) > 0 {
|
||||
j, _ := gjson.LoadContent(buffer, "json")
|
||||
j, _ := gjson.LoadContent(buffer)
|
||||
for k, _ := range j.ToMap() {
|
||||
m := make(map[string]string)
|
||||
for k, v := range j.GetMap(k) {
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
package ghttp
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
@ -44,6 +45,7 @@ type ServerConfig struct {
|
||||
WriteTimeout time.Duration // 写入超时
|
||||
IdleTimeout time.Duration // 等待超时
|
||||
MaxHeaderBytes int // 最大的header长度
|
||||
TLSConfig tls.Config
|
||||
|
||||
// 静态文件配置
|
||||
IndexFiles []string // 默认访问的文件列表
|
||||
@ -72,10 +74,11 @@ type ServerConfig struct {
|
||||
Rewrites map[string]string // URI Rewrite重写配置
|
||||
|
||||
// 日志配置
|
||||
LogPath string // 存放日志的目录路径
|
||||
LogHandler LogHandler // 自定义日志处理回调方法
|
||||
ErrorLogEnabled bool // 是否开启error log
|
||||
AccessLogEnabled bool // 是否开启access log
|
||||
LogPath string // 存放日志的目录路径(默认为空,表示不写文件)
|
||||
LogHandler LogHandler // 自定义日志处理回调方法(默认为空)
|
||||
LogStdPrint bool // 是否打印日志到终端(默认开启)
|
||||
ErrorLogEnabled bool // 是否开启error log(默认开启)
|
||||
AccessLogEnabled bool // 是否开启access log(默认关闭)
|
||||
|
||||
// 其他设置
|
||||
NameToUriType int // 服务注册时对象和方法名称转换为URI时的规则
|
||||
@ -108,12 +111,11 @@ var defaultServerConfig = ServerConfig {
|
||||
SessionMaxAge : gDEFAULT_SESSION_MAX_AGE,
|
||||
SessionIdName : gDEFAULT_SESSION_ID_NAME,
|
||||
|
||||
LogStdPrint : true,
|
||||
ErrorLogEnabled : true,
|
||||
|
||||
AccessLogEnabled : false,
|
||||
GzipContentTypes : defaultGzipContentTypes,
|
||||
|
||||
DumpRouteMap : true,
|
||||
|
||||
RouterCacheExpire : 60,
|
||||
Rewrites : make(map[string]string),
|
||||
}
|
||||
@ -191,28 +193,46 @@ func (s *Server)SetHTTPSPort(port...int) {
|
||||
}
|
||||
}
|
||||
|
||||
// 开启HTTPS支持,但是必须提供Cert和Key文件
|
||||
func (s *Server)EnableHTTPS(certFile, keyFile string) {
|
||||
// 开启HTTPS支持,但是必须提供Cert和Key文件,tlsConfig为可选项
|
||||
func (s *Server)EnableHTTPS(certFile, keyFile string, tlsConfig...tls.Config) {
|
||||
if s.Status() == SERVER_STATUS_RUNNING {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
return
|
||||
}
|
||||
certFileRealPath := gfile.RealPath(certFile)
|
||||
if certFileRealPath == "" {
|
||||
certFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + certFileRealPath)
|
||||
certFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + certFile)
|
||||
if certFileRealPath == "" {
|
||||
certFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + certFile)
|
||||
}
|
||||
}
|
||||
if certFileRealPath == "" {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] EnableHTTPS failed: certFile "%s" does not exist`, certFile))
|
||||
}
|
||||
keyFileRealPath := gfile.RealPath(keyFile)
|
||||
if keyFileRealPath == "" {
|
||||
keyFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + keyFileRealPath)
|
||||
keyFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + keyFile)
|
||||
if keyFileRealPath == "" {
|
||||
keyFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + keyFile)
|
||||
}
|
||||
}
|
||||
if keyFileRealPath == "" {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] EnableHTTPS failed: keyFile "%s" does not exist`, keyFile))
|
||||
}
|
||||
s.config.HTTPSCertPath = certFileRealPath
|
||||
s.config.HTTPSKeyPath = keyFileRealPath
|
||||
if len(tlsConfig) > 0 {
|
||||
s.config.TLSConfig = tlsConfig[0]
|
||||
}
|
||||
}
|
||||
|
||||
// 设置TLS配置对象
|
||||
func (s *Server)SetTLSConfig(tlsConfig tls.Config) {
|
||||
if s.Status() == SERVER_STATUS_RUNNING {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
return
|
||||
}
|
||||
s.config.TLSConfig = tlsConfig
|
||||
}
|
||||
|
||||
// 设置http server参数 - ReadTimeout
|
||||
|
||||
@ -10,7 +10,10 @@ import (
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
)
|
||||
|
||||
// 设置日志目录
|
||||
// 设置日志目录,只有在设置了日志目录的情况下才会输出日志到日志文件中。
|
||||
// 日志文件路径格式为:
|
||||
// 1. 请求日志: access/YYYY-MM-DD.log
|
||||
// 2. 错误日志: error/YYYY-MM-DD.log
|
||||
func (s *Server)SetLogPath(path string) {
|
||||
if s.Status() == SERVER_STATUS_RUNNING {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
@ -23,6 +26,16 @@ func (s *Server)SetLogPath(path string) {
|
||||
s.logger.SetPath(path)
|
||||
}
|
||||
|
||||
// 设置日志内容是否输出到终端,默认情况下只有错误日志才会自动输出到终端。
|
||||
// 如果需要输出请求日志到终端,默认情况下使用SetAccessLogEnabled方法开启请求日志特性即可。
|
||||
func (s *Server)SetLogStdPrint(enabled bool) {
|
||||
if s.Status() == SERVER_STATUS_RUNNING {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
return
|
||||
}
|
||||
s.config.LogStdPrint = enabled
|
||||
}
|
||||
|
||||
// 设置是否开启access log日志功能
|
||||
func (s *Server)SetAccessLogEnabled(enabled bool) {
|
||||
if s.Status() == SERVER_STATUS_RUNNING {
|
||||
@ -51,7 +64,7 @@ func (s *Server) SetLogHandler(handler LogHandler) {
|
||||
}
|
||||
|
||||
// 获取日志写入的回调函数
|
||||
func (s *Server) GetLogHandler() LogHandler {
|
||||
func (s *Server)GetLogHandler() LogHandler {
|
||||
return s.config.LogHandler
|
||||
}
|
||||
|
||||
|
||||
@ -57,15 +57,12 @@ func (s *Server)SetServerRoot(root string) {
|
||||
return
|
||||
}
|
||||
// RealPath的作用除了校验地址正确性以外,还转换分隔符号为当前系统正确的文件分隔符号
|
||||
path := gfile.RealPath(root)
|
||||
if path == "" {
|
||||
path = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + root)
|
||||
realPath, err := gfile.Search(root)
|
||||
if err != nil {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] SetServerRoot failed: %s`, err.Error()))
|
||||
}
|
||||
if path == "" {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] SetServerRoot failed: path "%s" does not exist`, root))
|
||||
}
|
||||
glog.Debug("[ghttp] SetServerRoot path:", path)
|
||||
s.config.SearchPaths = []string{strings.TrimRight(path, gfile.Separator)}
|
||||
glog.Debug("[ghttp] SetServerRoot path:", realPath)
|
||||
s.config.SearchPaths = []string{strings.TrimRight(realPath, gfile.Separator)}
|
||||
s.config.FileServerEnabled = true
|
||||
}
|
||||
|
||||
@ -75,13 +72,9 @@ func (s *Server) AddSearchPath(path string) {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
return
|
||||
}
|
||||
// RealPath的作用除了校验地址正确性以外,还转换分隔符号为当前系统正确的文件分隔符号
|
||||
realPath := gfile.RealPath(path)
|
||||
if realPath == "" {
|
||||
realPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + path)
|
||||
}
|
||||
if realPath == "" {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] AddSearchPath failed: path "%s" does not exist`, path))
|
||||
realPath, err := gfile.Search(path)
|
||||
if err != nil {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] AddSearchPath failed: %s`, err.Error()))
|
||||
}
|
||||
s.config.SearchPaths = append(s.config.SearchPaths, realPath)
|
||||
s.config.FileServerEnabled = true
|
||||
@ -93,13 +86,9 @@ func (s *Server) AddStaticPath(prefix string, path string) {
|
||||
glog.Error(gCHANGE_CONFIG_WHILE_RUNNING_ERROR)
|
||||
return
|
||||
}
|
||||
// RealPath的作用除了校验地址正确性以外,还转换分隔符号为当前系统正确的文件分隔符号
|
||||
realPath := gfile.RealPath(path)
|
||||
if realPath == "" {
|
||||
realPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + path)
|
||||
}
|
||||
if realPath == "" {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] AddStaticPath failed: path "%s" does not exist`, path))
|
||||
realPath, err := gfile.Search(path)
|
||||
if err != nil {
|
||||
glog.Fatal(fmt.Sprintf(`[ghttp] AddStaticPath failed: %s`, err.Error()))
|
||||
}
|
||||
addItem := staticPathItem {
|
||||
prefix : prefix,
|
||||
|
||||
@ -84,18 +84,22 @@ func (s *gracefulServer) setFd(fd int) {
|
||||
}
|
||||
|
||||
// 执行HTTPS监听
|
||||
func (s *gracefulServer) ListenAndServeTLS(certFile, keyFile string) error {
|
||||
func (s *gracefulServer) ListenAndServeTLS(certFile, keyFile string, tlsConfig...*tls.Config) error {
|
||||
addr := s.httpServer.Addr
|
||||
config := &tls.Config{}
|
||||
if s.httpServer.TLSConfig != nil {
|
||||
config := (*tls.Config)(nil)
|
||||
if len(tlsConfig) > 0 {
|
||||
config = tlsConfig[0]
|
||||
} else if s.httpServer.TLSConfig != nil {
|
||||
*config = *s.httpServer.TLSConfig
|
||||
}
|
||||
if config.NextProtos == nil {
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
}
|
||||
err := error(nil)
|
||||
config.Certificates = make([]tls.Certificate, 1)
|
||||
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if len(config.Certificates) == 0 {
|
||||
config.Certificates = make([]tls.Certificate, 1)
|
||||
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf(`open cert file "%s","%s" failed: %s`, certFile, keyFile, err.Error()))
|
||||
}
|
||||
|
||||
@ -35,6 +35,12 @@ func (s *Server)handleRequest(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Path = rewrite
|
||||
}
|
||||
}
|
||||
|
||||
// URI默认值
|
||||
if r.URL.Path == "" {
|
||||
r.URL.Path = "/"
|
||||
}
|
||||
|
||||
// 去掉末尾的"/"号
|
||||
if r.URL.Path != "/" {
|
||||
for r.URL.Path[len(r.URL.Path) - 1] == '/' {
|
||||
@ -52,6 +58,13 @@ func (s *Server)handleRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if !request.IsExited() {
|
||||
s.callHookHandler(HOOK_BEFORE_OUTPUT, request)
|
||||
}
|
||||
// error log
|
||||
if e := recover(); e != nil {
|
||||
request.Response.WriteStatus(http.StatusInternalServerError)
|
||||
s.handleErrorLog(e, request)
|
||||
}
|
||||
// access log
|
||||
s.handleAccessLog(request)
|
||||
// 输出Cookie
|
||||
request.Cookie.Output()
|
||||
// 输出缓冲区
|
||||
@ -60,18 +73,8 @@ func (s *Server)handleRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if !request.IsExited() {
|
||||
s.callHookHandler(HOOK_AFTER_OUTPUT, request)
|
||||
}
|
||||
// 事件 - BeforeClose
|
||||
s.callHookHandler(HOOK_BEFORE_CLOSE, request)
|
||||
// access log
|
||||
s.handleAccessLog(request)
|
||||
// error log使用recover进行判断
|
||||
if e := recover(); e != nil {
|
||||
request.Response.WriteStatus(http.StatusInternalServerError)
|
||||
s.handleErrorLog(e, request)
|
||||
}
|
||||
// 更新Session会话超时时间
|
||||
request.Session.UpdateExpire()
|
||||
s.callHookHandler(HOOK_AFTER_CLOSE, request)
|
||||
}()
|
||||
|
||||
// ============================================================
|
||||
|
||||
@ -9,7 +9,7 @@ package ghttp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gtime"
|
||||
)
|
||||
|
||||
// 处理服务错误信息,主要是panic,http请求的status由access log进行管理
|
||||
@ -22,19 +22,19 @@ func (s *Server) handleAccessLog(r *Request) {
|
||||
v(r)
|
||||
return
|
||||
}
|
||||
content := fmt.Sprintf(`"%s %s %s %s" %d`,
|
||||
r.Method, r.Host, r.URL.String(), r.Proto,
|
||||
content := fmt.Sprintf(`%d "%s %s %s %s"`,
|
||||
r.Response.Status,
|
||||
r.Method, r.Host, r.URL.String(), r.Proto,
|
||||
)
|
||||
content += fmt.Sprintf(` %.3f`, float64(r.LeaveTime - r.EnterTime)/1000)
|
||||
content += fmt.Sprintf(`, %s, "%s", "%s"`, r.GetClientIp(), r.Referer(), r.UserAgent())
|
||||
s.logger.Cat("access").Backtrace(false, 2).Println(content)
|
||||
s.logger.Cat("access").Backtrace(false, 2).StdPrint(s.config.LogStdPrint).Println(content)
|
||||
}
|
||||
|
||||
// 处理服务错误信息,主要是panic,http请求的status由access log进行管理
|
||||
func (s *Server) handleErrorLog(error interface{}, r *Request) {
|
||||
// 错误输出默认是开启的
|
||||
if !s.IsErrorLogEnabled() && gfile.MainPkgPath() == "" {
|
||||
if !s.IsErrorLogEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
@ -46,17 +46,11 @@ func (s *Server) handleErrorLog(error interface{}, r *Request) {
|
||||
|
||||
// 错误日志信息
|
||||
content := fmt.Sprintf(`%v, "%s %s %s %s"`, error, r.Method, r.Host, r.URL.String(), r.Proto)
|
||||
content += fmt.Sprintf(` %.3f`, float64(r.LeaveTime - r.EnterTime)/1000)
|
||||
content += fmt.Sprintf(`, %s, "%s", "%s"`, r.GetClientIp(), r.Referer(), r.UserAgent())
|
||||
|
||||
if s.logger.GetPath() == "" {
|
||||
// 错误信息特殊处理,在未开启日志文件保存时强制强制输出到终端
|
||||
s.logger.Cat("error").Backtrace(true, 2).StdPrint(true).Error(content)
|
||||
if r.LeaveTime > r.EnterTime {
|
||||
content += fmt.Sprintf(` %.3f`, float64(r.LeaveTime - r.EnterTime)/1000)
|
||||
} else {
|
||||
s.logger.Cat("error").Backtrace(true, 2).Error(content)
|
||||
// 开发环境下(MainPkgPath)自动输出错误信息到标准输出
|
||||
if gfile.MainPkgPath() != "" {
|
||||
s.logger.Cat("error").Backtrace(true, 2).StdPrint(true).Error(content)
|
||||
}
|
||||
content += fmt.Sprintf(` %.3f`, float64(gtime.Microsecond() - r.EnterTime)/1000)
|
||||
}
|
||||
content += fmt.Sprintf(`, %s, "%s", "%s"`, r.GetClientIp(), r.Referer(), r.UserAgent())
|
||||
s.logger.Cat("error").Backtrace(true, 2).StdPrint(s.config.LogStdPrint).Error(content)
|
||||
}
|
||||
|
||||
@ -37,7 +37,7 @@ func (s *Server)parsePattern(pattern string) (domain, method, path string, err e
|
||||
}
|
||||
}
|
||||
if path == "" {
|
||||
err = errors.New("invalid pattern")
|
||||
err = errors.New("invalid pattern: URI should not be empty")
|
||||
}
|
||||
// 去掉末尾的"/"符号,与路由匹配时处理一致
|
||||
if path != "/" {
|
||||
@ -72,11 +72,11 @@ func (s *Server) setHandler(pattern string, handler *handlerItem, hook ... strin
|
||||
}
|
||||
domain, method, uri, err := s.parsePattern(pattern)
|
||||
if err != nil {
|
||||
glog.Error("invalid pattern:", pattern)
|
||||
glog.Error("invalid pattern:", pattern, err)
|
||||
return
|
||||
}
|
||||
if len(uri) == 0 || uri[0] != '/' {
|
||||
glog.Error("invalid pattern:", pattern)
|
||||
glog.Error("invalid pattern:", pattern, "URI should lead with '/'")
|
||||
return
|
||||
}
|
||||
// 注册地址记录及重复注册判断
|
||||
@ -84,7 +84,7 @@ func (s *Server) setHandler(pattern string, handler *handlerItem, hook ... strin
|
||||
caller := s.getHandlerRegisterCallerLine(handler)
|
||||
if len(hook) == 0 {
|
||||
if item, ok := s.routesMap[regkey]; ok {
|
||||
glog.Errorfln(`duplicated route registry "%s", already registered in %s`, pattern, item[0].file)
|
||||
glog.Errorfln(`duplicated route registry "%s", already registered at %s`, pattern, item[0].file)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,14 +43,22 @@ func (s *Server)BindController(pattern string, c Controller, methods...string) {
|
||||
if mname == "Init" || mname == "Shut" || mname == "Exit" {
|
||||
continue
|
||||
}
|
||||
if _, ok := v.Method(i).Interface().(func()); !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func()" is required`, v.Method(i).Type().String())
|
||||
continue
|
||||
}
|
||||
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
|
||||
if ctlName[0] == '*' {
|
||||
ctlName = fmt.Sprintf(`(%s)`, ctlName)
|
||||
}
|
||||
if _, ok := v.Method(i).Interface().(func()); !ok {
|
||||
if len(methodMap) > 0 {
|
||||
// 指定的方法名称注册,那么需要使用错误提示
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func()" is required`,
|
||||
pkgPath, ctlName, mname, v.Method(i).Type().String())
|
||||
} else {
|
||||
// 否则只是Debug提示
|
||||
glog.Debugfln(`ignore route method: %s.%s.%s defined as "%s", no match "func()"`,
|
||||
pkgPath, ctlName, mname, v.Method(i).Type().String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(pattern, sname, mname, true)
|
||||
m[key] = &handlerItem {
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, mname),
|
||||
@ -93,16 +101,17 @@ func (s *Server)BindControllerMethod(pattern string, c Controller, method string
|
||||
glog.Error("invalid method name:" + mname)
|
||||
return
|
||||
}
|
||||
if _, ok := fval.Interface().(func()); !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func()" is required`, fval.Type().String())
|
||||
return
|
||||
}
|
||||
pkgPath := t.Elem().PkgPath()
|
||||
pkgName := gfile.Basename(pkgPath)
|
||||
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
|
||||
if ctlName[0] == '*' {
|
||||
ctlName = fmt.Sprintf(`(%s)`, ctlName)
|
||||
}
|
||||
if _, ok := fval.Interface().(func()); !ok {
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func()" is required`,
|
||||
pkgPath, ctlName, mname, fval.Type().String())
|
||||
return
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(pattern, sname, mname, false)
|
||||
m[key] = &handlerItem {
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, mname),
|
||||
@ -132,15 +141,16 @@ func (s *Server)BindControllerRest(pattern string, c Controller) {
|
||||
if _, ok := methodsMap[method]; !ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := v.Method(i).Interface().(func()); !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func()" is required`, v.Method(i).Type().String())
|
||||
return
|
||||
}
|
||||
pkgName := gfile.Basename(pkgPath)
|
||||
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
|
||||
if ctlName[0] == '*' {
|
||||
ctlName = fmt.Sprintf(`(%s)`, ctlName)
|
||||
}
|
||||
if _, ok := v.Method(i).Interface().(func()); !ok {
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func()" is required`,
|
||||
pkgPath, ctlName, mname, v.Method(i).Type().String())
|
||||
return
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(mname + ":" + pattern, sname, mname, false)
|
||||
m[key] = &handlerItem {
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, mname),
|
||||
|
||||
@ -49,15 +49,23 @@ func (s *Server)BindObject(pattern string, obj interface{}, methods...string) {
|
||||
if mname == "Init" || mname == "Shut" {
|
||||
continue
|
||||
}
|
||||
faddr, ok := v.Method(i).Interface().(func(*Request))
|
||||
if !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func(*Request))" is required`, v.Method(i).Type().String())
|
||||
continue
|
||||
}
|
||||
objName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
|
||||
if objName[0] == '*' {
|
||||
objName = fmt.Sprintf(`(%s)`, objName)
|
||||
}
|
||||
faddr, ok := v.Method(i).Interface().(func(*Request))
|
||||
if !ok {
|
||||
if len(methodMap) > 0 {
|
||||
// 指定的方法名称注册,那么需要使用错误提示
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" is required`,
|
||||
pkgPath, objName, mname, v.Method(i).Type().String())
|
||||
} else {
|
||||
// 否则只是Debug提示
|
||||
glog.Debugfln(`ignore route method: %s.%s.%s defined as "%s", no match "func(*ghttp.Request)"`,
|
||||
pkgPath, objName, mname, v.Method(i).Type().String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(pattern, sname, mname, true)
|
||||
m[key] = &handlerItem {
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, mname),
|
||||
@ -103,11 +111,6 @@ func (s *Server)BindObjectMethod(pattern string, obj interface{}, method string)
|
||||
glog.Error("invalid method name:" + mname)
|
||||
return
|
||||
}
|
||||
faddr, ok := fval.Interface().(func(*Request))
|
||||
if !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func(*Request)" is required`, fval.Type().String())
|
||||
return
|
||||
}
|
||||
finit := (func(*Request))(nil)
|
||||
fshut := (func(*Request))(nil)
|
||||
if v.MethodByName("Init").IsValid() {
|
||||
@ -122,6 +125,12 @@ func (s *Server)BindObjectMethod(pattern string, obj interface{}, method string)
|
||||
if objName[0] == '*' {
|
||||
objName = fmt.Sprintf(`(%s)`, objName)
|
||||
}
|
||||
faddr, ok := fval.Interface().(func(*Request))
|
||||
if !ok {
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" is required`,
|
||||
pkgPath, objName, mname, fval.Type().String())
|
||||
return
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(pattern, sname, mname, false)
|
||||
m[key] = &handlerItem{
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, mname),
|
||||
@ -158,16 +167,17 @@ func (s *Server)BindObjectRest(pattern string, obj interface{}) {
|
||||
if _, ok := methodsMap[method]; !ok {
|
||||
continue
|
||||
}
|
||||
faddr, ok := v.Method(i).Interface().(func(*Request))
|
||||
if !ok {
|
||||
glog.Errorfln(`invalid method definition "%s", while "func(*Request)" is required`, v.Method(i).Type().String())
|
||||
continue
|
||||
}
|
||||
pkgName := gfile.Basename(pkgPath)
|
||||
objName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
|
||||
if objName[0] == '*' {
|
||||
objName = fmt.Sprintf(`(%s)`, objName)
|
||||
}
|
||||
faddr, ok := v.Method(i).Interface().(func(*Request))
|
||||
if !ok {
|
||||
glog.Errorfln(`invalid route method: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" is required`,
|
||||
pkgPath, objName, mname, v.Method(i).Type().String())
|
||||
continue
|
||||
}
|
||||
key := s.mergeBuildInNameToPattern(mname + ":" + pattern, sname, mname, false)
|
||||
m[key] = &handlerItem {
|
||||
name : fmt.Sprintf(`%s.%s.%s`, pkgPath, objName, mname),
|
||||
|
||||
@ -1,59 +0,0 @@
|
||||
// Package greuseport provides Listen and Dial functions that set socket
|
||||
// options in order to be able to reuse ports. You should only use this
|
||||
// package if you know what SO_REUSEADDR and SO_REUSEPORT are.
|
||||
//
|
||||
// For example:
|
||||
//
|
||||
// // listen on the same port.
|
||||
// l1, _ := reuse.Listen("tcp", "127.0.0.1:1234")
|
||||
// l2, _ := reuse.Listen("tcp", "127.0.0.1:1234")
|
||||
//
|
||||
// // dial from the same port.
|
||||
// l1, _ := reuse.Listen("tcp", "127.0.0.1:1234")
|
||||
// l2, _ := reuse.Listen("tcp", "127.0.0.1:1235")
|
||||
// c, _ := reuse.Dial("tcp", "127.0.0.1:1234", "127.0.0.1:1235")
|
||||
//
|
||||
// Note: cant dial self because tcp/ip stacks use 4-tuples to identify connections,
|
||||
// and doing so would clash.
|
||||
package greuseport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
)
|
||||
|
||||
var (
|
||||
Enabled = false
|
||||
listenConfig = net.ListenConfig {
|
||||
Control: Control,
|
||||
}
|
||||
)
|
||||
|
||||
// Listen listens at the given network and address. see net.Listen
|
||||
// Returns a net.Listener created from a file discriptor for a socket
|
||||
// with SO_REUSEPORT and SO_REUSEADDR option set.
|
||||
func Listen(network, address string) (net.Listener, error) {
|
||||
return listenConfig.Listen(context.Background(), network, address)
|
||||
}
|
||||
|
||||
// ListenPacket listens at the given network and address. see net.ListenPacket
|
||||
// Returns a net.Listener created from a file discriptor for a socket
|
||||
// with SO_REUSEPORT and SO_REUSEADDR option set.
|
||||
func ListenPacket(network, address string) (net.PacketConn, error) {
|
||||
return listenConfig.ListenPacket(context.Background(), network, address)
|
||||
}
|
||||
|
||||
// Dial dials the given network and address. see net.Dialer.Dial
|
||||
// Returns a net.Conn created from a file discriptor for a socket
|
||||
// with SO_REUSEPORT and SO_REUSEADDR option set.
|
||||
func Dial(network, laddr, raddr string) (net.Conn, error) {
|
||||
nla, err := ResolveAddr(network, laddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := net.Dialer {
|
||||
Control: Control,
|
||||
LocalAddr: nla,
|
||||
}
|
||||
return d.Dial(network, raddr)
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
package greuseport
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
func ResolveAddr(network, address string) (net.Addr, error) {
|
||||
switch network {
|
||||
case "ip", "ip4", "ip6":
|
||||
return net.ResolveIPAddr(network, address)
|
||||
case "tcp", "tcp4", "tcp6":
|
||||
return net.ResolveTCPAddr(network, address)
|
||||
case "udp", "udp4", "udp6":
|
||||
return net.ResolveUDPAddr(network, address)
|
||||
case "unix", "unixgram", "unixpacket":
|
||||
return net.ResolveUnixAddr(network, address)
|
||||
default:
|
||||
return nil, net.UnknownNetworkError(network)
|
||||
}
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
// +build !windows,!linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd
|
||||
|
||||
package greuseport
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// See net.RawConn.Control
|
||||
func Control(network, address string, c syscall.RawConn) (err error) {
|
||||
return nil
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
// +build linux darwin dragonfly freebsd netbsd openbsd
|
||||
|
||||
package greuseport
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/third/golang.org/x/sys/unix"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Enabled = true
|
||||
}
|
||||
|
||||
// See net.RawConn.Control
|
||||
func Control(network, address string, c syscall.RawConn) (err error) {
|
||||
c.Control(func(fd uintptr) {
|
||||
if err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil {
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
if err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
|
||||
})
|
||||
return
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
// +build windows
|
||||
|
||||
package greuseport
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/third/golang.org/x/sys/windows"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// See net.RawConn.Control
|
||||
func Control(network, address string, c syscall.RawConn) (err error) {
|
||||
return c.Control(func(fd uintptr) {
|
||||
if err = windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1); err != nil {
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -1,213 +0,0 @@
|
||||
// +build linux darwin dragonfly freebsd netbsd openbsd
|
||||
|
||||
package greuseport_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/net/greuseport"
|
||||
"html"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
httpServerOneResponse = "1"
|
||||
httpServerTwoResponse = "2"
|
||||
)
|
||||
|
||||
var (
|
||||
httpServerOne = NewHTTPServer(httpServerOneResponse)
|
||||
httpServerTwo = NewHTTPServer(httpServerTwoResponse)
|
||||
)
|
||||
|
||||
func NewHTTPServer(resp string) *httptest.Server {
|
||||
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, resp)
|
||||
}))
|
||||
}
|
||||
func TestNewReusablePortListener(t *testing.T) {
|
||||
listenerOne, err := greuseport.Listen("tcp4", "localhost:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerOne.Close()
|
||||
|
||||
listenerTwo, err := greuseport.Listen("tcp", "127.0.0.1:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerTwo.Close()
|
||||
|
||||
listenerThree, err := greuseport.Listen("tcp6", "[::]:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerThree.Close()
|
||||
|
||||
listenerFour, err := greuseport.Listen("tcp6", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerFour.Close()
|
||||
|
||||
listenerFive, err := greuseport.Listen("tcp4", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerFive.Close()
|
||||
|
||||
listenerSix, err := greuseport.Listen("tcp", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerSix.Close()
|
||||
}
|
||||
|
||||
func TestListen(t *testing.T) {
|
||||
listenerOne, err := greuseport.Listen("tcp4", "localhost:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerOne.Close()
|
||||
|
||||
listenerTwo, err := greuseport.Listen("tcp", "127.0.0.1:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerTwo.Close()
|
||||
|
||||
listenerThree, err := greuseport.Listen("tcp6", "[::]:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerThree.Close()
|
||||
|
||||
listenerFour, err := greuseport.Listen("tcp6", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerFour.Close()
|
||||
|
||||
listenerFive, err := greuseport.Listen("tcp4", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerFive.Close()
|
||||
|
||||
listenerSix, err := greuseport.Listen("tcp", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerSix.Close()
|
||||
}
|
||||
|
||||
func TestNewReusablePortServers(t *testing.T) {
|
||||
listenerOne, err := greuseport.Listen("tcp4", "localhost:10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerOne.Close()
|
||||
|
||||
listenerTwo, err := greuseport.Listen("tcp6", ":10081")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer listenerTwo.Close()
|
||||
|
||||
httpServerOne.Listener = listenerOne
|
||||
httpServerTwo.Listener = listenerTwo
|
||||
|
||||
httpServerOne.Start()
|
||||
httpServerTwo.Start()
|
||||
|
||||
// Server One — First Response
|
||||
resp1, err := http.Get(httpServerOne.URL)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
body1, err := ioutil.ReadAll(resp1.Body)
|
||||
resp1.Body.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if string(body1) != httpServerOneResponse && string(body1) != httpServerTwoResponse {
|
||||
t.Errorf("Expected %#v or %#v, got %#v.", httpServerOneResponse, httpServerTwoResponse, string(body1))
|
||||
}
|
||||
|
||||
// Server Two — First Response
|
||||
resp2, err := http.Get(httpServerTwo.URL)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
body2, err := ioutil.ReadAll(resp2.Body)
|
||||
resp1.Body.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if string(body2) != httpServerOneResponse && string(body2) != httpServerTwoResponse {
|
||||
t.Errorf("Expected %#v or %#v, got %#v.", httpServerOneResponse, httpServerTwoResponse, string(body2))
|
||||
}
|
||||
|
||||
httpServerTwo.Close()
|
||||
|
||||
// Server One — Second Response
|
||||
resp3, err := http.Get(httpServerOne.URL)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
body3, err := ioutil.ReadAll(resp3.Body)
|
||||
resp1.Body.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if string(body3) != httpServerOneResponse {
|
||||
t.Errorf("Expected %#v, got %#v.", httpServerOneResponse, string(body3))
|
||||
}
|
||||
|
||||
// Server One — Third Response
|
||||
resp5, err := http.Get(httpServerOne.URL)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
body5, err := ioutil.ReadAll(resp5.Body)
|
||||
resp1.Body.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if string(body5) != httpServerOneResponse {
|
||||
t.Errorf("Expected %#v, got %#v.", httpServerOneResponse, string(body5))
|
||||
}
|
||||
|
||||
httpServerOne.Close()
|
||||
}
|
||||
|
||||
func BenchmarkNewReusablePortListener(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
listener, err := greuseport.Listen("tcp", ":10081")
|
||||
|
||||
if err != nil {
|
||||
b.Error(err)
|
||||
} else {
|
||||
listener.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleNewReusablePortListener() {
|
||||
listener, err := greuseport.Listen("tcp", ":8881")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
server := &http.Server{}
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Println(os.Getgid())
|
||||
fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
|
||||
})
|
||||
|
||||
panic(server.Serve(listener))
|
||||
}
|
||||
@ -30,7 +30,7 @@ var serverMapping = gmap.NewStringInterfaceMap()
|
||||
|
||||
// 获取/创建一个空配置的TCP Server
|
||||
// 单例模式,请保证name的唯一性
|
||||
func GetServer(name...interface{}) (*Server) {
|
||||
func GetServer(name...interface{}) *Server {
|
||||
serverName := gDEFAULT_SERVER
|
||||
if len(name) > 0 {
|
||||
serverName = gconv.String(name[0])
|
||||
|
||||
@ -221,8 +221,11 @@ func (c *Conn) LocalAddr() net.Addr {
|
||||
return c.conn.LocalAddr()
|
||||
}
|
||||
|
||||
// 不能使用c.conn.RemoteAddr(),其返回为nil,
|
||||
// 这里使用c.raddr获取远程连接地址。
|
||||
func (c *Conn) RemoteAddr() net.Addr {
|
||||
return c.conn.RemoteAddr()
|
||||
//return c.conn.RemoteAddr()
|
||||
return c.raddr
|
||||
}
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
|
||||
@ -1 +0,0 @@
|
||||
package net
|
||||
@ -119,6 +119,9 @@ func (c *memCache) doSetWithLockCheck(key interface{}, value interface{}, expire
|
||||
if f, ok := value.(func() interface {}); ok {
|
||||
value = f()
|
||||
}
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
c.data[key] = memCacheItem{v : value, e : expireTimestamp}
|
||||
c.dataMu.Unlock()
|
||||
c.eventList.PushBack(&memCacheEvent{k : key, e : expireTimestamp})
|
||||
|
||||
@ -57,7 +57,7 @@ func TestCache_LRU(t *testing.T) {
|
||||
|
||||
gtest.Assert(cache.Size(), 10)
|
||||
gtest.Assert(cache.Get(6), 6)
|
||||
time.Sleep(3*time.Second)
|
||||
time.Sleep(4*time.Second)
|
||||
gtest.Assert(cache.Size(), 2)
|
||||
gtest.Assert(cache.Get(6), 6)
|
||||
gtest.Assert(cache.Get(1), nil)
|
||||
|
||||
@ -4,44 +4,42 @@
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// Package gcfg provides reading, caching and managing for configuration files.
|
||||
//
|
||||
// 配置管理,
|
||||
// 配置文件格式支持:json, xml, toml, yaml/yml
|
||||
// Package gcfg provides reading, caching and managing for configuration files/contents.
|
||||
package gcfg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/garray"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/g/container/gtype"
|
||||
"github.com/gogf/gf/g/container/gvar"
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gfsnotify"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/os/gspath"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/g/container/garray"
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
"github.com/gogf/gf/g/container/gtype"
|
||||
"github.com/gogf/gf/g/container/gvar"
|
||||
"github.com/gogf/gf/g/encoding/gjson"
|
||||
"github.com/gogf/gf/g/internal/cmdenv"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/os/gfsnotify"
|
||||
"github.com/gogf/gf/g/os/glog"
|
||||
"github.com/gogf/gf/g/os/gspath"
|
||||
)
|
||||
|
||||
const (
|
||||
// 默认的配置管理文件名称
|
||||
// Default configuration file name.
|
||||
DEFAULT_CONFIG_FILE = "config.toml"
|
||||
)
|
||||
|
||||
// 配置管理对象
|
||||
// Configuration struct.
|
||||
type Config struct {
|
||||
name *gtype.String // 默认配置文件名称
|
||||
paths *garray.StringArray // 搜索目录路径
|
||||
jsons *gmap.StringInterfaceMap // 配置文件对象
|
||||
vc *gtype.Bool // 层级检索是否执行分隔符冲突检测(默认为false,检测会比较影响检索效率)
|
||||
name *gtype.String // Default configuration file name.
|
||||
paths *garray.StringArray // Searching path array.
|
||||
jsons *gmap.StringInterfaceMap // The pared JSON objects for configuration files.
|
||||
vc *gtype.Bool // Whether do violence check in value index searching.
|
||||
// It affects the performance when set true(false in default).
|
||||
}
|
||||
|
||||
// New returns a new configuration management object.
|
||||
//
|
||||
// 生成一个配置管理对象
|
||||
func New(path string, file...string) *Config {
|
||||
// The param <file> specifies the default configuration file name for reading.
|
||||
func New(file ...string) *Config {
|
||||
name := DEFAULT_CONFIG_FILE
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
@ -52,15 +50,29 @@ func New(path string, file...string) *Config {
|
||||
jsons : gmap.NewStringInterfaceMap(),
|
||||
vc : gtype.NewBool(),
|
||||
}
|
||||
if len(path) > 0 {
|
||||
c.SetPath(path)
|
||||
}
|
||||
// Customized dir path from env/cmd.
|
||||
if envPath := cmdenv.Get("gf.gcfg.path").String(); envPath != "" {
|
||||
if gfile.Exists(envPath) {
|
||||
c.SetPath(envPath)
|
||||
} else {
|
||||
glog.Errorfln("Configuration directory path does not exist: %s", envPath)
|
||||
}
|
||||
} else {
|
||||
// Dir path of working dir.
|
||||
c.SetPath(gfile.Pwd())
|
||||
// Dir path of binary.
|
||||
if selfPath := gfile.SelfDir(); selfPath != "" && gfile.Exists(selfPath) {
|
||||
c.AddPath(selfPath)
|
||||
}
|
||||
// Dir path of main package.
|
||||
if mainPath := gfile.MainPkgPath(); mainPath != "" && gfile.Exists(mainPath) {
|
||||
c.AddPath(mainPath)
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// filePath returns the absolute configuration file path for the given filename by <file>.
|
||||
//
|
||||
// 判断从哪个配置文件中获取内容,返回配置文件的绝对路径
|
||||
func (c *Config) filePath(file...string) (path string) {
|
||||
name := c.name.Val()
|
||||
if len(file) > 0 {
|
||||
@ -72,8 +84,12 @@ func (c *Config) filePath(file...string) (path string) {
|
||||
if c.paths.Len() > 0 {
|
||||
buffer.WriteString(fmt.Sprintf("[gcfg] cannot find config file \"%s\" in following paths:", name))
|
||||
c.paths.RLockFunc(func(array []string) {
|
||||
for k, v := range array {
|
||||
buffer.WriteString(fmt.Sprintf("\n%d. %s",k + 1, v))
|
||||
index := 1
|
||||
for _, v := range array {
|
||||
buffer.WriteString(fmt.Sprintf("\n%d. %s", index, v))
|
||||
index++
|
||||
buffer.WriteString(fmt.Sprintf("\n%d. %s%s%s", index, v, gfile.Separator, "config"))
|
||||
index++
|
||||
}
|
||||
})
|
||||
} else {
|
||||
@ -84,15 +100,46 @@ func (c *Config) filePath(file...string) (path string) {
|
||||
return path
|
||||
}
|
||||
|
||||
// 设置配置管理器的配置文件存放目录绝对路径
|
||||
// SetPath sets the configuration directory path for file search.
|
||||
// The param <path> can be absolute or relative path, but absolute path is suggested.
|
||||
func (c *Config) SetPath(path string) error {
|
||||
// Absolute path.
|
||||
realPath := gfile.RealPath(path)
|
||||
if realPath == "" {
|
||||
err := errors.New(fmt.Sprintf(`path "%s" does not exist`, path))
|
||||
glog.Error(fmt.Sprintf(`[gcfg] SetPath failed: %s`, err.Error()))
|
||||
// Relative path.
|
||||
c.paths.RLockFunc(func(array []string) {
|
||||
for _, v := range array {
|
||||
if path, _ := gspath.Search(v, path); path != "" {
|
||||
realPath = path
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// Path not exist.
|
||||
if realPath == "" {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
if c.paths.Len() > 0 {
|
||||
buffer.WriteString(fmt.Sprintf("[gcfg] SetPath failed: cannot find directory \"%s\" in following paths:", path))
|
||||
c.paths.RLockFunc(func(array []string) {
|
||||
for k, v := range array {
|
||||
buffer.WriteString(fmt.Sprintf("\n%d. %s",k + 1, v))
|
||||
}
|
||||
})
|
||||
} else {
|
||||
buffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" does not exist`, path))
|
||||
}
|
||||
err := errors.New(buffer.String())
|
||||
glog.Error(err)
|
||||
return err
|
||||
}
|
||||
// 重复判断
|
||||
// Should be a directory.
|
||||
if !gfile.IsDir(realPath) {
|
||||
err := errors.New(fmt.Sprintf(`[gcfg] SetPath failed: path "%s" should be directory type`, path))
|
||||
glog.Error(err)
|
||||
return err
|
||||
}
|
||||
// Repeated path check.
|
||||
if c.paths.Search(realPath) != -1 {
|
||||
return nil
|
||||
}
|
||||
@ -103,22 +150,54 @@ func (c *Config) SetPath(path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 设置是否执行层级冲突检查,当键名中存在层级符号时需要开启该特性,默认为关闭。
|
||||
// 开启比较耗性能,也不建议允许键名中存在分隔符,最好在应用端避免这种情况。
|
||||
// SetViolenceCheck sets whether to perform level conflict check.
|
||||
// This feature needs to be enabled when there is a level symbol in the key name.
|
||||
// The default is off.
|
||||
// Turning on this feature is quite expensive,
|
||||
// and it is not recommended to allow separators in the key names.
|
||||
// It is best to avoid this on the application side.
|
||||
func (c *Config) SetViolenceCheck(check bool) {
|
||||
c.vc.Set(check)
|
||||
c.Reload()
|
||||
c.Clear()
|
||||
}
|
||||
|
||||
// 添加配置管理器的配置文件搜索路径
|
||||
// AddPath adds a absolute or relative path to the search paths.
|
||||
func (c *Config) AddPath(path string) error {
|
||||
// Absolute path.
|
||||
realPath := gfile.RealPath(path)
|
||||
if realPath == "" {
|
||||
err := errors.New(fmt.Sprintf(`path "%s" does not exist`, path))
|
||||
glog.Error(fmt.Sprintf(`[gcfg] AddPath failed: %s`, err.Error()))
|
||||
// Relative path.
|
||||
c.paths.RLockFunc(func(array []string) {
|
||||
for _, v := range array {
|
||||
if path, _ := gspath.Search(v, path); path != "" {
|
||||
realPath = path
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
if realPath == "" {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
if c.paths.Len() > 0 {
|
||||
buffer.WriteString(fmt.Sprintf("[gcfg] AddPath failed: cannot find directory \"%s\" in following paths:", path))
|
||||
c.paths.RLockFunc(func(array []string) {
|
||||
for k, v := range array {
|
||||
buffer.WriteString(fmt.Sprintf("\n%d. %s", k + 1, v))
|
||||
}
|
||||
})
|
||||
} else {
|
||||
buffer.WriteString(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" does not exist`, path))
|
||||
}
|
||||
err := errors.New(buffer.String())
|
||||
glog.Error(err)
|
||||
return err
|
||||
}
|
||||
// 重复判断
|
||||
if !gfile.IsDir(realPath) {
|
||||
err := errors.New(fmt.Sprintf(`[gcfg] AddPath failed: path "%s" should be directory type`, path))
|
||||
glog.Error(err)
|
||||
return err
|
||||
}
|
||||
// Repeated path check.
|
||||
if c.paths.Search(realPath) != -1 {
|
||||
return nil
|
||||
}
|
||||
@ -127,8 +206,10 @@ func (c *Config) AddPath(path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 查找配置文件,获取指定配置文件的绝对路径,默认获取默认的配置文件路径;
|
||||
// 当指定的配置文件不存在时,返回空字符串,并且不会报错。
|
||||
// GetFilePath returns the absolute path of the specified configuration file.
|
||||
// If <file> is not passed, it returns the configuration file path of the default name.
|
||||
// If the specified configuration file does not exist,
|
||||
// an empty string is returned.
|
||||
func (c *Config) GetFilePath(file...string) (path string) {
|
||||
name := c.name.Val()
|
||||
if len(file) > 0 {
|
||||
@ -149,33 +230,60 @@ func (c *Config) GetFilePath(file...string) (path string) {
|
||||
return
|
||||
}
|
||||
|
||||
// 设置配置管理对象的默认文件名称
|
||||
// SetFileName sets the default configuration file name.
|
||||
func (c *Config) SetFileName(name string) {
|
||||
//glog.Debug("[gcfg] SetFileName:", name)
|
||||
c.name.Set(name)
|
||||
}
|
||||
|
||||
// 添加配置文件到配置管理器中,第二个参数为非必须,如果不输入表示添加进入默认的配置名称中
|
||||
// GetFileName returns the default configuration file name.
|
||||
func (c *Config) GetFileName() string {
|
||||
return c.name.Val()
|
||||
}
|
||||
|
||||
// getJson returns a gjson.Json object for the specified <file> content.
|
||||
// It would print error if file reading fails.
|
||||
// If any error occurs, it return nil.
|
||||
func (c *Config) getJson(file...string) *gjson.Json {
|
||||
filePath := c.filePath(file...)
|
||||
if filePath == "" {
|
||||
name := c.name.Val()
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
}
|
||||
r := c.jsons.GetOrSetFuncLock(name, func() interface{} {
|
||||
content := ""
|
||||
filePath := ""
|
||||
if content = GetContent(name); content == "" {
|
||||
filePath = c.filePath(name)
|
||||
if filePath == "" {
|
||||
return nil
|
||||
}
|
||||
content = gfile.GetContents(filePath)
|
||||
}
|
||||
if j, err := gjson.LoadContent(content); err == nil {
|
||||
j.SetViolenceCheck(c.vc.Val())
|
||||
// Add monitor for this configuration file,
|
||||
// any changes of this file will refresh its cache in Config object.
|
||||
if filePath != "" {
|
||||
gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
|
||||
c.jsons.Remove(name)
|
||||
})
|
||||
}
|
||||
return j
|
||||
} else {
|
||||
if filePath != "" {
|
||||
glog.Criticalfln(`[gcfg] Load config file "%s" failed: %s`, filePath, err.Error())
|
||||
} else {
|
||||
glog.Criticalfln(`[gcfg] Load configuration failed: %s`, err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if r := c.jsons.Get(filePath); r != nil {
|
||||
})
|
||||
if r != nil {
|
||||
return r.(*gjson.Json)
|
||||
}
|
||||
if j, err := gjson.Load(filePath); err == nil {
|
||||
j.SetViolenceCheck(c.vc.Val())
|
||||
c.addMonitor(filePath)
|
||||
c.jsons.Set(filePath, j)
|
||||
return j
|
||||
} else {
|
||||
glog.Errorfln(`[gcfg] Load config file "%s" failed: %s`, filePath, err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取配置项,当不存在时返回nil
|
||||
func (c *Config) Get(pattern string, file...string) interface{} {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.Get(pattern)
|
||||
@ -183,7 +291,6 @@ func (c *Config) Get(pattern string, file...string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获得配置项,返回动态变量
|
||||
func (c *Config) GetVar(pattern string, file...string) gvar.VarRead {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return gvar.New(j.Get(pattern), true)
|
||||
@ -191,7 +298,6 @@ func (c *Config) GetVar(pattern string, file...string) gvar.VarRead {
|
||||
return gvar.New(nil, true)
|
||||
}
|
||||
|
||||
// 判断指定的配置项是否存在
|
||||
func (c *Config) Contains(pattern string, file...string) bool {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.Contains(pattern)
|
||||
@ -199,8 +305,6 @@ func (c *Config) Contains(pattern string, file...string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 获得一个键值对关联数组/哈希表,方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
func (c *Config) GetMap(pattern string, file...string) map[string]interface{} {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetMap(pattern)
|
||||
@ -208,8 +312,6 @@ func (c *Config) GetMap(pattern string, file...string) map[string]interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获得一个数组[]interface{},方便操作,不需要自己做类型转换
|
||||
// 注意,如果获取的值不存在,或者类型与json类型不匹配,那么将会返回nil
|
||||
func (c *Config) GetArray(pattern string, file...string) []interface{} {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetArray(pattern)
|
||||
@ -217,7 +319,6 @@ func (c *Config) GetArray(pattern string, file...string) []interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回指定json中的string
|
||||
func (c *Config) GetString(pattern string, file...string) string {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetString(pattern)
|
||||
@ -239,7 +340,6 @@ func (c *Config) GetInterfaces(pattern string, file...string) []interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回指定json中的bool
|
||||
func (c *Config) GetBool(pattern string, file...string) bool {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetBool(pattern)
|
||||
@ -247,7 +347,6 @@ func (c *Config) GetBool(pattern string, file...string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 返回指定json中的float32
|
||||
func (c *Config) GetFloat32(pattern string, file...string) float32 {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetFloat32(pattern)
|
||||
@ -255,7 +354,6 @@ func (c *Config) GetFloat32(pattern string, file...string) float32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// 返回指定json中的float64
|
||||
func (c *Config) GetFloat64(pattern string, file...string) float64 {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetFloat64(pattern)
|
||||
@ -270,7 +368,6 @@ func (c *Config) GetFloats(pattern string, file...string) []float64 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回指定json中的float64->int
|
||||
func (c *Config) GetInt(pattern string, file...string) int {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetInt(pattern)
|
||||
@ -314,7 +411,6 @@ func (c *Config) GetInts(pattern string, file...string) []int {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回指定json中的float64->uint
|
||||
func (c *Config) GetUint(pattern string, file...string) uint {
|
||||
if j := c.getJson(file...); j != nil {
|
||||
return j.GetUint(pattern)
|
||||
@ -357,19 +453,14 @@ func (c *Config) GetToStruct(pattern string, objPointer interface{}, file...stri
|
||||
return errors.New("config file not found")
|
||||
}
|
||||
|
||||
// 清空当前配置文件缓存,强制重新从磁盘文件读取配置文件内容
|
||||
// Deprecated. See Clear.
|
||||
func (c *Config) Reload() {
|
||||
c.jsons.Clear()
|
||||
}
|
||||
|
||||
// 添加文件监控
|
||||
func (c *Config) addMonitor(path string) {
|
||||
// 防止多goroutine同时调用
|
||||
if c.jsons.Get(path) != nil {
|
||||
return
|
||||
}
|
||||
gfsnotify.Add(path, func(event *gfsnotify.Event) {
|
||||
// 删除文件内容缓存,下一次查询会自动更新
|
||||
c.jsons.Remove(event.Path)
|
||||
})
|
||||
// Clear removes all parsed configuration files content cache,
|
||||
// which will force reload configuration content from file.
|
||||
func (c *Config) Clear() {
|
||||
c.jsons.Clear()
|
||||
}
|
||||
|
||||
|
||||
71
g/os/gcfg/gcfg_config.go
Normal file
71
g/os/gcfg/gcfg_config.go
Normal file
@ -0,0 +1,71 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gcfg
|
||||
|
||||
import "github.com/gogf/gf/g/container/gmap"
|
||||
|
||||
var (
|
||||
// Customized configuration content.
|
||||
configs = gmap.NewStringStringMap()
|
||||
)
|
||||
|
||||
// SetContent sets customized configuration content for specified <file>.
|
||||
// The <file> is unnecessary param, default is DEFAULT_CONFIG_FILE.
|
||||
func SetContent(content string, file ...string) {
|
||||
name := DEFAULT_CONFIG_FILE
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
}
|
||||
// Clear file cache for instances which cached <name>.
|
||||
instances.LockFunc(func(m map[string]interface{}) {
|
||||
if configs.Contains(name) {
|
||||
for _, v := range m {
|
||||
v.(*Config).jsons.Remove(name)
|
||||
}
|
||||
}
|
||||
configs.Set(name, content)
|
||||
})
|
||||
}
|
||||
|
||||
// GetContent returns customized configuration content for specified <file>.
|
||||
// The <file> is unnecessary param, default is DEFAULT_CONFIG_FILE.
|
||||
func GetContent(file ...string) string {
|
||||
name := DEFAULT_CONFIG_FILE
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
}
|
||||
return configs.Get(name)
|
||||
}
|
||||
|
||||
// RemoveConfig removes the global configuration with specified group.
|
||||
// If <name> is not passed, it removes configuration of the default group name.
|
||||
func RemoveConfig(file ...string) {
|
||||
name := DEFAULT_CONFIG_FILE
|
||||
if len(file) > 0 {
|
||||
name = file[0]
|
||||
}
|
||||
// Clear file cache for instances which cached <name>.
|
||||
instances.LockFunc(func(m map[string]interface{}) {
|
||||
if configs.Contains(name) {
|
||||
for _, v := range m {
|
||||
v.(*Config).jsons.Remove(name)
|
||||
}
|
||||
configs.Remove(name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ClearContent removes all global configuration contents.
|
||||
func ClearContent() {
|
||||
configs.Clear()
|
||||
// Clear cache for all instances.
|
||||
instances.LockFunc(func(m map[string]interface{}) {
|
||||
for _, v := range m {
|
||||
v.(*Config).jsons.Clear()
|
||||
}
|
||||
})
|
||||
}
|
||||
32
g/os/gcfg/gcfg_instance.go
Normal file
32
g/os/gcfg/gcfg_instance.go
Normal file
@ -0,0 +1,32 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gcfg
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/container/gmap"
|
||||
)
|
||||
|
||||
const (
|
||||
// Default group name for instance usage.
|
||||
DEFAULT_GROUP_NAME = "default"
|
||||
)
|
||||
var (
|
||||
// Instances map.
|
||||
instances = gmap.NewStringInterfaceMap()
|
||||
)
|
||||
|
||||
// Instance returns an instance of Config with default settings.
|
||||
// The param <name> is the name for the instance.
|
||||
func Instance(name ...string) *Config {
|
||||
key := DEFAULT_GROUP_NAME
|
||||
if len(name) > 0 {
|
||||
key = name[0]
|
||||
}
|
||||
return instances.GetOrSetFuncLock(key, func() interface{} {
|
||||
return New()
|
||||
}).(*Config)
|
||||
}
|
||||
271
g/os/gcfg/gcfg_z_unit_test.go
Normal file
271
g/os/gcfg/gcfg_z_unit_test.go
Normal file
@ -0,0 +1,271 @@
|
||||
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
// go test *.go -bench=".*" -benchmem
|
||||
|
||||
package gcfg_test
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/g/os/gcfg"
|
||||
"github.com/gogf/gf/g/os/gfile"
|
||||
"github.com/gogf/gf/g/test/gtest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Basic(t *testing.T) {
|
||||
config := `
|
||||
v1 = 1
|
||||
v2 = "true"
|
||||
v3 = "off"
|
||||
v4 = "1.23"
|
||||
array = [1,2,3]
|
||||
[redis]
|
||||
disk = "127.0.0.1:6379,0"
|
||||
cache = "127.0.0.1:6379,1"
|
||||
`
|
||||
gtest.Case(t, func() {
|
||||
path := gcfg.DEFAULT_CONFIG_FILE
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
c := gcfg.New()
|
||||
gtest.Assert(c.Get("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt8("v1"), int8(1))
|
||||
gtest.AssertEQ(c.GetInt16("v1"), int16(1))
|
||||
gtest.AssertEQ(c.GetInt32("v1"), int32(1))
|
||||
gtest.AssertEQ(c.GetInt64("v1"), int64(1))
|
||||
gtest.AssertEQ(c.GetUint("v1"), uint(1))
|
||||
gtest.AssertEQ(c.GetUint8("v1"), uint8(1))
|
||||
gtest.AssertEQ(c.GetUint16("v1"), uint16(1))
|
||||
gtest.AssertEQ(c.GetUint32("v1"), uint32(1))
|
||||
gtest.AssertEQ(c.GetUint64("v1"), uint64(1))
|
||||
|
||||
gtest.AssertEQ(c.GetVar("v1").String(), "1")
|
||||
gtest.AssertEQ(c.GetVar("v1").Bool(), true)
|
||||
gtest.AssertEQ(c.GetVar("v2").String(), "true")
|
||||
gtest.AssertEQ(c.GetVar("v2").Bool(), true)
|
||||
|
||||
gtest.AssertEQ(c.GetString("v1"), "1")
|
||||
gtest.AssertEQ(c.GetFloat32("v4"), float32(1.23))
|
||||
gtest.AssertEQ(c.GetFloat64("v4"), float64(1.23))
|
||||
gtest.AssertEQ(c.GetString("v2"), "true")
|
||||
gtest.AssertEQ(c.GetBool("v2"), true)
|
||||
gtest.AssertEQ(c.GetBool("v3"), false)
|
||||
|
||||
gtest.AssertEQ(c.Contains("v1"), true)
|
||||
gtest.AssertEQ(c.Contains("v2"), true)
|
||||
gtest.AssertEQ(c.Contains("v3"), true)
|
||||
gtest.AssertEQ(c.Contains("v4"), true)
|
||||
gtest.AssertEQ(c.Contains("v5"), false)
|
||||
|
||||
gtest.AssertEQ(c.GetInts("array"), []int{1,2,3})
|
||||
gtest.AssertEQ(c.GetStrings("array"), []string{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetArray("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetInterfaces("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetMap("redis"), map[string]interface{}{
|
||||
"disk" : "127.0.0.1:6379,0",
|
||||
"cache" : "127.0.0.1:6379,1",
|
||||
})
|
||||
gtest.AssertEQ(c.GetFilePath(), gfile.Pwd() + gfile.Separator + path)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Content(t *testing.T) {
|
||||
content := `
|
||||
v1 = 1
|
||||
v2 = "true"
|
||||
v3 = "off"
|
||||
v4 = "1.23"
|
||||
array = [1,2,3]
|
||||
[redis]
|
||||
disk = "127.0.0.1:6379,0"
|
||||
cache = "127.0.0.1:6379,1"
|
||||
`
|
||||
gcfg.SetContent(content)
|
||||
defer gcfg.ClearContent()
|
||||
|
||||
gtest.Case(t, func() {
|
||||
c := gcfg.New()
|
||||
gtest.Assert(c.Get("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt8("v1"), int8(1))
|
||||
gtest.AssertEQ(c.GetInt16("v1"), int16(1))
|
||||
gtest.AssertEQ(c.GetInt32("v1"), int32(1))
|
||||
gtest.AssertEQ(c.GetInt64("v1"), int64(1))
|
||||
gtest.AssertEQ(c.GetUint("v1"), uint(1))
|
||||
gtest.AssertEQ(c.GetUint8("v1"), uint8(1))
|
||||
gtest.AssertEQ(c.GetUint16("v1"), uint16(1))
|
||||
gtest.AssertEQ(c.GetUint32("v1"), uint32(1))
|
||||
gtest.AssertEQ(c.GetUint64("v1"), uint64(1))
|
||||
|
||||
gtest.AssertEQ(c.GetVar("v1").String(), "1")
|
||||
gtest.AssertEQ(c.GetVar("v1").Bool(), true)
|
||||
gtest.AssertEQ(c.GetVar("v2").String(), "true")
|
||||
gtest.AssertEQ(c.GetVar("v2").Bool(), true)
|
||||
|
||||
gtest.AssertEQ(c.GetString("v1"), "1")
|
||||
gtest.AssertEQ(c.GetFloat32("v4"), float32(1.23))
|
||||
gtest.AssertEQ(c.GetFloat64("v4"), float64(1.23))
|
||||
gtest.AssertEQ(c.GetString("v2"), "true")
|
||||
gtest.AssertEQ(c.GetBool("v2"), true)
|
||||
gtest.AssertEQ(c.GetBool("v3"), false)
|
||||
|
||||
gtest.AssertEQ(c.Contains("v1"), true)
|
||||
gtest.AssertEQ(c.Contains("v2"), true)
|
||||
gtest.AssertEQ(c.Contains("v3"), true)
|
||||
gtest.AssertEQ(c.Contains("v4"), true)
|
||||
gtest.AssertEQ(c.Contains("v5"), false)
|
||||
|
||||
gtest.AssertEQ(c.GetInts("array"), []int{1,2,3})
|
||||
gtest.AssertEQ(c.GetStrings("array"), []string{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetArray("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetInterfaces("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetMap("redis"), map[string]interface{}{
|
||||
"disk" : "127.0.0.1:6379,0",
|
||||
"cache" : "127.0.0.1:6379,1",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func Test_SetFileName(t *testing.T) {
|
||||
config := `
|
||||
{
|
||||
"array": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"redis": {
|
||||
"cache": "127.0.0.1:6379,1",
|
||||
"disk": "127.0.0.1:6379,0"
|
||||
},
|
||||
"v1": 1,
|
||||
"v2": "true",
|
||||
"v3": "off",
|
||||
"v4": "1.234"
|
||||
}
|
||||
`
|
||||
gtest.Case(t, func() {
|
||||
path := "config.json"
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
c := gcfg.New()
|
||||
c.SetFileName(path)
|
||||
gtest.Assert(c.Get("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt8("v1"), int8(1))
|
||||
gtest.AssertEQ(c.GetInt16("v1"), int16(1))
|
||||
gtest.AssertEQ(c.GetInt32("v1"), int32(1))
|
||||
gtest.AssertEQ(c.GetInt64("v1"), int64(1))
|
||||
gtest.AssertEQ(c.GetUint("v1"), uint(1))
|
||||
gtest.AssertEQ(c.GetUint8("v1"), uint8(1))
|
||||
gtest.AssertEQ(c.GetUint16("v1"), uint16(1))
|
||||
gtest.AssertEQ(c.GetUint32("v1"), uint32(1))
|
||||
gtest.AssertEQ(c.GetUint64("v1"), uint64(1))
|
||||
|
||||
gtest.AssertEQ(c.GetVar("v1").String(), "1")
|
||||
gtest.AssertEQ(c.GetVar("v1").Bool(), true)
|
||||
gtest.AssertEQ(c.GetVar("v2").String(), "true")
|
||||
gtest.AssertEQ(c.GetVar("v2").Bool(), true)
|
||||
|
||||
gtest.AssertEQ(c.GetString("v1"), "1")
|
||||
gtest.AssertEQ(c.GetFloat32("v4"), float32(1.234))
|
||||
gtest.AssertEQ(c.GetFloat64("v4"), float64(1.234))
|
||||
gtest.AssertEQ(c.GetString("v2"), "true")
|
||||
gtest.AssertEQ(c.GetBool("v2"), true)
|
||||
gtest.AssertEQ(c.GetBool("v3"), false)
|
||||
|
||||
gtest.AssertEQ(c.Contains("v1"), true)
|
||||
gtest.AssertEQ(c.Contains("v2"), true)
|
||||
gtest.AssertEQ(c.Contains("v3"), true)
|
||||
gtest.AssertEQ(c.Contains("v4"), true)
|
||||
gtest.AssertEQ(c.Contains("v5"), false)
|
||||
|
||||
gtest.AssertEQ(c.GetInts("array"), []int{1,2,3})
|
||||
gtest.AssertEQ(c.GetStrings("array"), []string{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetArray("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetInterfaces("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetMap("redis"), map[string]interface{}{
|
||||
"disk" : "127.0.0.1:6379,0",
|
||||
"cache" : "127.0.0.1:6379,1",
|
||||
})
|
||||
gtest.AssertEQ(c.GetFilePath(), gfile.Pwd() + gfile.Separator + path)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Instance(t *testing.T) {
|
||||
config := `
|
||||
{
|
||||
"array": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"redis": {
|
||||
"cache": "127.0.0.1:6379,1",
|
||||
"disk": "127.0.0.1:6379,0"
|
||||
},
|
||||
"v1": 1,
|
||||
"v2": "true",
|
||||
"v3": "off",
|
||||
"v4": "1.234"
|
||||
}
|
||||
`
|
||||
gtest.Case(t, func() {
|
||||
path := gcfg.DEFAULT_CONFIG_FILE
|
||||
err := gfile.PutContents(path, config)
|
||||
gtest.Assert(err, nil)
|
||||
defer gfile.Remove(path)
|
||||
|
||||
c := gcfg.Instance()
|
||||
gtest.Assert(c.Get("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt("v1"), 1)
|
||||
gtest.AssertEQ(c.GetInt8("v1"), int8(1))
|
||||
gtest.AssertEQ(c.GetInt16("v1"), int16(1))
|
||||
gtest.AssertEQ(c.GetInt32("v1"), int32(1))
|
||||
gtest.AssertEQ(c.GetInt64("v1"), int64(1))
|
||||
gtest.AssertEQ(c.GetUint("v1"), uint(1))
|
||||
gtest.AssertEQ(c.GetUint8("v1"), uint8(1))
|
||||
gtest.AssertEQ(c.GetUint16("v1"), uint16(1))
|
||||
gtest.AssertEQ(c.GetUint32("v1"), uint32(1))
|
||||
gtest.AssertEQ(c.GetUint64("v1"), uint64(1))
|
||||
|
||||
gtest.AssertEQ(c.GetVar("v1").String(), "1")
|
||||
gtest.AssertEQ(c.GetVar("v1").Bool(), true)
|
||||
gtest.AssertEQ(c.GetVar("v2").String(), "true")
|
||||
gtest.AssertEQ(c.GetVar("v2").Bool(), true)
|
||||
|
||||
gtest.AssertEQ(c.GetString("v1"), "1")
|
||||
gtest.AssertEQ(c.GetFloat32("v4"), float32(1.234))
|
||||
gtest.AssertEQ(c.GetFloat64("v4"), float64(1.234))
|
||||
gtest.AssertEQ(c.GetString("v2"), "true")
|
||||
gtest.AssertEQ(c.GetBool("v2"), true)
|
||||
gtest.AssertEQ(c.GetBool("v3"), false)
|
||||
|
||||
gtest.AssertEQ(c.Contains("v1"), true)
|
||||
gtest.AssertEQ(c.Contains("v2"), true)
|
||||
gtest.AssertEQ(c.Contains("v3"), true)
|
||||
gtest.AssertEQ(c.Contains("v4"), true)
|
||||
gtest.AssertEQ(c.Contains("v5"), false)
|
||||
|
||||
gtest.AssertEQ(c.GetInts("array"), []int{1,2,3})
|
||||
gtest.AssertEQ(c.GetStrings("array"), []string{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetArray("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetInterfaces("array"), []interface{}{"1","2","3"})
|
||||
gtest.AssertEQ(c.GetMap("redis"), map[string]interface{}{
|
||||
"disk" : "127.0.0.1:6379,0",
|
||||
"cache" : "127.0.0.1:6379,1",
|
||||
})
|
||||
gtest.AssertEQ(c.GetFilePath(), gfile.Pwd() + gfile.Separator + path)
|
||||
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user