Compare commits

...

121 Commits

Author SHA1 Message Date
2eec1bc61a version updates 2022-03-14 19:39:56 +08:00
09a3f23e3d cli pack updates 2022-03-13 09:23:19 +08:00
329f6b90f7 improve gutil.Dump feature 2022-03-11 15:26:01 +08:00
9e056dfac8 Merge branch 'master' of https://github.com/gogf/gf 2022-03-11 10:24:57 +08:00
d8d9996464 fix issue #1662 2022-03-11 10:24:42 +08:00
43992a137e Merge pull request #1659 from arieslee/master
[fix bug] the default value of r.get is invalid
2022-03-11 09:14:11 +08:00
7767bf4d5d 重跑ci 2022-03-11 07:54:34 +08:00
acd1989fa1 improve Dump feature for package gutil 2022-03-10 22:29:47 +08:00
afa1f78a02 fix issue #1661 2022-03-10 21:12:24 +08:00
87b1433473 issue template update 2022-03-10 19:30:03 +08:00
5813979479 重跑ci 2022-03-10 14:32:06 +08:00
ba7cbfe3d9 error message update for database driver import 2022-03-10 14:29:49 +08:00
546b6b1724 t.Assert(err, nil) -> t.AssertNil(err) 2022-03-10 11:36:40 +08:00
eca3583845 fix issue #1416; add ParseOption for package gview 2022-03-10 11:35:23 +08:00
2471130f59 重跑ci 2022-03-10 09:52:45 +08:00
f5693c4393 improve package gview 2022-03-10 09:48:19 +08:00
12eb3ac63e [fix bug] the default value of r.get is invalid 2022-03-10 09:33:33 +08:00
e3f0163092 Merge branch 'master' of https://github.com/gogf/gf 2022-03-10 09:23:01 +08:00
213392640c fix issue #1653 2022-03-10 09:22:50 +08:00
4382a6e7bc Merge pull request #1658 from houseme/fix-1655
fix: js link err
2022-03-10 09:14:38 +08:00
c200177af4 fix: js link err 2022-03-09 23:36:30 +08:00
465100ae41 Merge pull request #1657 from houseme/fix-1655
fix: server access logs contain the protocol used between the server …
2022-03-09 22:23:40 +08:00
3d6867c321 fix 2022-03-09 21:29:49 +08:00
3d5ff3b250 fix 2022-03-09 21:27:02 +08:00
be47203732 improve code 2022-03-09 21:24:57 +08:00
1625fc6f7e improve order feature for gdb.Model 2022-03-09 21:02:08 +08:00
fa57634505 Merge pull request #1529 from zxr615/feature-groupRaw
Added Order() method support for gdb.
2022-03-09 20:55:15 +08:00
ac71658b4b Merge branch 'master' into feature-groupRaw 2022-03-09 20:55:06 +08:00
61db7d96b7 Merge pull request #1520 from FlyingBlazer/patch-1
Fix gdb Order
2022-03-09 20:48:54 +08:00
5ee297d999 Merge pull request #1651 from chenzebinm4/develop/bert
Repeat 'len(s)'.
2022-03-09 20:46:41 +08:00
6301403777 Merge pull request #1632 from huangqian1985/master
Improving gfile and gSesssion Code Coverage
2022-03-09 20:45:44 +08:00
95881d7616 Merge pull request #1652 from stardemo/master
[fix] gf cli build missing suffix
2022-03-09 20:43:40 +08:00
85d8f90d81 Merge pull request #1656 from tiger1103/master
[fix bug] Fix redis cache adapter GetOrSetFunc, GetOrSetFuncLock meth…
2022-03-09 20:42:44 +08:00
f6054ab37f improve code 2022-03-09 18:32:13 +08:00
5537930210 fix 2022-03-09 18:30:32 +08:00
920dbbef5e fix: server access logs contain the protocol used between the server and the load balancer, but not the protocol used between the client and the load balancer 2022-03-09 17:42:56 +08:00
yxh
2510e0412d [fix bug] Fix redis cache adapter GetOrSetFunc, GetOrSetFuncLock method bug and add unit test 2022-03-09 17:21:02 +08:00
2302f88847 [fix] gf cli build missing suffix 2022-03-09 11:27:52 +08:00
4f95d0a07a Repeat 'len(s)'. 2022-03-09 10:53:28 +08:00
8f326dcac5 project template update 2022-03-08 22:51:56 +08:00
aa294ea5df ci updates 2022-03-08 21:27:14 +08:00
6afc725b61 ci updates 2022-03-08 21:22:01 +08:00
ec01693773 ci updates 2022-03-08 21:04:48 +08:00
b0cf501782 ci updates 2022-03-08 20:28:18 +08:00
c2fb7ada0a improve example for package gmap 2022-03-08 20:25:34 +08:00
d0a8e60ace improve example for package gmap 2022-03-08 20:14:38 +08:00
ab36bb8842 version updates 2022-03-08 20:12:48 +08:00
0b3cd7b7ae improve handler response for ghttp.Server 2022-03-08 11:50:23 +08:00
10ed04cdb8 example updates for package gmap 2022-03-08 09:49:33 +08:00
f08c18594b Merge branch 'master' of https://github.com/gogf/gf 2022-03-07 22:35:39 +08:00
e09704a408 example updates for package gmap 2022-03-07 22:10:34 +08:00
ade9ae3c0b improve package goai 2022-03-07 21:29:37 +08:00
9cf6124c4c improve package goai 2022-03-07 21:09:02 +08:00
6d323cc529 improve package goai 2022-03-07 20:49:30 +08:00
aea9f6fe18 keep sequence in attributes definition for oai.Schemas 2022-03-07 19:46:05 +08:00
8a27463e44 ensure sequence for json.Marshal for gmap.ListMap/TreeMap 2022-03-07 17:39:41 +08:00
47ee2cba51 Merge branch 'master' of https://github.com/gogf/gf 2022-03-07 09:58:07 +08:00
531cc7b864 fix issue in package gproc 2022-03-07 09:57:51 +08:00
54bdabd94d Merge pull request #1549 from FlyingBlazer/cookie-secure-config
ghttp: add cookie security configurations
2022-03-04 17:42:44 +08:00
bb6e8fe7a8 Merge branch 'master' of https://github.com/gogf/gf 2022-03-04 11:37:30 +08:00
d5d199ebef Swagger UI updates 2022-03-04 11:36:05 +08:00
158a4589d2 Merge pull request #1637 from wangbs95/feature/fix-chinese-encode
fix(fix bug , add nexttime feature): ServeFileDownload filename doubl…
2022-03-04 09:32:01 +08:00
84c0f456c0 template pack update 2022-03-03 21:43:01 +08:00
3fcd6ef877 fix issue orphan value parsing for sructured arguments of command for package gcmd 2022-03-03 21:03:42 +08:00
b5855037f3 Improving gSession Code Coverage 2022-03-02 21:50:23 +08:00
4e2d378145 improve file uploading using strict route feature 2022-03-02 21:15:16 +08:00
38a7055017 Merge branch 'master' of https://github.com/gogf/gf 2022-03-02 21:05:14 +08:00
d64898c59a improve package goai 2022-03-02 20:00:40 +08:00
3bff71b3fc merge master and update unit test 2022-03-02 15:33:58 +08:00
8343d1cd0e Merge branch 'master' into cookie-secure-config 2022-03-02 15:20:31 +08:00
5c23c0cecd fix(fix bug , add nexttime feature): ServeFileDownload filename double quotes cause underscores before and after the final file 2022-03-02 11:00:04 +08:00
f580713478 Merge branch 'master' of https://github.com/gogf/gf 2022-03-02 10:26:20 +08:00
3c58b8d7fa improve openapi 2022-03-02 10:26:09 +08:00
072d5f9760 make options public 2022-03-02 09:56:58 +08:00
f8067f5dd5 improve package ghttp 2022-03-01 22:53:19 +08:00
ea354d10cc Merge pull request #1636 from wangbs95/feature/fix-chinese-encode
revert(fix bug , add nexttime feature): ServeFileDownload File name C…
2022-03-01 22:52:34 +08:00
4d5b41434a Merge branch 'master' of https://github.com/gogf/gf 2022-03-01 22:38:51 +08:00
1724a26957 improve package gcfg 2022-03-01 22:34:57 +08:00
cb69fbcbd6 Improving gSession Code Coverage 2022-03-01 22:12:59 +08:00
46dc68dfd5 CI update for gf cli 2022-03-01 21:20:17 +08:00
12fdfbf8b2 improve package gcfg 2022-03-01 21:14:45 +08:00
992a986d12 Merge branch 'master' of https://github.com/gogf/gf 2022-03-01 20:02:21 +08:00
68bdf7deb4 revert(fix bug , add nexttime feature): ServeFileDownload File name Chinese garbled repair 2022-03-01 18:32:11 +08:00
2362c453ec improve cli command install 2022-03-01 16:39:47 +08:00
50f6b6e0f0 fix UT case for package ghttp 2022-03-01 14:08:36 +08:00
88a9eef8a6 api swagger ui update 2022-03-01 11:43:42 +08:00
eb533f3344 Improving gfile Code Coverage 2022-02-28 22:57:53 +08:00
308e13a546 gf cli command build update 2022-02-28 22:00:25 +08:00
a0b1fefdbb Merge branch 'master' of https://github.com/gogf/gf 2022-02-28 21:58:15 +08:00
3edbcb7bf9 gf cli update 2022-02-28 21:57:59 +08:00
436931b560 Merge branch 'master' of https://github.com/gogf/gf 2022-02-28 21:15:15 +08:00
0516159ae3 Improving gcmd Code Coverage 2022-02-28 21:11:53 +08:00
cb78953b38 Merge pull request #1628 from huangqian1985/master
Improving gcmd Code Coverage
2022-02-28 20:45:01 +08:00
a1ddac4e6b Merge branch 'master' of https://github.com/gogf/gf 2022-02-28 17:49:16 +08:00
456697ea99 improve cli command install 2022-02-28 17:48:52 +08:00
8acffd1186 Improving gcmd Code Coverage 2022-02-27 21:00:23 +08:00
814450fd17 gcmd example 2022-02-27 13:22:26 +08:00
1365c1d277 Merge pull request #1623 from huangqian1985/master
Improving gjson Code Coverage
2022-02-27 08:59:19 +08:00
30be5c5e49 Improving gjson Code Coverage And Fix 2022-02-26 21:26:30 +08:00
932cd9d5bb README updates 2022-02-25 10:22:54 +08:00
7b5f17c16b gf cli pack template update 2022-02-24 22:44:48 +08:00
b5e8e68713 fix issue #1625 2022-02-24 22:07:27 +08:00
3a803ac39f fix 2022-02-24 21:41:39 +08:00
d27db119a0 fix issue #1626 2022-02-24 21:24:42 +08:00
f54d0a339c Improving gjson Code Coverage 2022-02-24 21:14:11 +08:00
d83b676c60 Merge branch 'gjson_example' 2022-02-24 20:15:55 +08:00
def3dc364f Merge branch 'master' of https://github.com/gogf/gf 2022-02-24 20:15:44 +08:00
298aa5f040 Improving gjson Code Coverage 2022-02-24 20:14:44 +08:00
e4d56e7ad9 improve package gjson 2022-02-23 16:54:15 +08:00
0fce4edcd3 Merge branch 'master' of https://github.com/gogf/gf 2022-02-23 00:46:47 +08:00
a34f52ae5e Merge branch 'gjson_example' 2022-02-23 00:46:33 +08:00
da465bb030 Improving gjson Code Coverage 2022-02-23 00:46:13 +08:00
658ca8c0fd Eg 2022-01-17 17:14:40 +08:00
d30862373e 修正测试数据库配置 2022-01-07 22:25:00 +08:00
ee4ca43bd5 Safe() 2022-01-07 22:21:18 +08:00
0dc1adb672 orderBy raw() 2022-01-07 21:06:49 +08:00
d045b4d2f5 make unit test compatible with go 1.15 2022-01-07 18:52:21 +08:00
572e71d76a add CookieOptions
add UnitTest
2022-01-07 17:10:21 +08:00
c91b83969c WIP: add cookie security configuration 2022-01-05 14:33:20 +08:00
47cefbf6d7 允许多次调用Order 2022-01-05 11:53:50 +08:00
b39b2374c4 Added Order() method support for gdb. 2021-12-22 20:51:03 +08:00
234 changed files with 3395 additions and 1480 deletions

View File

@ -1,12 +1,11 @@
<!-- Please answer these questions before submitting your issue. Thanks! -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码 -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码 -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码 -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码否则issue可能会被延期处理 -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码否则issue可能会被延期处理 -->
<!-- 为高效处理您的疑问如果觉得是BUG类问题请您务必提供可复现该问题的最小可运行代码否则issue可能会被延期处理 -->
<!-- 重要的事情说三遍! -->
### 1. What version of `Go` and system type/arch are you using?
<!--
Please paste the output of command `go version` from your terminal.
What expect to see is like: `go 1.12, linux/amd64`
@ -14,7 +13,6 @@ What expect to see is like: `go 1.12, linux/amd64`
### 2. What version of `GoFrame` are you using?
<!-- You can find the GF version from your `go.mod`, or from the `version.go` in `GF` -->
@ -23,7 +21,6 @@ What expect to see is like: `go 1.12, linux/amd64`
### 4. What did you do?
<!--
If possible, provide a copy of shortest codes for reproducing the error.
A complete runnable program is best.

View File

@ -6,6 +6,10 @@ on:
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
TZ: Asia/Shanghai
jobs:
build:
name: Build And Release
@ -26,37 +30,21 @@ jobs:
GOOS=linux GOARCH=amd64 go build main.go
chmod +x main
./main install -y
# gf build
- name: Build CLI Binary For All Platform
run: |
cd cmd/gf
gf build main.go -n gf -a all -s all
# 处理gf-cli批量编译后的文件结构
- name: Move Files Before Upx
- name: Move Files Before Release
run: |
cd cmd/gf/bin
cd cmd/gf/temp
for OS in *;do for FILE in $OS/*;\
do if [[ ${OS} =~ 'windows' ]];\
then rm -rf noupx && mkdir noupx && mv $FILE noupx/gf_$OS.exe && rm -rf $OS;\
then mv $FILE gf_$OS.exe && rm -rf $OS;\
else mv $FILE gf_$OS && rm -rf $OS;\
fi;done;done
# UPX 加壳所有文件
- name: Upx All Binary
uses: gacts/upx@master
with:
dir: 'cmd/gf/bin'
upx_args: '-9'
# 移动未UPX的windows程序到上传bin目录下
- name: Move Files After Upx
run: |
cd cmd/gf/bin
mv noupx/* ./ && rm -rf noupx
ls -l
- name: Create Github Release
id: create_release
uses: actions/create-release@v1
@ -74,4 +62,4 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_paths: '["cmd/gf/bin/gf_*"]'
asset_paths: '["cmd/gf/temp/gf_*"]'

View File

@ -7,26 +7,17 @@
You can also install `gf` tool using pre-built binaries: https://github.com/gogf/gf/releases
1. `Mac`
1. `Mac` & `Linux`
```shell
# Intel.
wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_darwin_amd64 && chmod +x gf && ./gf install && rm ./gf
# M1.
wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_darwin_arm64 && chmod +x gf && ./gf install && rm ./gf
wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_$(go env GOOS)_$(go env GOARCH) && chmod +x gf && ./gf install -y && rm ./gf
```
> If you're using `zsh`, you might need rename your alias by command `alias gf=gf` to resolve the conflicts between `gf` and `git fetch`.
2. `Linux`
```shell
wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_linux_amd64 && chmod +x gf && ./gf install && rm ./gf
```
3. `Windows`
2. `Windows`
Manually download, execute it and then follow the instruction.
4. Database `sqlite` and `oracle` are not support in `gf gen` command in default as it needs `cgo` and `gcc`, you can manually make some changes to the source codes and do the building.
3. Database `sqlite` and `oracle` are not support in `gf gen` command in default as it needs `cgo` and `gcc`, you can manually make some changes to the source codes and do the building.
## 2. Commands
```html

View File

@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"regexp"
"runtime"
"strings"
@ -114,11 +115,12 @@ type cBuildInput struct {
Arch string `short:"a" name:"arch" brief:"output binary architecture, multiple arch separated with ','"`
System string `short:"s" name:"system" brief:"output binary system, multiple os separated with ','"`
Output string `short:"o" name:"output" brief:"output binary path, used when building single binary file"`
Path string `short:"p" name:"path" brief:"output binary directory path, default is './bin'" d:"./bin"`
Path string `short:"p" name:"path" brief:"output binary directory path, default is './temp'" d:"./temp"`
Extra string `short:"e" name:"extra" brief:"extra custom \"go build\" options"`
Mod string `short:"m" name:"mod" brief:"like \"-mod\" option of \"go build\", use \"-m none\" to disable go module"`
Cgo bool `short:"c" name:"cgo" brief:"enable or disable cgo feature, it's disabled in default" orphan:"true"`
VarMap g.Map `short:"r" name:"varMap" brief:"custom built embedded variable into binary"`
Exit bool `name:"exit" brief:"exit building when any error occurs, default is false" orphan:"true"`
Pack string `name:"pack" brief:"pack specified folder into temporary go file before building and removes it after built"`
}
type cBuildOutput struct{}
@ -254,7 +256,14 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e
cmdShow, _ := gregex.ReplaceString(`\s+(-ldflags ".+?")\s+`, " ", cmd)
mlog.Print(cmdShow)
if result, err := gproc.ShellExec(cmd); err != nil {
mlog.Printf("failed to build, os:%s, arch:%s, error:\n%s\n", system, arch, gstr.Trim(result))
mlog.Printf(
"failed to build, os:%s, arch:%s, error:\n%s\n\n%s\n",
system, arch, gstr.Trim(result),
`you may use command option "--debug" to enable debug info and check the details`,
)
if in.Exit {
os.Exit(1)
}
} else {
mlog.Debug(gstr.Trim(result))
}
@ -264,6 +273,7 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e
}
}
}
buildDone:
mlog.Print("done!")
return

View File

@ -81,6 +81,7 @@ func (c cDocker) Index(ctx context.Context, in cDockerInput) (out *cDockerOutput
}
// Binary build.
in.Build += " --exit"
if in.Main != "" {
if err = gproc.ShellRun(fmt.Sprintf(`gf build %s %s`, in.Main, in.Build)); err != nil {
return

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -32,7 +32,7 @@ type serviceInstallAvailablePath struct {
func (s serviceInstall) Run(ctx context.Context) (err error) {
// Ask where to install.
paths := s.getInstallPathsData()
paths := s.getAvailablePaths()
if len(paths) <= 0 {
mlog.Printf("no path detected, you can manually install gf by copying the binary to path folder.")
return
@ -43,16 +43,21 @@ func (s serviceInstall) Run(ctx context.Context) (err error) {
// Print all paths status and determine the default selectedID value.
var (
selectedID = -1
newPaths []serviceInstallAvailablePath
pathSet = gset.NewStrSet() // Used for repeated items filtering.
)
for id, aPath := range paths {
if !pathSet.AddIfNotExist(aPath.dirPath) {
for _, path := range paths {
if !pathSet.AddIfNotExist(path.dirPath) {
continue
}
mlog.Printf(" %2d | %8t | %9t | %s", id, aPath.writable, aPath.installed, aPath.dirPath)
newPaths = append(newPaths, path)
}
paths = newPaths
for id, path := range paths {
mlog.Printf(" %2d | %8t | %9t | %s", id, path.writable, path.installed, path.dirPath)
if selectedID == -1 {
// Use the previously installed path as the most priority choice.
if aPath.installed {
if path.installed {
selectedID = id
}
}
@ -61,6 +66,7 @@ func (s serviceInstall) Run(ctx context.Context) (err error) {
if selectedID == -1 {
// Order by choosing priority.
commonPaths := garray.NewStrArrayFrom(g.SliceStr{
s.getGoPathBin(),
`/usr/local/bin`,
`/usr/bin`,
`/usr/sbin`,
@ -121,10 +127,10 @@ func (s serviceInstall) Run(ctx context.Context) (err error) {
}
// Uninstall the old binary.
for _, aPath := range paths {
for _, path := range paths {
// Do not delete myself.
if aPath.filePath != "" && aPath.filePath != dstPath.filePath && gfile.SelfPath() != aPath.filePath {
_ = gfile.Remove(aPath.filePath)
if path.filePath != "" && path.filePath != dstPath.filePath && gfile.SelfPath() != path.filePath {
_ = gfile.Remove(path.filePath)
}
}
return
@ -132,7 +138,7 @@ func (s serviceInstall) Run(ctx context.Context) (err error) {
// IsInstalled checks and returns whether the binary is installed.
func (s serviceInstall) IsInstalled() bool {
paths := s.getInstallPathsData()
paths := s.getAvailablePaths()
for _, aPath := range paths {
if aPath.installed {
return true
@ -141,11 +147,26 @@ func (s serviceInstall) IsInstalled() bool {
return false
}
// GetInstallPathsData returns the installation paths data for the binary.
func (s serviceInstall) getInstallPathsData() []serviceInstallAvailablePath {
var folderPaths []serviceInstallAvailablePath
// Pre generate binaryFileName.
binaryFileName := "gf" + gfile.Ext(gfile.SelfPath())
// getGoPathBinFilePath retrieves ad returns the GOPATH/bin path for binary.
func (s serviceInstall) getGoPathBin() string {
if goPath := genv.Get(`GOPATH`).String(); goPath != "" {
return gfile.Join(goPath, "bin")
}
return ""
}
// getAvailablePaths returns the installation paths data for the binary.
func (s serviceInstall) getAvailablePaths() []serviceInstallAvailablePath {
var (
folderPaths []serviceInstallAvailablePath
binaryFileName = "gf" + gfile.Ext(gfile.SelfPath())
)
// $GOPATH/bin
if goPathBin := s.getGoPathBin(); goPathBin != "" {
folderPaths = s.checkAndAppendToAvailablePath(
folderPaths, goPathBin, binaryFileName,
)
}
switch runtime.GOOS {
case "darwin":
darwinInstallationCheckPaths := []string{"/usr/local/bin"}
@ -157,21 +178,24 @@ func (s serviceInstall) getInstallPathsData() []serviceInstallAvailablePath {
fallthrough
default:
// $GOPATH/bin
gopath := gfile.Join(runtime.GOROOT(), "bin")
folderPaths = s.checkAndAppendToAvailablePath(
folderPaths, gopath, binaryFileName,
)
// Search and find the writable directory path.
envPath := genv.Get("PATH", genv.Get("Path").String()).String()
if gstr.Contains(envPath, ";") {
// windows.
for _, v := range gstr.SplitAndTrim(envPath, ";") {
if v == "." {
continue
}
folderPaths = s.checkAndAppendToAvailablePath(
folderPaths, v, binaryFileName,
)
}
} else if gstr.Contains(envPath, ":") {
// *nix.
for _, v := range gstr.SplitAndTrim(envPath, ":") {
if v == "." {
continue
}
folderPaths = s.checkAndAppendToAvailablePath(
folderPaths, v, binaryFileName,
)

View File

@ -3,7 +3,6 @@ package mlog
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/genv"
"github.com/gogf/gf/v2/os/glog"
@ -36,9 +35,9 @@ func init() {
func SetHeaderPrint(enabled bool) {
logger.SetHeaderPrint(enabled)
if enabled {
genv.Set(headerPrintEnvName, "1")
_ = genv.Set(headerPrintEnvName, "1")
} else {
genv.Set(headerPrintEnvName, "0")
_ = genv.Set(headerPrintEnvName, "0")
}
}
@ -51,17 +50,17 @@ func Printf(format string, v ...interface{}) {
}
func Fatal(v ...interface{}) {
logger.Fatal(ctx, append(g.Slice{"ERROR:"}, v...)...)
logger.Fatal(ctx, v...)
}
func Fatalf(format string, v ...interface{}) {
logger.Fatalf(ctx, "ERROR: "+format, v...)
logger.Fatalf(ctx, format, v...)
}
func Debug(v ...interface{}) {
logger.Debug(ctx, append(g.Slice{"DEBUG:"}, v...)...)
logger.Debug(ctx, v...)
}
func Debugf(format string, v ...interface{}) {
logger.Debugf(ctx, "DEBUG: "+format, v...)
logger.Debugf(ctx, format, v...)
}

View File

@ -576,7 +576,7 @@ func TestArray_Json(t *testing.T) {
var a3 garray.Array
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// value.
@ -595,7 +595,7 @@ func TestArray_Json(t *testing.T) {
var a3 garray.Array
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// pointer
@ -609,11 +609,11 @@ func TestArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -628,11 +628,11 @@ func TestArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -720,7 +720,7 @@ func TestArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": g.Slice{1, 2, 3},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})

View File

@ -619,7 +619,7 @@ func TestIntArray_Json(t *testing.T) {
var a3 garray.IntArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array value
@ -637,7 +637,7 @@ func TestIntArray_Json(t *testing.T) {
var a3 garray.IntArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array pointer
@ -651,11 +651,11 @@ func TestIntArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -670,11 +670,11 @@ func TestIntArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -752,7 +752,7 @@ func TestIntArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": []byte(`[1,2,3]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})
@ -763,7 +763,7 @@ func TestIntArray_UnmarshalValue(t *testing.T) {
// "name": "john",
// "array": g.Slice{1, 2, 3},
// }, &v)
// t.Assert(err, nil)
// t.AssertNil(err)
// t.Assert(v.Name, "john")
// t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
// })

View File

@ -619,7 +619,7 @@ func TestStrArray_Json(t *testing.T) {
var a3 garray.StrArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array value
@ -637,7 +637,7 @@ func TestStrArray_Json(t *testing.T) {
var a3 garray.StrArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array pointer
@ -651,11 +651,11 @@ func TestStrArray_Json(t *testing.T) {
"Scores": []string{"A+", "A", "A"},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -670,11 +670,11 @@ func TestStrArray_Json(t *testing.T) {
"Scores": []string{"A+", "A", "A"},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, data["Scores"])
})
@ -751,7 +751,7 @@ func TestStrArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": []byte(`["1","2","3"]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.SliceStr{"1", "2", "3"})
})
@ -762,7 +762,7 @@ func TestStrArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": g.SliceStr{"1", "2", "3"},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.SliceStr{"1", "2", "3"})
})

View File

@ -661,7 +661,7 @@ func TestSortedArray_Json(t *testing.T) {
var a3 garray.SortedArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
t.Assert(a3.Interfaces(), s1)
})
@ -681,7 +681,7 @@ func TestSortedArray_Json(t *testing.T) {
var a3 garray.SortedArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
t.Assert(a3.Interfaces(), s1)
})
@ -696,11 +696,11 @@ func TestSortedArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.AssertNE(user.Scores, nil)
t.Assert(user.Scores.Len(), 3)
@ -732,11 +732,11 @@ func TestSortedArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.AssertNE(user.Scores, nil)
t.Assert(user.Scores.Len(), 3)
@ -830,7 +830,7 @@ func TestSortedArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": []byte(`[2,3,1]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})
@ -841,7 +841,7 @@ func TestSortedArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": g.Slice{2, 3, 1},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})

View File

@ -561,7 +561,7 @@ func TestSortedIntArray_Json(t *testing.T) {
var a3 garray.SortedIntArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array value
@ -580,7 +580,7 @@ func TestSortedIntArray_Json(t *testing.T) {
var a3 garray.SortedIntArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
})
// array pointer
@ -594,11 +594,11 @@ func TestSortedIntArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, []int{98, 99, 100})
})
@ -613,11 +613,11 @@ func TestSortedIntArray_Json(t *testing.T) {
"Scores": []int{99, 100, 98},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, []int{98, 99, 100})
})
@ -695,7 +695,7 @@ func TestSortedIntArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": []byte(`[2,3,1]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})
@ -706,7 +706,7 @@ func TestSortedIntArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": g.Slice{2, 3, 1},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.Slice{1, 2, 3})
})

View File

@ -583,7 +583,7 @@ func TestSortedStrArray_Json(t *testing.T) {
var a3 garray.SortedStrArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
t.Assert(a3.Interfaces(), s1)
})
@ -604,7 +604,7 @@ func TestSortedStrArray_Json(t *testing.T) {
var a3 garray.SortedStrArray
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Slice(), s1)
t.Assert(a3.Interfaces(), s1)
})
@ -619,11 +619,11 @@ func TestSortedStrArray_Json(t *testing.T) {
"Scores": []string{"A+", "A", "A"},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, []string{"A", "A", "A+"})
})
@ -638,11 +638,11 @@ func TestSortedStrArray_Json(t *testing.T) {
"Scores": []string{"A+", "A", "A"},
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
user := new(User)
err = json.UnmarshalUseNumber(b, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Name, data["Name"])
t.Assert(user.Scores, []string{"A", "A", "A+"})
})
@ -719,7 +719,7 @@ func TestSortedStrArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": []byte(`["1","3","2"]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.SliceStr{"1", "2", "3"})
})
@ -730,7 +730,7 @@ func TestSortedStrArray_UnmarshalValue(t *testing.T) {
"name": "john",
"array": g.SliceStr{"1", "3", "2"},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Array.Slice(), g.SliceStr{"1", "2", "3"})
})

View File

@ -709,20 +709,20 @@ func TestList_Json(t *testing.T) {
a := []interface{}{"a", "b", "c"}
l := New()
b, err := json.Marshal(a)
t.Assert(err, nil)
t.AssertNil(err)
err = json.UnmarshalUseNumber(b, l)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(l.FrontAll(), a)
})
gtest.C(t, func(t *gtest.T) {
var l List
a := []interface{}{"a", "b", "c"}
b, err := json.Marshal(a)
t.Assert(err, nil)
t.AssertNil(err)
err = json.UnmarshalUseNumber(b, &l)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(l.FrontAll(), a)
})
}
@ -739,7 +739,7 @@ func TestList_UnmarshalValue(t *testing.T) {
"name": "john",
"list": []byte(`[1,2,3]`),
}, &tlist)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(tlist.Name, "john")
t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3})
})
@ -750,7 +750,7 @@ func TestList_UnmarshalValue(t *testing.T) {
"name": "john",
"list": []interface{}{1, 2, 3},
}, &tlist)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(tlist.Name, "john")
t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3})
})

View File

@ -7,6 +7,9 @@
package gmap
import (
"bytes"
"fmt"
"github.com/gogf/gf/v2/container/glist"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/internal/empty"
@ -15,6 +18,13 @@ import (
"github.com/gogf/gf/v2/util/gconv"
)
// ListMap is a map that preserves insertion-order.
//
// It is backed by a hash table to store values and doubly-linked list to store ordering.
//
// Structure is not thread safe.
//
// Reference: http://en.wikipedia.org/wiki/Associative_array
type ListMap struct {
mu rwmutex.RWMutex
data map[interface{}]*glist.Element
@ -58,7 +68,7 @@ func (m *ListMap) IteratorAsc(f func(key interface{}, value interface{}) bool) {
m.mu.RLock()
defer m.mu.RUnlock()
if m.list != nil {
node := (*gListMapNode)(nil)
var node *gListMapNode
m.list.IteratorAsc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode)
return f(node.key, node.value)
@ -72,7 +82,7 @@ func (m *ListMap) IteratorDesc(f func(key interface{}, value interface{}) bool)
m.mu.RLock()
defer m.mu.RUnlock()
if m.list != nil {
node := (*gListMapNode)(nil)
var node *gListMapNode
m.list.IteratorDesc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode)
return f(node.key, node.value)
@ -146,8 +156,10 @@ func (m *ListMap) MapStrAny() map[string]interface{} {
func (m *ListMap) FilterEmpty() {
m.mu.Lock()
if m.list != nil {
keys := make([]interface{}, 0)
node := (*gListMapNode)(nil)
var (
keys = make([]interface{}, 0)
node *gListMapNode
)
m.list.IteratorAsc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode)
if empty.IsEmpty(node.value) {
@ -495,7 +507,7 @@ func (m *ListMap) Merge(other *ListMap) {
other.mu.RLock()
defer other.mu.RUnlock()
}
node := (*gListMapNode)(nil)
var node *gListMapNode
other.list.IteratorAsc(func(e *glist.Element) bool {
node = e.Value.(*gListMapNode)
if e, ok := m.data[node.key]; !ok {
@ -514,8 +526,26 @@ func (m *ListMap) String() string {
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (m ListMap) MarshalJSON() ([]byte, error) {
return json.Marshal(gconv.Map(m.Map()))
func (m ListMap) MarshalJSON() (jsonBytes []byte, err error) {
if m.data == nil {
return []byte("null"), nil
}
buffer := bytes.NewBuffer(nil)
buffer.WriteByte('{')
m.Iterator(func(key, value interface{}) bool {
valueBytes, valueJsonErr := json.Marshal(value)
if valueJsonErr != nil {
err = valueJsonErr
return false
}
if buffer.Len() > 1 {
buffer.WriteByte(',')
}
buffer.WriteString(fmt.Sprintf(`"%v":%s`, key, valueBytes))
return true
})
buffer.WriteByte('}')
return buffer.Bytes(), nil
}
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

View File

@ -8,6 +8,7 @@ package gmap_test
import (
"fmt"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/internal/json"
@ -195,7 +196,7 @@ func ExampleListMap_Sets() {
m.Sets(addMap)
fmt.Println(m)
// Output:
// May Output:
// {"key1":"val1","key2":"val2","key3":"val3"}
}
@ -562,12 +563,10 @@ func ExampleListMap_String() {
func ExampleListMap_MarshalJSON() {
var m gmap.ListMap
m.Sets(g.MapAnyAny{
"k1": "v1",
"k2": "v2",
"k3": "v3",
"k4": "v4",
})
m.Set("k1", "v1")
m.Set("k2", "v2")
m.Set("k3", "v3")
m.Set("k4", "v4")
bytes, err := json.Marshal(&m)
if err == nil {

View File

@ -8,6 +8,7 @@ package gmap_test
import (
"fmt"
"github.com/gogf/gf/v2/util/gutil"
"github.com/gogf/gf/v2/container/gmap"
@ -277,7 +278,7 @@ func ExampleNewListMapFrom() {
n := gmap.NewListMapFrom(m.Map(), true)
fmt.Println(n)
// Output:
// May Output:
// {"key1":"var1","key2":"var2"}
// {"key1":"var1","key2":"var2"}
}
@ -290,7 +291,7 @@ func ExampleNewTreeMap() {
fmt.Println(m.Map())
// Output:
// May Output:
// map[key1:var1 key2:var2]
}
@ -305,7 +306,7 @@ func ExampleNewTreeMapFrom() {
n := gmap.NewListMapFrom(m.Map(), true)
fmt.Println(n.Map())
// Output:
// May Output:
// map[key1:var1 key2:var2]
// map[key1:var1 key2:var2]
}

View File

@ -253,11 +253,11 @@ func Test_AnyAnyMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.New()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -267,11 +267,11 @@ func Test_AnyAnyMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.Map
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -342,7 +342,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")
@ -358,7 +358,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) {
"k2": "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")

View File

@ -242,11 +242,11 @@ func Test_IntAnyMap_Json(t *testing.T) {
2: "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewIntAnyMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get(1), data[1])
t.Assert(m.Get(2), data[2])
})
@ -317,7 +317,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "v1")
@ -333,7 +333,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) {
2: "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "v1")

View File

@ -248,11 +248,11 @@ func Test_IntIntMap_Json(t *testing.T) {
2: 20,
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewIntIntMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get(1), data[1])
t.Assert(m.Get(2), data[2])
})
@ -323,7 +323,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"1":1,"2":2}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "1")
@ -339,7 +339,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) {
2: 2,
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "1")

View File

@ -246,11 +246,11 @@ func Test_IntStrMap_Json(t *testing.T) {
2: "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewIntStrMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get(1), data[1])
t.Assert(m.Get(2), data[2])
})
@ -321,7 +321,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "v1")
@ -337,7 +337,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) {
2: "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get(1), "v1")

View File

@ -240,11 +240,11 @@ func Test_StrAnyMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewStrAnyMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -254,11 +254,11 @@ func Test_StrAnyMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.StrAnyMap
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -329,7 +329,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")
@ -345,7 +345,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) {
"k2": "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")

View File

@ -244,11 +244,11 @@ func Test_StrIntMap_Json(t *testing.T) {
"k2": 2,
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewStrIntMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -258,11 +258,11 @@ func Test_StrIntMap_Json(t *testing.T) {
"k2": 2,
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.StrIntMap
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -333,7 +333,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"k1":1,"k2":2}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), 1)
@ -349,7 +349,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) {
"k2": 2,
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), 1)

View File

@ -241,11 +241,11 @@ func Test_StrStrMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewStrStrMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -255,11 +255,11 @@ func Test_StrStrMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(data)
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.StrStrMap
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -330,7 +330,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")
@ -346,7 +346,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) {
"k2": "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")

View File

@ -186,12 +186,12 @@ func Test_ListMap_Json(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
data := g.MapAnyAny{
"k1": "v1",
"k2": "v2",
}
m1 := gmap.NewListMapFrom(data)
b1, err1 := json.Marshal(m1)
t.AssertNil(err1)
b2, err2 := json.Marshal(gconv.Map(data))
t.Assert(err1, err2)
t.AssertNil(err2)
t.Assert(b1, b2)
})
// Unmarshal
@ -201,11 +201,11 @@ func Test_ListMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewListMap()
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -216,16 +216,37 @@ func Test_ListMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.ListMap
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
}
func Test_ListMap_Json_Sequence(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
m := gmap.NewListMap()
for i := 'z'; i >= 'a'; i-- {
m.Set(string(i), i)
}
b, err := json.Marshal(m)
t.AssertNil(err)
t.Assert(b, `{"z":122,"y":121,"x":120,"w":119,"v":118,"u":117,"t":116,"s":115,"r":114,"q":113,"p":112,"o":111,"n":110,"m":109,"l":108,"k":107,"j":106,"i":105,"h":104,"g":103,"f":102,"e":101,"d":100,"c":99,"b":98,"a":97}`)
})
gtest.C(t, func(t *gtest.T) {
m := gmap.NewListMap()
for i := 'a'; i <= 'z'; i++ {
m.Set(string(i), i)
}
b, err := json.Marshal(m)
t.AssertNil(err)
t.Assert(b, `{"a":97,"b":98,"c":99,"d":100,"e":101,"f":102,"g":103,"h":104,"i":105,"j":106,"k":107,"l":108,"m":109,"n":110,"o":111,"p":112,"q":113,"r":114,"s":115,"t":116,"u":117,"v":118,"w":119,"x":120,"y":121,"z":122}`)
})
}
func Test_ListMap_Pop(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
m := gmap.NewListMapFrom(g.MapAnyAny{
@ -291,7 +312,7 @@ func TestListMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"1":"v1","2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("1"), "v1")
@ -307,7 +328,7 @@ func TestListMap_UnmarshalValue(t *testing.T) {
2: "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("1"), "v1")

View File

@ -185,11 +185,11 @@ func Test_TreeMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
m := gmap.NewTreeMap(gutil.ComparatorString)
err = json.UnmarshalUseNumber(b, m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -199,11 +199,11 @@ func Test_TreeMap_Json(t *testing.T) {
"k2": "v2",
}
b, err := json.Marshal(gconv.Map(data))
t.Assert(err, nil)
t.AssertNil(err)
var m gmap.TreeMap
err = json.UnmarshalUseNumber(b, &m)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m.Get("k1"), data["k1"])
t.Assert(m.Get("k2"), data["k2"])
})
@ -221,7 +221,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) {
"name": "john",
"map": []byte(`{"k1":"v1","k2":"v2"}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")
@ -237,7 +237,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) {
"k2": "v2",
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Map.Size(), 2)
t.Assert(v.Map.Get("k1"), "v1")

View File

@ -109,7 +109,7 @@ func (p *Pool) Get() (interface{}, error) {
if f.expireAt == 0 || f.expireAt > gtime.TimestampMilli() {
return f.value, nil
} else if p.ExpireFunc != nil {
// TODO: move expire function calling asynchronously from `Get` operation.
// TODO: move expire function calling asynchronously out from `Get` operation.
p.ExpireFunc(f.value)
}
} else {
@ -129,7 +129,7 @@ func (p *Pool) Size() int {
// Close closes the pool. If `p` has ExpireFunc,
// then it automatically closes all items using this function before it's closed.
// Commonly you do not need call this function manually.
// Commonly you do not need to call this function manually.
func (p *Pool) Close() {
p.closed.Set(true)
}

View File

@ -336,7 +336,7 @@ func TestSet_Json(t *testing.T) {
var a3 gset.Set
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Contains("a"), true)
t.Assert(a3.Contains("b"), true)
t.Assert(a3.Contains("c"), true)
@ -438,7 +438,7 @@ func TestSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": []byte(`["k1","k2","k3"]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains("k1"), true)
@ -453,7 +453,7 @@ func TestSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": g.Slice{"k1", "k2", "k3"},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains("k1"), true)

View File

@ -368,7 +368,7 @@ func TestIntSet_Json(t *testing.T) {
var a3 gset.IntSet
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a2.Contains(1), true)
t.Assert(a2.Contains(2), true)
t.Assert(a2.Contains(3), true)
@ -402,7 +402,7 @@ func TestIntSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": []byte(`[1,2,3]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains(1), true)
@ -417,7 +417,7 @@ func TestIntSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": g.Slice{1, 2, 3},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains(1), true)

View File

@ -414,7 +414,7 @@ func TestStrSet_Json(t *testing.T) {
var a3 gset.StrSet
err := json.UnmarshalUseNumber(b2, &a3)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a3.Contains("a"), true)
t.Assert(a3.Contains("b"), true)
t.Assert(a3.Contains("c"), true)
@ -453,7 +453,7 @@ func TestStrSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": []byte(`["1","2","3"]`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains("1"), true)
@ -468,7 +468,7 @@ func TestStrSet_UnmarshalValue(t *testing.T) {
"name": "john",
"set": g.SliceStr{"1", "2", "3"},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Set.Size(), 3)
t.Assert(v.Set.Contains("1"), true)

View File

@ -7,6 +7,7 @@
package gtree
import (
"bytes"
"fmt"
"github.com/gogf/gf/v2/container/gvar"
@ -780,8 +781,26 @@ func output(node *AVLTreeNode, prefix string, isTail bool, str *string) {
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (tree AVLTree) MarshalJSON() ([]byte, error) {
return json.Marshal(tree.MapStrAny())
func (tree AVLTree) MarshalJSON() (jsonBytes []byte, err error) {
if tree.root == nil {
return []byte("null"), nil
}
buffer := bytes.NewBuffer(nil)
buffer.WriteByte('{')
tree.Iterator(func(key, value interface{}) bool {
valueBytes, valueJsonErr := json.Marshal(value)
if valueJsonErr != nil {
err = valueJsonErr
return false
}
if buffer.Len() > 1 {
buffer.WriteByte(',')
}
buffer.WriteString(fmt.Sprintf(`"%v":%s`, key, valueBytes))
return true
})
buffer.WriteByte('}')
return buffer.Bytes(), nil
}
// getComparator returns the comparator if it's previously set,

View File

@ -944,8 +944,26 @@ func (tree *BTree) deleteChild(node *BTreeNode, index int) {
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (tree BTree) MarshalJSON() ([]byte, error) {
return json.Marshal(tree.MapStrAny())
func (tree BTree) MarshalJSON() (jsonBytes []byte, err error) {
if tree.root == nil {
return []byte("null"), nil
}
buffer := bytes.NewBuffer(nil)
buffer.WriteByte('{')
tree.Iterator(func(key, value interface{}) bool {
valueBytes, valueJsonErr := json.Marshal(value)
if valueJsonErr != nil {
err = valueJsonErr
return false
}
if buffer.Len() > 1 {
buffer.WriteByte(',')
}
buffer.WriteString(fmt.Sprintf(`"%v":%s`, key, valueBytes))
return true
})
buffer.WriteByte('}')
return buffer.Bytes(), nil
}
// getComparator returns the comparator if it's previously set,

View File

@ -7,6 +7,7 @@
package gtree
import (
"bytes"
"fmt"
"github.com/gogf/gf/v2/container/gvar"
@ -925,8 +926,26 @@ func (tree *RedBlackTree) nodeColor(node *RedBlackTreeNode) color {
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (tree RedBlackTree) MarshalJSON() ([]byte, error) {
return json.Marshal(gconv.Map(tree.Map()))
func (tree RedBlackTree) MarshalJSON() (jsonBytes []byte, err error) {
if tree.root == nil {
return []byte("null"), nil
}
buffer := bytes.NewBuffer(nil)
buffer.WriteByte('{')
tree.Iterator(func(key, value interface{}) bool {
valueBytes, valueJsonErr := json.Marshal(value)
if valueJsonErr != nil {
err = valueJsonErr
return false
}
if buffer.Len() > 1 {
buffer.WriteByte(',')
}
buffer.WriteString(fmt.Sprintf(`"%v":%s`, key, valueBytes))
return true
})
buffer.WriteByte('}')
return buffer.Bytes(), nil
}
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

View File

@ -56,16 +56,16 @@ func Test_Bool_JSON(t *testing.T) {
var err error
i := gtype.NewBool()
err = json.UnmarshalUseNumber([]byte("true"), &i)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i.Val(), true)
err = json.UnmarshalUseNumber([]byte("false"), &i)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i.Val(), false)
err = json.UnmarshalUseNumber([]byte("1"), &i)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i.Val(), true)
err = json.UnmarshalUseNumber([]byte("0"), &i)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i.Val(), false)
})
@ -79,7 +79,7 @@ func Test_Bool_JSON(t *testing.T) {
i2 := gtype.NewBool()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i.Val())
})
gtest.C(t, func(t *gtest.T) {
@ -92,7 +92,7 @@ func Test_Bool_JSON(t *testing.T) {
i2 := gtype.NewBool()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i.Val())
})
}
@ -108,7 +108,7 @@ func Test_Bool_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "true",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), true)
})
@ -118,7 +118,7 @@ func Test_Bool_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "false",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), false)
})

View File

@ -54,7 +54,7 @@ func Test_Byte_JSON(t *testing.T) {
var err error
i := gtype.NewByte()
err = json.UnmarshalUseNumber([]byte("49"), &i)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i.Val(), "49")
})
}
@ -70,7 +70,7 @@ func Test_Byte_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "2",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "2")
})

View File

@ -40,7 +40,7 @@ func Test_Bytes_JSON(t *testing.T) {
i2 := gtype.NewBytes()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), b)
})
}
@ -56,7 +56,7 @@ func Test_Bytes_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -42,7 +42,7 @@ func Test_Float32_JSON(t *testing.T) {
i2 := gtype.NewFloat32()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), v)
})
}
@ -58,7 +58,7 @@ func Test_Float32_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123.456",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123.456")
})

View File

@ -40,7 +40,7 @@ func Test_Float64_JSON(t *testing.T) {
i2 := gtype.NewFloat64()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), v)
})
}
@ -56,7 +56,7 @@ func Test_Float64_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123.456",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123.456")
})

View File

@ -53,7 +53,7 @@ func Test_Int32_JSON(t *testing.T) {
i2 := gtype.NewInt32()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), v)
})
}
@ -69,7 +69,7 @@ func Test_Int32_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -52,7 +52,7 @@ func Test_Int64_JSON(t *testing.T) {
i2 := gtype.NewInt64()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i)
})
}
@ -68,7 +68,7 @@ func Test_Int64_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -52,7 +52,7 @@ func Test_Int_JSON(t *testing.T) {
i2 := gtype.NewInt()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), v)
})
}
@ -68,7 +68,7 @@ func Test_Int_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -42,7 +42,7 @@ func Test_Interface_JSON(t *testing.T) {
i2 := gtype.New()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), s)
})
}
@ -58,7 +58,7 @@ func Test_Interface_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -40,7 +40,7 @@ func Test_String_JSON(t *testing.T) {
i2 := gtype.NewString()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), s)
})
}
@ -56,7 +56,7 @@ func Test_String_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -52,7 +52,7 @@ func Test_Uint32_JSON(t *testing.T) {
i2 := gtype.NewUint32()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i)
})
}
@ -68,7 +68,7 @@ func Test_Uint32_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -56,7 +56,7 @@ func Test_Uint64_JSON(t *testing.T) {
i2 := gtype.NewUint64()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i)
})
}
@ -72,7 +72,7 @@ func Test_Uint64_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -51,7 +51,7 @@ func Test_Uint_JSON(t *testing.T) {
i2 := gtype.NewUint()
err := json.UnmarshalUseNumber(b2, &i2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(i2.Val(), i)
})
}
@ -67,7 +67,7 @@ func Test_Uint_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "123",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.Val(), "123")
})

View File

@ -18,10 +18,10 @@ import (
// New
func ExampleVarNew() {
v := gvar.New(400)
g.Dump(v)
fmt.Println(v)
// Output:
// "400"
// 400
}
// Clone

View File

@ -253,7 +253,7 @@ func Test_UnmarshalJson(t *testing.T) {
"name": "john",
"var": "v",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.String(), "v")
})
@ -267,7 +267,7 @@ func Test_UnmarshalJson(t *testing.T) {
"name": "john",
"var": "v",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.String(), "v")
})
@ -284,7 +284,7 @@ func Test_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "v",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.String(), "v")
})
@ -298,7 +298,7 @@ func Test_UnmarshalValue(t *testing.T) {
"name": "john",
"var": "v",
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Var.String(), "v")
})

View File

@ -40,10 +40,10 @@ func TestVar_Json(t *testing.T) {
s := "i love gf"
v := gvar.New(nil)
b, err := json.Marshal(s)
t.Assert(err, nil)
t.AssertNil(err)
err = json.UnmarshalUseNumber(b, v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.String(), s)
})
@ -51,10 +51,10 @@ func TestVar_Json(t *testing.T) {
var v gvar.Var
s := "i love gf"
b, err := json.Marshal(s)
t.Assert(err, nil)
t.AssertNil(err)
err = json.UnmarshalUseNumber(b, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.String(), s)
})
}

View File

@ -55,7 +55,7 @@ func TestVar_Var_Attribute_Struct(t *testing.T) {
"uid": gvar.New(1),
"name": gvar.New("john"),
}, user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Uid, 1)
t.Assert(user.Name, "john")
})
@ -70,7 +70,7 @@ func TestVar_Var_Attribute_Struct(t *testing.T) {
"uid": gvar.New(1),
"name": gvar.New("john"),
}, &user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user.Uid, 1)
t.Assert(user.Name, "john")
})

View File

@ -41,19 +41,19 @@ var (
func TestEncrypt(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
data, err := gaes.Encrypt(content, key_16)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(data, []byte(content_16))
data, err = gaes.Encrypt(content, key_24)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(data, []byte(content_24))
data, err = gaes.Encrypt(content, key_32)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(data, []byte(content_32))
data, err = gaes.Encrypt(content, key_16, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(data, []byte(content_16_iv))
data, err = gaes.Encrypt(content, key_32, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(data, []byte(content_32_iv))
})
}
@ -61,23 +61,23 @@ func TestEncrypt(t *testing.T) {
func TestDecrypt(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
decrypt, err := gaes.Decrypt([]byte(content_16), key_16)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
decrypt, err = gaes.Decrypt([]byte(content_24), key_24)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
decrypt, err = gaes.Decrypt([]byte(content_32), key_32)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
decrypt, err = gaes.Decrypt([]byte(content_16_iv), key_16, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
decrypt, err = gaes.Decrypt([]byte(content_32_iv), key_32, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
decrypt, err = gaes.Decrypt([]byte(content_32_iv), keys, iv)
@ -134,7 +134,7 @@ func TestEncryptCFB(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var padding int = 0
data, err := gaes.EncryptCFB(content, key_16, &padding, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(padding, padding_size)
t.Assert(data, []byte(content_16_cfb))
})
@ -143,7 +143,7 @@ func TestEncryptCFB(t *testing.T) {
func TestDecryptCFB(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
decrypt, err := gaes.DecryptCFB([]byte(content_16_cfb), key_16, padding_size, iv)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(decrypt, content)
})
}

View File

@ -65,7 +65,7 @@ func TestEncryptFile(t *testing.T) {
file, err := os.Create(path)
defer os.Remove(path)
defer file.Close()
t.Assert(err, nil)
t.AssertNil(err)
_, _ = file.Write([]byte("Hello Go Frame"))
encryptFile, _ := gmd5.EncryptFile(path)
t.AssertEQ(encryptFile, result)

View File

@ -48,7 +48,7 @@ func TestEncryptFile(t *testing.T) {
file, err := os.Create(path)
defer os.Remove(path)
defer file.Close()
t.Assert(err, nil)
t.AssertNil(err)
_, _ = file.Write([]byte("Hello Go Frame"))
encryptFile, _ := gsha1.EncryptFile(path)
t.AssertEQ(encryptFile, result)

View File

@ -409,7 +409,8 @@ func doNewByNode(node ConfigNode, group string) (db DB, err error) {
return c.db, nil
}
errorMsg := `cannot find database driver for specified database type "%s"`
errorMsg += `, did you misspell type name "%s" or forget importing the database driver?`
errorMsg += `, did you misspell type name "%s" or forget importing the database driver? `
errorMsg += `possible reference: https://github.com/gogf/gf/tree/master/contrib/drivers`
return nil, gerror.NewCodef(gcode.CodeInvalidConfiguration, errorMsg, node.Type, node.Type)
}

View File

@ -18,6 +18,7 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
@ -201,7 +202,7 @@ func (c *Core) GetStructs(ctx context.Context, pointer interface{}, sql string,
// the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally
// for conversion.
func (c *Core) GetScan(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error {
reflectInfo := utils.OriginTypeAndKind(pointer)
reflectInfo := reflection.OriginTypeAndKind(pointer)
if reflectInfo.InputKind != reflect.Ptr {
return gerror.NewCodef(
gcode.CodeInvalidParameter,

View File

@ -14,7 +14,7 @@ import (
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/util/gconv"
)
@ -341,7 +341,7 @@ func (tx *TX) GetStructs(objPointerSlice interface{}, sql string, args ...interf
// the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally
// for conversion.
func (tx *TX) GetScan(pointer interface{}, sql string, args ...interface{}) error {
reflectInfo := utils.OriginTypeAndKind(pointer)
reflectInfo := reflection.OriginTypeAndKind(pointer)
if reflectInfo.InputKind != reflect.Ptr {
return gerror.NewCodef(
gcode.CodeInvalidParameter,

View File

@ -15,6 +15,7 @@ import (
"time"
"github.com/gogf/gf/v2/internal/empty"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/os/gstructs"
"github.com/gogf/gf/v2/os/gtime"
@ -366,7 +367,7 @@ func isKeyValueCanBeOmitEmpty(omitEmpty bool, whereType string, key, value inter
func formatWhereHolder(db DB, in formatWhereHolderInput) (newWhere string, newArgs []interface{}) {
var (
buffer = bytes.NewBuffer(nil)
reflectInfo = utils.OriginValueAndKind(in.Where)
reflectInfo = reflection.OriginValueAndKind(in.Where)
)
switch reflectInfo.OriginKind {
case reflect.Array, reflect.Slice:
@ -707,7 +708,7 @@ func handleArguments(sql string, args []interface{}) (newSql string, newArgs []i
// Handles the slice arguments.
if len(args) > 0 {
for index, arg := range args {
reflectInfo := utils.OriginValueAndKind(arg)
reflectInfo := reflection.OriginValueAndKind(arg)
switch reflectInfo.OriginKind {
case reflect.Slice, reflect.Array:
// It does not split the type of []byte.
@ -817,7 +818,7 @@ func FormatSqlWithArgs(sql string, args []interface{}) string {
if v, ok := args[index].(Raw); ok {
return gconv.String(v)
}
reflectInfo := utils.OriginValueAndKind(args[index])
reflectInfo := reflection.OriginValueAndKind(args[index])
if reflectInfo.OriginKind == reflect.Ptr &&
(reflectInfo.OriginValue.IsNil() || !reflectInfo.OriginValue.IsValid()) {
return "null"

View File

@ -13,7 +13,7 @@ import (
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
@ -69,7 +69,7 @@ func (m *Model) Data(data ...interface{}) *Model {
model.data = gutil.MapCopy(value)
default:
reflectInfo := utils.OriginValueAndKind(value)
reflectInfo := reflection.OriginValueAndKind(value)
switch reflectInfo.OriginKind {
case reflect.Slice, reflect.Array:
if reflectInfo.OriginValue.Len() > 0 {
@ -253,7 +253,7 @@ func (m *Model) doInsertWithOption(insertOption int) (result sql.Result, err err
list = List{m.db.ConvertDataForRecord(m.GetCtx(), value)}
default:
reflectInfo := utils.OriginValueAndKind(newData)
reflectInfo := reflection.OriginValueAndKind(newData)
switch reflectInfo.OriginKind {
// If it's slice type, it then converts it to List type.
case reflect.Slice, reflect.Array:
@ -330,7 +330,7 @@ func (m *Model) formatDoInsertOption(insertOption int, columnNames []string) (op
option.OnDuplicateStr = gconv.String(m.onDuplicate)
default:
reflectInfo := utils.OriginValueAndKind(m.onDuplicate)
reflectInfo := reflection.OriginValueAndKind(m.onDuplicate)
switch reflectInfo.OriginKind {
case reflect.String:
option.OnDuplicateMap = make(map[string]interface{})
@ -385,7 +385,7 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er
return nil, nil
}
reflectInfo := utils.OriginValueAndKind(onDuplicateEx)
reflectInfo := reflection.OriginValueAndKind(onDuplicateEx)
switch reflectInfo.OriginKind {
case reflect.String:
return gstr.SplitAndTrim(reflectInfo.OriginValue.String(), ","), nil

View File

@ -6,15 +6,22 @@
package gdb
import "strings"
import (
"strings"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
// Order sets the "ORDER BY" statement for the model.
//
// Eg:
// Order("id desc")
// Order("id", "desc")
// Order("id desc,name asc").
func (m *Model) Order(orderBy ...string) *Model {
// Order("id", "desc").
// Order("id desc,name asc")
// Order("id desc").Order("name asc")
// Order(gdb.Raw("field(id, 3,1,2)")).
func (m *Model) Order(orderBy ...interface{}) *Model {
if len(orderBy) == 0 {
return m
}
@ -22,7 +29,14 @@ func (m *Model) Order(orderBy ...string) *Model {
if model.orderBy != "" {
model.orderBy += ","
}
model.orderBy = model.db.GetCore().QuoteString(strings.Join(orderBy, " "))
for _, v := range orderBy {
switch v.(type) {
case Raw, *Raw:
model.orderBy += gconv.String(v)
return model
}
}
model.orderBy += model.db.GetCore().QuoteString(gstr.JoinAny(orderBy, " "))
return model
}

View File

@ -17,7 +17,7 @@ import (
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
@ -294,7 +294,7 @@ func (m *Model) doStructs(pointer interface{}, where ...interface{}) error {
// users := ([]*User)(nil)
// err := db.Model("user").Scan(&users).
func (m *Model) Scan(pointer interface{}, where ...interface{}) error {
reflectInfo := utils.OriginTypeAndKind(pointer)
reflectInfo := reflection.OriginTypeAndKind(pointer)
if reflectInfo.InputKind != reflect.Ptr {
return gerror.NewCode(
gcode.CodeInvalidParameter,

View File

@ -13,7 +13,7 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
@ -49,7 +49,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro
)
// Automatically update the record updating time.
if !m.unscoped && fieldNameUpdate != "" {
reflectInfo := utils.OriginTypeAndKind(m.data)
reflectInfo := reflection.OriginTypeAndKind(m.data)
switch reflectInfo.OriginKind {
case reflect.Map, reflect.Struct:
dataMap := m.db.ConvertDataForRecord(m.GetCtx(), m.data)

View File

@ -353,20 +353,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
@ -553,20 +553,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
gtest.C(t, func(t *gtest.T) {
@ -668,20 +668,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
gtest.C(t, func(t *gtest.T) {
@ -809,20 +809,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
@ -945,20 +945,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
gtest.C(t, func(t *gtest.T) {
@ -1065,20 +1065,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
db.SetDebug(true)
@ -1184,20 +1184,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
gtest.C(t, func(t *gtest.T) {
@ -1299,20 +1299,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
@ -1439,20 +1439,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}
@ -1585,20 +1585,20 @@ PRIMARY KEY (id)
"id": i,
"name": fmt.Sprintf(`name_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Detail.
_, err = db.Insert(ctx, tableUserDetail, g.Map{
"uid": i,
"address": fmt.Sprintf(`address_%d`, i),
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
// Scores.
for j := 1; j <= 5; j++ {
_, err = db.Insert(ctx, tableUserScores, g.Map{
"uid": i,
"score": j,
})
gtest.Assert(err, nil)
gtest.AssertNil(err)
}
}

View File

@ -438,14 +438,14 @@ func Test_Model_Clone(t *testing.T) {
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
md := db.Model(table).Where("id IN(?)", g.Slice{1, 3})
md := db.Model(table).Safe(true).Where("id IN(?)", g.Slice{1, 3})
count, err := md.Count()
t.AssertNil(err)
record, err := md.Order("id DESC").One()
record, err := md.Safe(true).Order("id DESC").One()
t.AssertNil(err)
result, err := md.Order("id ASC").All()
result, err := md.Safe(true).Order("id ASC").All()
t.AssertNil(err)
t.Assert(count, 2)
@ -1114,6 +1114,15 @@ func Test_Model_OrderBy(t *testing.T) {
t.Assert(len(result), TableSize)
t.Assert(result[0]["nickname"].String(), "name_1")
})
gtest.C(t, func(t *gtest.T) {
result, err := db.Model(table).Order(gdb.Raw("field(id, 10,1,2,3,4,5,6,7,8,9)")).All()
t.AssertNil(err)
t.Assert(len(result), TableSize)
t.Assert(result[0]["nickname"].String(), "name_10")
t.Assert(result[1]["nickname"].String(), "name_1")
t.Assert(result[2]["nickname"].String(), "name_2")
})
}
func Test_Model_GroupBy(t *testing.T) {
@ -2058,7 +2067,7 @@ func Test_Model_OmitEmpty(t *testing.T) {
"id": 1,
"name": "",
}).Save()
t.Assert(err, nil)
t.AssertNil(err)
})
}
@ -2087,14 +2096,14 @@ func Test_Model_OmitNil(t *testing.T) {
"id": 1,
"name": "",
}).Save()
t.Assert(err, nil)
t.AssertNil(err)
})
gtest.C(t, func(t *gtest.T) {
_, err := db.Model(table).OmitNilWhere().Data(g.Map{
"id": 1,
"name": "",
}).Save()
t.Assert(err, nil)
t.AssertNil(err)
})
}

View File

@ -13,7 +13,7 @@ import (
"github.com/gogf/gf/v2"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/os/gtime"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
@ -33,7 +33,7 @@ func (c *RedisConn) Do(ctx context.Context, command string, args ...interface{})
}
for k, v := range args {
var (
reflectInfo = utils.OriginTypeAndKind(v)
reflectInfo = reflection.OriginTypeAndKind(v)
)
switch reflectInfo.OriginKind {
case

View File

@ -30,11 +30,11 @@ func TestConn_DoWithTimeout(t *testing.T) {
defer conn.Close(ctx)
_, err = conn.Do(ctx, "set", "test", "123")
t.Assert(err, nil)
t.AssertNil(err)
defer conn.Do(ctx, "del", "test")
r, err := conn.Do(ctx, "get", "test")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.String(), "123")
})
}

View File

@ -46,16 +46,16 @@ func Test_Do(t *testing.T) {
defer redis.Close(ctx)
_, err = redis.Do(ctx, "SET", "k", "v")
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, []byte("v"))
_, err = redis.Do(ctx, "DEL", "k")
t.Assert(err, nil)
t.AssertNil(err)
r, err = redis.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, nil)
})
}
@ -74,16 +74,16 @@ func Test_Conn(t *testing.T) {
key := gconv.String(gtime.TimestampNano())
value := []byte("v")
r, err := conn.Do(ctx, "SET", key, value)
t.Assert(err, nil)
t.AssertNil(err)
r, err = conn.Do(ctx, "GET", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, value)
_, err = conn.Do(ctx, "DEL", key)
t.Assert(err, nil)
t.AssertNil(err)
r, err = conn.Do(ctx, "GET", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, nil)
})
}
@ -102,16 +102,16 @@ func Test_Instance(t *testing.T) {
defer conn.Close(ctx)
_, err = conn.Do(ctx, "SET", "k", "v")
t.Assert(err, nil)
t.AssertNil(err)
r, err := conn.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, []byte("v"))
_, err = conn.Do(ctx, "DEL", "k")
t.Assert(err, nil)
t.AssertNil(err)
r, err = conn.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, nil)
})
}
@ -153,10 +153,10 @@ func Test_Error(t *testing.T) {
defer redis.Close(ctx)
_, err = redis.Do(ctx, "SET", "k", "v")
t.Assert(err, nil)
t.AssertNil(err)
v, err := redis.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.String(), "v")
conn, err := redis.Conn(ctx)
@ -197,17 +197,17 @@ func Test_Bool(t *testing.T) {
}()
_, err = redis.Do(ctx, "SET", "key-true", true)
t.Assert(err, nil)
t.AssertNil(err)
_, err = redis.Do(ctx, "SET", "key-false", false)
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "GET", "key-true")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Bool(), true)
r, err = redis.Do(ctx, "GET", "key-false")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Bool(), false)
})
}
@ -223,10 +223,10 @@ func Test_Int(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "SET", key, 1)
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "GET", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Int(), 1)
})
}
@ -242,10 +242,10 @@ func Test_HSet(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "HSET", key, "name", "john")
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "HGETALL", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Strings(), g.ArrayStr{"name", "john"})
})
}
@ -262,12 +262,12 @@ func Test_HGetAll1(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "HSET", key, "id", 100)
t.Assert(err, nil)
t.AssertNil(err)
_, err = redis.Do(ctx, "HSET", key, "name", "john")
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "HGETALL", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Map(), g.MapStrAny{
"id": 100,
"name": "john",
@ -287,12 +287,12 @@ func Test_HGetAll2(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "HSET", key, "id", 100)
t.Assert(err, nil)
t.AssertNil(err)
_, err = redis.Do(ctx, "HSET", key, "name", "john")
t.Assert(err, nil)
t.AssertNil(err)
result, err := redis.Do(ctx, "HGETALL", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gconv.Uint(result.MapStrVar()["id"]), 100)
t.Assert(result.MapStrVar()["id"].Uint(), 100)
@ -317,9 +317,9 @@ func Test_HMSet(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "HMSET", append(g.Slice{key}, gutil.MapToSlice(data)...)...)
t.Assert(err, nil)
t.AssertNil(err)
v, err := redis.Do(ctx, "HMGET", key, "name")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Slice(), g.Slice{data["name"]})
})
// struct
@ -344,9 +344,9 @@ func Test_HMSet(t *testing.T) {
defer redis.Do(ctx, "DEL", key)
_, err = redis.Do(ctx, "HMSET", append(g.Slice{key}, gutil.StructToSlice(data)...)...)
t.Assert(err, nil)
t.AssertNil(err)
v, err := redis.Do(ctx, "HMGET", key, "name")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Slice(), g.Slice{data.Name})
})
}
@ -374,10 +374,10 @@ func Test_Auto_Marshal(t *testing.T) {
}
_, err = redis.Do(ctx, "SET", key, user)
t.Assert(err, nil)
t.AssertNil(err)
r, err := redis.Do(ctx, "GET", key)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r.Map(), g.MapStrAny{
"Id": user.Id,
"Name": user.Name,
@ -418,14 +418,14 @@ func Test_Auto_MarshalSlice(t *testing.T) {
)
_, err = redis.Do(ctx, "SET", key, users1)
t.Assert(err, nil)
t.AssertNil(err)
result, err = redis.Do(ctx, "GET", key)
t.Assert(err, nil)
t.AssertNil(err)
var users2 []User
err = result.Structs(&users2)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(users2, users1)
})
}

View File

@ -70,12 +70,12 @@ func Test_File(t *testing.T) {
expect := "dGVzdA=="
gtest.C(t, func(t *gtest.T) {
b, err := gbase64.EncodeFile(path)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(b), expect)
})
gtest.C(t, func(t *gtest.T) {
s, err := gbase64.EncodeFileToString(path)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(s, expect)
})
}

View File

@ -50,13 +50,13 @@ func Test_Gzip_UnGzip_File(t *testing.T) {
// Compress.
gtest.C(t, func(t *gtest.T) {
err := gcompress.GzipFile(srcPath, dstPath1, 9)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dstPath1)
t.Assert(gfile.Exists(dstPath1), true)
// Decompress.
err = gcompress.UnGzipFile(dstPath1, dstPath2)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dstPath2)
t.Assert(gfile.Exists(dstPath2), true)

View File

@ -52,7 +52,7 @@ func Test_ZipPath(t *testing.T) {
t.Assert(gfile.Exists(dstPath), false)
err := gcompress.ZipPath(srcPath1+","+srcPath2, dstPath)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), true)
defer gfile.Remove(dstPath)
@ -60,7 +60,7 @@ func Test_ZipPath(t *testing.T) {
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
t.Assert(gfile.Mkdir(tempDirPath), nil)
err = gcompress.UnZipFile(dstPath, tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tempDirPath)
t.Assert(
@ -85,7 +85,7 @@ func Test_ZipPath(t *testing.T) {
t.Assert(gfile.Exists(dstPath), false)
err := gcompress.ZipPath(srcPath1+","+srcPath2, dstPath)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), true)
defer gfile.Remove(dstPath)
@ -93,7 +93,7 @@ func Test_ZipPath(t *testing.T) {
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
t.Assert(gfile.Mkdir(tempDirPath), nil)
err = gcompress.UnZipFile(dstPath, tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tempDirPath)
t.Assert(
@ -113,20 +113,20 @@ func Test_ZipPath(t *testing.T) {
pwd := gfile.Pwd()
err := gfile.Chdir(srcPath)
defer gfile.Chdir(pwd)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), false)
err = gcompress.ZipPath(srcPath, dstPath)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), true)
defer gfile.Remove(dstPath)
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
err = gcompress.UnZipFile(dstPath, tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tempDirPath)
t.Assert(
@ -149,22 +149,22 @@ func Test_ZipPath(t *testing.T) {
pwd := gfile.Pwd()
err := gfile.Chdir(srcPath)
defer gfile.Chdir(pwd)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), false)
err = gcompress.ZipPath(srcPath1+", "+srcPath2, dstPath)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gfile.Exists(dstPath), true)
defer gfile.Remove(dstPath)
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
zipContent := gfile.GetBytes(dstPath)
t.AssertGT(len(zipContent), 0)
err = gcompress.UnZipContent(zipContent, tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tempDirPath)
t.Assert(
@ -188,22 +188,22 @@ func Test_ZipPathWriter(t *testing.T) {
pwd := gfile.Pwd()
err := gfile.Chdir(srcPath)
defer gfile.Chdir(pwd)
t.Assert(err, nil)
t.AssertNil(err)
writer := bytes.NewBuffer(nil)
t.Assert(writer.Len(), 0)
err = gcompress.ZipPathWriter(srcPath1+", "+srcPath2, writer)
t.Assert(err, nil)
t.AssertNil(err)
t.AssertGT(writer.Len(), 0)
tempDirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
zipContent := writer.Bytes()
t.AssertGT(len(zipContent), 0)
err = gcompress.UnZipContent(zipContent, tempDirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tempDirPath)
t.Assert(

View File

@ -47,7 +47,7 @@ func Test_SpecialCharsMapOrStruct_Map(t *testing.T) {
"Content": "<div>C</div>",
}
err := ghtml.SpecialCharsMapOrStruct(a)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a["Title"], `&lt;h1&gt;T&lt;/h1&gt;`)
t.Assert(a["Content"], `&lt;div&gt;C&lt;/div&gt;`)
})
@ -57,7 +57,7 @@ func Test_SpecialCharsMapOrStruct_Map(t *testing.T) {
"Content": "<div>C</div>",
}
err := ghtml.SpecialCharsMapOrStruct(a)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a["Title"], `&lt;h1&gt;T&lt;/h1&gt;`)
t.Assert(a["Content"], `&lt;div&gt;C&lt;/div&gt;`)
})
@ -74,7 +74,7 @@ func Test_SpecialCharsMapOrStruct_Struct(t *testing.T) {
Content: "<div>C</div>",
}
err := ghtml.SpecialCharsMapOrStruct(a)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(a.Title, `&lt;h1&gt;T&lt;/h1&gt;`)
t.Assert(a.Content, `&lt;div&gt;C&lt;/div&gt;`)
})

View File

@ -97,7 +97,7 @@ func TestToJson(t *testing.T) {
}
iniMap, err := gini.Decode([]byte(iniContent))
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(iniMap["addr"].(map[string]interface{})["ip"], json.Get("addr.ip").String())
t.Assert(iniMap["addr"].(map[string]interface{})["port"], json.Get("addr.port").String())

View File

@ -14,6 +14,7 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/internal/rwmutex"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/text/gstr"
@ -90,6 +91,9 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error {
// Delete item from map.
delete((*pointer).(map[string]interface{}), array[i])
} else {
if (*pointer).(map[string]interface{}) == nil {
*pointer = map[string]interface{}{}
}
(*pointer).(map[string]interface{})[array[i]] = value
}
} else {
@ -279,7 +283,7 @@ func (j *Json) convertValue(value interface{}) (convertedValue interface{}, err
default:
var (
reflectInfo = utils.OriginValueAndKind(value)
reflectInfo = reflection.OriginValueAndKind(value)
)
switch reflectInfo.OriginKind {
case reflect.Array:

View File

@ -60,12 +60,7 @@ func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var {
return nil
}
var result *interface{}
if j.vc {
result = j.getPointerByPattern(pattern)
} else {
result = j.getPointerByPatternWithoutViolenceCheck(pattern)
}
result := j.getPointerByPattern(pattern)
if result != nil {
return gvar.New(*result)
}

View File

@ -17,8 +17,8 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/internal/rwmutex"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/util/gconv"
@ -67,38 +67,30 @@ func NewWithOptions(data interface{}, options Options) *Json {
}
}
default:
var reflectInfo = utils.OriginValueAndKind(data)
var (
pointedData interface{}
reflectInfo = reflection.OriginValueAndKind(data)
)
switch reflectInfo.OriginKind {
case reflect.Slice, reflect.Array:
var i interface{} = gconv.Interfaces(data)
j = &Json{
p: &i,
c: byte(defaultSplitChar),
vc: false,
}
pointedData = gconv.Interfaces(data)
case reflect.Map:
var i interface{} = gconv.MapDeep(data, options.Tags)
j = &Json{
p: &i,
c: byte(defaultSplitChar),
vc: false,
}
pointedData = gconv.MapDeep(data, options.Tags)
case reflect.Struct:
if v, ok := data.(iVal); ok {
return NewWithOptions(v.Val(), options)
}
var i interface{} = gconv.MapDeep(data, options.Tags)
j = &Json{
p: &i,
c: byte(defaultSplitChar),
vc: false,
}
pointedData = gconv.MapDeep(data, options.Tags)
default:
j = &Json{
p: &data,
c: byte(defaultSplitChar),
vc: false,
}
pointedData = data
}
j = &Json{
p: &pointedData,
c: byte(defaultSplitChar),
vc: false,
}
}
j.mu = rwmutex.New(options.Safe)

View File

@ -270,6 +270,6 @@ func ExampleDecodeToJson() {
j, _ := gjson.DecodeToJson([]byte(jsonContent))
fmt.Println(j.Map())
// Output:
// May Output:
// map[name:john score:100]
}

View File

@ -19,6 +19,10 @@ func ExampleLoad() {
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
notExistFilePath := gdebug.TestDataPath("json", "data2.json")
j2, _ := gjson.Load(notExistFilePath)
fmt.Println(j2.Get("name"))
// Output:
// john
// 100
@ -97,25 +101,51 @@ func ExampleLoadToml() {
func ExampleLoadContent() {
jsonContent := `{"name":"john", "score":"100"}`
j, _ := gjson.LoadContent(jsonContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
func ExampleLoadContent_UTF8BOM() {
jsonContent := `{"name":"john", "score":"100"}`
content := make([]byte, 3, len(jsonContent)+3)
content[0] = 0xEF
content[1] = 0xBB
content[2] = 0xBF
content = append(content, jsonContent...)
j, _ := gjson.LoadContent(content)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
func ExampleLoadContent_Xml() {
xmlContent := `<?xml version="1.0" encoding="UTF-8"?>
<base>
<name>john</name>
<score>100</score>
</base>`
j, _ := gjson.LoadContent(jsonContent)
x, _ := gjson.LoadContent(xmlContent)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(x.Get("base.name"))
fmt.Println(x.Get("base.score"))
// Output:
// john
// 100
// john
// 100
}
func ExampleLoadContentType() {
@ -128,11 +158,13 @@ func ExampleLoadContentType() {
j, _ := gjson.LoadContentType("json", jsonContent)
x, _ := gjson.LoadContentType("xml", xmlContent)
j1, _ := gjson.LoadContentType("json", "")
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(x.Get("base.name"))
fmt.Println(x.Get("base.score"))
fmt.Println(j1.Get(""))
// Output:
// john
@ -148,6 +180,8 @@ func ExampleIsValidDataType() {
fmt.Println(gjson.IsValidDataType("mp4"))
fmt.Println(gjson.IsValidDataType("xsl"))
fmt.Println(gjson.IsValidDataType("txt"))
fmt.Println(gjson.IsValidDataType(""))
fmt.Println(gjson.IsValidDataType(".json"))
// Output:
// true
@ -156,6 +190,8 @@ func ExampleIsValidDataType() {
// false
// false
// false
// false
// true
}
func ExampleLoad_Xml() {

View File

@ -34,7 +34,7 @@ func ExampleNewWithTag() {
Score: 100,
Title: "engineer",
}
j := gjson.NewWithTag(me, "tag")
j := gjson.NewWithTag(me, "tag", true)
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
fmt.Println(j.Get("Title"))
@ -70,6 +70,26 @@ func ExampleNewWithOptions() {
// engineer
}
func ExampleNewWithOptions_UTF8BOM() {
jsonContent := `{"name":"john", "score":"100"}`
content := make([]byte, 3, len(jsonContent)+3)
content[0] = 0xEF
content[1] = 0xBB
content[2] = 0xBF
content = append(content, jsonContent...)
j := gjson.NewWithOptions(content, gjson.Options{
Tags: "tag",
})
fmt.Println(j.Get("name"))
fmt.Println(j.Get("score"))
// Output:
// john
// 100
}
func ExampleNew_Xml() {
jsonContent := `<?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>`
j := gjson.New(jsonContent)

View File

@ -590,61 +590,52 @@ func ExampleJson_ToIni() {
func ExampleJson_ToIniString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
IniStr, _ := j.ToIniString()
fmt.Println(string(IniStr))
// May Output:
// Output:
//Name=John
//Age=18
}
func ExampleJson_MustToIni() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
IniBytes := j.MustToIni()
fmt.Println(string(IniBytes))
// May Output:
// Output:
//Name=John
//Age=18
}
func ExampleJson_MustToIniString() {
type BaseInfo struct {
Name string
Age int
}
info := BaseInfo{
Name: "John",
Age: 18,
}
j := gjson.New(info)
IniStr := j.MustToIniString()
fmt.Println(string(IniStr))
// May Output:
// Output:
//Name=John
//Age=18
}
func ExampleJson_MarshalJSON() {
@ -758,8 +749,12 @@ func ExampleJson_Interface() {
j := gjson.New(info)
fmt.Println(j.Interface())
var nilJ *gjson.Json = nil
fmt.Println(nilJ.Interface())
// Output:
// map[Age:18 Name:John]
// <nil>
}
func ExampleJson_Var() {
@ -807,11 +802,16 @@ func ExampleJson_Get() {
}`
j, _ := gjson.LoadContent(data)
fmt.Println(j.Get("."))
fmt.Println(j.Get("users"))
fmt.Println(j.Get("users.count"))
fmt.Println(j.Get("users.array"))
var nilJ *gjson.Json = nil
fmt.Println(nilJ.Get("."))
// Output:
// {"users":{"array":["John","Ming"],"count":1}}
// {"array":["John","Ming"],"count":1}
// 1
// ["John","Ming"]
@ -893,10 +893,11 @@ func ExampleJson_Set() {
j := gjson.New(info)
j.Set("Addr", "ChengDu")
j.Set("Friends.0", "Tom")
fmt.Println(j.Var().String())
// Output:
// {"Addr":"ChengDu","Age":18,"Name":"John"}
// {"Addr":"ChengDu","Age":18,"Friends":["Tom"],"Name":"John"}
}
func ExampleJson_MustSet() {
@ -1091,7 +1092,7 @@ func ExampleJson_Scan() {
fmt.Println(info)
// Output:
// May Output:
// {john 18}
}
@ -1099,12 +1100,11 @@ func ExampleJson_Dump() {
data := `{"name":"john","age":"18"}`
j, _ := gjson.LoadContent(data)
j.Dump()
// May Output:
//{
// "age": "18",
// "name": "john",
// "age": "18",
//}
}

View File

@ -36,7 +36,7 @@ func Test_ToJson(t *testing.T) {
jsonContent := `{"dataSetId":2001,"fieldInfos":{"duration":{"id":80079,"value":"59"},"om_level":{"id":2409,"value":"4"}},"id":"g0936lt1u0f","modifyFieldInfos":{"om_level":{"id":2409,"new":"4","old":""}},"timeStamp":1584599734}`
var info MediaRequestModifyInfo
err := gjson.DecodeTo(jsonContent, &info)
t.Assert(err, nil)
t.AssertNil(err)
content := gjson.New(info).MustToJsonString()
t.Assert(gstr.Contains(content, `"feed_id":""`), true)
t.Assert(gstr.Contains(content, `"fieldInfos":{`), true)
@ -56,29 +56,34 @@ func Test_MapAttributeConvert(t *testing.T) {
`
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
gtest.Assert(err, nil)
gtest.AssertNil(err)
tx := struct {
Title map[string]interface{}
}{}
err = j.Var().Scan(&tx)
gtest.Assert(err, nil)
gtest.AssertNil(err)
t.Assert(tx.Title, g.Map{
"l1": "标签1", "l2": "标签2",
})
j.Dump()
var nilJ *gjson.Json = nil
nilJ.Dump()
})
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
gtest.Assert(err, nil)
gtest.AssertNil(err)
tx := struct {
Title map[string]string
}{}
err = j.Var().Scan(&tx)
gtest.Assert(err, nil)
gtest.AssertNil(err)
t.Assert(tx.Title, g.Map{
"l1": "标签1", "l2": "标签2",
})

View File

@ -20,7 +20,7 @@ func Test_Load_JSON1(t *testing.T) {
// JSON
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -28,12 +28,18 @@ func Test_Load_JSON1(t *testing.T) {
t.Assert(j.Get("a.1").Int(), 2)
})
// JSON
gtest.C(t, func(t *gtest.T) {
errData := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]`)
_, err := gjson.LoadContentType("json", errData, true)
t.AssertNE(err, nil)
})
// JSON
gtest.C(t, func(t *gtest.T) {
path := "test.json"
gfile.PutBytes(path, data)
defer gfile.Remove(path)
j, err := gjson.Load(path)
t.Assert(err, nil)
j, err := gjson.Load(path, true)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -46,7 +52,7 @@ func Test_Load_JSON2(t *testing.T) {
data := []byte(`{"n":123456789000000000000, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789000000000000")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -60,7 +66,7 @@ func Test_Load_XML(t *testing.T) {
// XML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("doc.n").String(), "123456789")
t.Assert(j.Get("doc.m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("doc.m.k").String(), "v")
@ -68,12 +74,28 @@ func Test_Load_XML(t *testing.T) {
t.Assert(j.Get("doc.a.1").Int(), 2)
})
// XML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadXml(data, true)
t.AssertNil(err)
t.Assert(j.Get("doc.n").String(), "123456789")
t.Assert(j.Get("doc.m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("doc.m.k").String(), "v")
t.Assert(j.Get("doc.a").Slice(), g.Slice{"1", "2", "3"})
t.Assert(j.Get("doc.a.1").Int(), 2)
})
// XML
gtest.C(t, func(t *gtest.T) {
errData := []byte(`<doc><a>1</a><a>2</a><a>3</a><m><k>v</k></m><n>123456789</n><doc>`)
_, err := gjson.LoadContentType("xml", errData, true)
t.AssertNE(err, nil)
})
// XML
gtest.C(t, func(t *gtest.T) {
path := "test.xml"
gfile.PutBytes(path, data)
defer gfile.Remove(path)
j, err := gjson.Load(path)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("doc.n").String(), "123456789")
t.Assert(j.Get("doc.m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("doc.m.k").String(), "v")
@ -94,7 +116,7 @@ func Test_Load_XML(t *testing.T) {
<nworkOrderFrontXML/>
</Output>`
j, err := gjson.LoadContent(xml)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Output.ipageIndex"), "2")
t.Assert(j.Get("Output.itotalRecords"), "GF框架")
})
@ -113,7 +135,17 @@ m:
// YAML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
t.Assert(j.Get("a").Slice(), g.Slice{1, 2, 3})
t.Assert(j.Get("a.1").Int(), 2)
})
// YAML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadYaml(data, true)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -126,7 +158,7 @@ m:
gfile.PutBytes(path, data)
defer gfile.Remove(path)
j, err := gjson.Load(path)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -139,9 +171,14 @@ func Test_Load_YAML2(t *testing.T) {
data := []byte("i : 123456789")
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("i"), "123456789")
})
gtest.C(t, func(t *gtest.T) {
errData := []byte("i # 123456789")
_, err := gjson.LoadContentType("yaml", errData, true)
t.AssertNE(err, nil)
})
}
func Test_Load_TOML1(t *testing.T) {
@ -155,7 +192,17 @@ n = 123456789
// TOML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
t.Assert(j.Get("a").Slice(), g.Slice{"1", "2", "3"})
t.Assert(j.Get("a.1").Int(), 2)
})
// TOML
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadToml(data, true)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -168,7 +215,7 @@ n = 123456789
gfile.PutBytes(path, data)
defer gfile.Remove(path)
j, err := gjson.Load(path)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -181,9 +228,14 @@ func Test_Load_TOML2(t *testing.T) {
data := []byte("i=123456789")
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadContent(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("i"), "123456789")
})
gtest.C(t, func(t *gtest.T) {
errData := []byte("i : 123456789")
_, err := gjson.LoadContentType("toml", errData, true)
t.AssertNE(err, nil)
})
}
func Test_Load_Basic(t *testing.T) {
@ -195,11 +247,11 @@ func Test_Load_Basic(t *testing.T) {
_, err = gjson.DecodeToJson(nil)
t.AssertNE(err, nil)
j, err = gjson.LoadContent(nil)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Interface(), nil)
j, err = gjson.LoadContent(`{"name": "gf"}`)
t.Assert(err, nil)
t.AssertNil(err)
j, err = gjson.LoadContent(`{"name": "gf"""}`)
t.AssertNE(err, nil)
@ -245,6 +297,26 @@ enable=true
gtest.Fatal(err)
}
})
gtest.C(t, func(t *gtest.T) {
j, err := gjson.LoadIni(data, true)
if err != nil {
gtest.Fatal(err)
}
t.Assert(j.Get("addr.ip").String(), "127.0.0.1")
t.Assert(j.Get("addr.port").String(), "9001")
t.Assert(j.Get("addr.enable").String(), "true")
t.Assert(j.Get("DBINFO.type").String(), "mysql")
t.Assert(j.Get("DBINFO.user").String(), "root")
t.Assert(j.Get("DBINFO.password").String(), "password")
})
gtest.C(t, func(t *gtest.T) {
errData := []byte("i : 123456789")
_, err := gjson.LoadContentType("ini", errData, true)
t.AssertNE(err, nil)
})
}
func Test_Load_YamlWithV3(t *testing.T) {

View File

@ -65,7 +65,7 @@ func Test_New_CustomStruct(t *testing.T) {
t.AssertNE(j, nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(s == `{"Id":1,"Name":"john"}` || s == `{"Name":"john","Id":1}`, true)
})
}

View File

@ -236,7 +236,7 @@ func Test_Set15(t *testing.T) {
t.Assert(j.Set("k", "v"), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(
gstr.Contains(s, `"root":[{"k1":"v1"},{"k2":"v2"}`) ||
gstr.Contains(s, `"root":[{"k2":"v2"},{"k1":"v1"}`),
@ -259,7 +259,7 @@ func Test_Set16(t *testing.T) {
t.Assert(j.Set("description", "3"), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(
gstr.Contains(s, `"processors":[{"set":{"0field":"2","0value":"1"}}]`) ||
gstr.Contains(s, `"processors":[{"set":{"0value":"1","0field":"2"}}]`),
@ -282,7 +282,7 @@ func Test_Set17(t *testing.T) {
t.Assert(j.Set("k", "v"), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(s, `{"k":"v"}`)
})
}
@ -294,7 +294,7 @@ func Test_Set18(t *testing.T) {
t.Assert(j.Set("0.1.k1", "v1"), nil)
t.Assert(j.Set("0.2.k2", "v2"), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(s, `[[null,{"k1":"v1"},{"k2":"v2"}]]`)
})
}
@ -306,7 +306,7 @@ func Test_Set19(t *testing.T) {
t.Assert(j.Set("0.1.1.k1", "v1"), nil)
t.Assert(j.Set("0.2.1.k2", "v2"), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(s, `[[null,[null,{"k1":"v1"}],[null,{"k2":"v2"}]]]`)
})
}
@ -320,7 +320,7 @@ func Test_Set20(t *testing.T) {
t.Assert(j.Set("k2.1", 20), nil)
t.Assert(j.Set("k2.2", g.Map{"k3": "v3"}), nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(gstr.InArray(
g.SliceStr{
`{"k1":"v1","k2":[1,20,{"k3":"v3"}]}`,
@ -339,3 +339,11 @@ func Test_Set_GArray(t *testing.T) {
t.Assert(j.Get("arr").Array(), g.Slice{"test"})
})
}
func Test_Set_WithEmptyStruct(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
j := gjson.New(&struct{}{})
t.AssertNil(j.Set("aa", "123"))
t.Assert(j.MustToJsonString(), `{"aa":"123"}`)
})
}

View File

@ -22,7 +22,7 @@ func Test_GetScan(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var user *User
err := j.Get("1").Scan(&user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user, &User{
Name: "smith",
Score: 60,
@ -31,7 +31,7 @@ func Test_GetScan(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var users []User
err := j.Get(".").Scan(&users)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(users, []User{
{
Name: "john",
@ -54,7 +54,7 @@ func Test_GetScanDeep(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var user *User
err := j.Get("1").Scan(&user)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(user, &User{
Name: "smith",
Score: 60,
@ -63,7 +63,7 @@ func Test_GetScanDeep(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var users []User
err := j.Get(".").Scan(&users)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(users, []User{
{
Name: "john",
@ -86,7 +86,7 @@ func Test_Scan1(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var users []User
err := j.Var().Scan(&users)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(users, []User{
{
Name: "john",
@ -109,7 +109,7 @@ func Test_Scan2(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var users []User
err := j.Var().Scan(&users)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(users, []User{
{
Name: "john",
@ -197,10 +197,10 @@ func Test_Struct1(t *testing.T) {
}]
}`
data := new(UserCollectionAddReq)
j, err := gjson.LoadJson(jsonContent)
t.Assert(err, nil)
j, err := gjson.LoadJson(jsonContent, true)
t.AssertNil(err)
err = j.Scan(data)
t.Assert(err, nil)
t.AssertNil(err)
})
}
@ -226,14 +226,14 @@ func Test_Struct(t *testing.T) {
}`
j, err := gjson.LoadContent(txt)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("me.name").String(), "mikey")
t.Assert(j.Get("items").String(), "")
t.Assert(j.Get("items").Bool(), false)
t.Assert(j.Get("items").Array(), nil)
m := new(M)
err = j.Scan(m)
t.Assert(err, nil)
t.AssertNil(err)
t.AssertNE(m.Me, nil)
t.Assert(m.Me["day"], "20009")
t.Assert(m.Items, nil)
@ -289,10 +289,10 @@ func Test_Struct_Complicated(t *testing.T) {
]
}`
j, err := gjson.LoadContent(jsonContent)
t.Assert(err, nil)
t.AssertNil(err)
var response = new(Response)
err = j.Scan(response)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(len(response.CertList), 3)
t.Assert(response.CertList[0].CertID, 2023313)
t.Assert(response.CertList[1].CertID, 2023314)

View File

@ -24,7 +24,7 @@ func TestJson_UnmarshalJSON(t *testing.T) {
j = gjson.New(nil)
err = json.UnmarshalUseNumber(data, j)
)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get(".").String(), `["a","b","c"]`)
t.Assert(j.Get("2").String(), `c`)
})
@ -35,7 +35,7 @@ func TestJson_UnmarshalJSON(t *testing.T) {
j = gjson.New(nil)
err = json.UnmarshalUseNumber(data, j)
)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get(".").String(), `[{"a":1},{"b":2},{"c":3}]`)
t.Assert(j.Get("2.c").String(), `3`)
})
@ -46,7 +46,7 @@ func TestJson_UnmarshalJSON(t *testing.T) {
j = gjson.New(nil)
err = json.UnmarshalUseNumber(data, j)
)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k").String(), "v")
@ -68,7 +68,7 @@ func TestJson_UnmarshalValue(t *testing.T) {
"name": "john",
"json": []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`),
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Json.Get("n").String(), "123456789")
t.Assert(v.Json.Get("m").Map(), g.Map{"k": "v"})
@ -83,7 +83,7 @@ func TestJson_UnmarshalValue(t *testing.T) {
"name": "john",
"json": `["a", "b", "c"]`,
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Json.Get(".").String(), `["a","b","c"]`)
t.Assert(v.Json.Get("2").String(), `c`)
@ -95,7 +95,7 @@ func TestJson_UnmarshalValue(t *testing.T) {
"name": "john",
"json": `[{"a":1},{"b":2},{"c":3}]`,
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Json.Get(".").String(), `[{"a":1},{"b":2},{"c":3}]`)
t.Assert(v.Json.Get("2.c").String(), `3`)
@ -111,7 +111,7 @@ func TestJson_UnmarshalValue(t *testing.T) {
"a": g.Slice{1, 2, 3},
},
}, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v.Name, "john")
t.Assert(v.Json.Get("n").String(), "123456789")
t.Assert(v.Json.Get("m").Map(), g.Map{"k": "v"})

View File

@ -66,7 +66,7 @@ func Test_Encode(t *testing.T) {
value := g.Slice{1, 2, 3}
gtest.C(t, func(t *gtest.T) {
b, err := gjson.Encode(value)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(b, []byte(`[1,2,3]`))
})
}
@ -75,7 +75,7 @@ func Test_Decode(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
v, err := gjson.Decode(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v, g.Map{
"n": 123456789,
"a": g.Slice{1, 2, 3},
@ -87,7 +87,7 @@ func Test_Decode(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var v interface{}
err := gjson.DecodeTo(data, &v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(v, g.Map{
"n": 123456789,
"a": g.Slice{1, 2, 3},
@ -98,7 +98,7 @@ func Test_Decode(t *testing.T) {
})
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m.k"), "v")
@ -112,7 +112,7 @@ func Test_SplitChar(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
j.SetSplitChar(byte('#'))
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("m#k").String(), "v")
@ -125,7 +125,7 @@ func Test_ViolenceCheck(t *testing.T) {
data := []byte(`{"m":{"a":[1,2,3], "v1.v2":"4"}}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("m.a.2"), 3)
t.Assert(j.Get("m.v1.v2"), nil)
j.SetViolenceCheck(true)
@ -137,7 +137,7 @@ func Test_GetVar(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").String(), "123456789")
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("a").Interfaces(), g.Slice{1, 2, 3})
@ -150,7 +150,7 @@ func Test_GetMap(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").Map(), nil)
t.Assert(j.Get("m").Map(), g.Map{"k": "v"})
t.Assert(j.Get("a").Map(), g.Map{"1": "2", "3": nil})
@ -161,7 +161,7 @@ func Test_GetJson(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
j2 := j.GetJson("m")
t.AssertNE(j2, nil)
t.Assert(j2.Get("k"), "v")
@ -174,7 +174,7 @@ func Test_GetArray(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("n").Array(), g.Array{123456789})
t.Assert(j.Get("m").Array(), g.Array{g.Map{"k": "v"}})
t.Assert(j.Get("a").Array(), g.Array{1, 2, 3})
@ -185,7 +185,7 @@ func Test_GetString(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.AssertEQ(j.Get("n").String(), "123456789")
t.AssertEQ(j.Get("m").String(), `{"k":"v"}`)
t.AssertEQ(j.Get("a").String(), `[1,2,3]`)
@ -197,7 +197,7 @@ func Test_GetStrings(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.AssertEQ(j.Get("n").Strings(), g.SliceStr{"123456789"})
t.AssertEQ(j.Get("m").Strings(), g.SliceStr{`{"k":"v"}`})
t.AssertEQ(j.Get("a").Strings(), g.SliceStr{"1", "2", "3"})
@ -209,7 +209,7 @@ func Test_GetInterfaces(t *testing.T) {
data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`)
gtest.C(t, func(t *gtest.T) {
j, err := gjson.DecodeToJson(data)
t.Assert(err, nil)
t.AssertNil(err)
t.AssertEQ(j.Get("n").Interfaces(), g.Array{123456789})
t.AssertEQ(j.Get("m").Interfaces(), g.Array{g.Map{"k": "v"}})
t.AssertEQ(j.Get("a").Interfaces(), g.Array{1, 2, 3})
@ -332,37 +332,37 @@ func Test_Convert(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
j := gjson.New(`{"name":"gf"}`)
arr, err := j.ToXml()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "<name>gf</name>")
arr, err = j.ToXmlIndent()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "<name>gf</name>")
str, err := j.ToXmlString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(str, "<name>gf</name>")
str, err = j.ToXmlIndentString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(str, "<name>gf</name>")
arr, err = j.ToJsonIndent()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "{\n\t\"name\": \"gf\"\n}")
str, err = j.ToJsonIndentString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "{\n\t\"name\": \"gf\"\n}")
arr, err = j.ToYaml()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "name: gf\n")
str, err = j.ToYamlString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "name: gf\n")
arr, err = j.ToToml()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "name = \"gf\"\n")
str, err = j.ToTomlString()
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(string(arr), "name = \"gf\"\n")
})
}
@ -387,19 +387,19 @@ func Test_Convert2(t *testing.T) {
t.Assert(j.Get("time").Duration().String(), "0s")
err := j.Var().Scan(&name)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(name.Name, "gf")
// j.Dump()
t.Assert(err, nil)
t.AssertNil(err)
j = gjson.New(`{"person":{"name":"gf"}}`)
err = j.Get("person").Scan(&name)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(name.Name, "gf")
j = gjson.New(`{"name":"gf""}`)
// j.Dump()
t.Assert(err, nil)
t.AssertNil(err)
j = gjson.New(`[1,2,3]`)
t.Assert(len(j.Var().Array()), 3)
@ -417,12 +417,12 @@ func Test_Basic(t *testing.T) {
t.Assert(j.Get(".").Interface().(g.Map)["name"], "gf")
err := j.Set("name", "gf1")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("name"), "gf1")
j = gjson.New(`[1,2,3]`)
err = j.Set("\"0\".1", 11)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("1"), 11)
j = gjson.New(`[1,2,3]`)
@ -431,7 +431,7 @@ func Test_Basic(t *testing.T) {
j = gjson.New(`[1,2,3]`)
err = j.Remove("1")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("0"), 1)
t.Assert(len(j.Var().Array()), 2)
@ -445,18 +445,18 @@ func Test_Basic(t *testing.T) {
j = gjson.New(`[1,2,3]`)
err = j.Remove("3")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("0"), 1)
t.Assert(len(j.Var().Array()), 3)
j = gjson.New(`[1,2,3]`)
err = j.Remove("0.3")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("0"), 1)
j = gjson.New(`[1,2,3]`)
err = j.Remove("0.a")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("0"), 1)
name := struct {
@ -465,35 +465,35 @@ func Test_Basic(t *testing.T) {
j = gjson.New(name)
t.Assert(j.Get("Name"), "gf")
err = j.Remove("Name")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name"), nil)
err = j.Set("Name", "gf1")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name"), "gf1")
j = gjson.New(nil)
err = j.Remove("Name")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name"), nil)
j = gjson.New(name)
t.Assert(j.Get("Name"), "gf")
err = j.Set("Name1", g.Map{"Name": "gf1"})
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name1").Interface().(g.Map)["Name"], "gf1")
err = j.Set("Name2", g.Slice{1, 2, 3})
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name2").Interface().(g.Slice)[0], 1)
err = j.Set("Name3", name)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name3").Interface().(g.Map)["Name"], "gf")
err = j.Set("Name4", &name)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name4").Interface().(g.Map)["Name"], "gf")
arr := [3]int{1, 2, 3}
err = j.Set("Name5", arr)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(j.Get("Name5").Interface().(g.Array)[0], 1)
})

View File

@ -112,7 +112,7 @@ func Test_Decode2(t *testing.T) {
<?xml version="1.0" encoding="UTF-8"?><doc><username>johngcn</username><password1>123456</password1><password2>123456</password2></doc>
`
m, err := gxml.Decode([]byte(content))
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m["doc"].(map[string]interface{})["username"], "johngcn")
t.Assert(m["doc"].(map[string]interface{})["password1"], "123456")
t.Assert(m["doc"].(map[string]interface{})["password2"], "123456")
@ -125,7 +125,7 @@ func Test_DecodeWitoutRoot(t *testing.T) {
<?xml version="1.0" encoding="UTF-8"?><doc><username>johngcn</username><password1>123456</password1><password2>123456</password2></doc>
`
m, err := gxml.DecodeWithoutRoot([]byte(content))
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(m["username"], "johngcn")
t.Assert(m["password1"], "123456")
t.Assert(m["password2"], "123456")

View File

@ -74,7 +74,7 @@ func Test_EncodeIndent(t *testing.T) {
func Test_Decode(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
result, err := gyaml.Decode([]byte(yamlStr))
t.Assert(err, nil)
t.AssertNil(err)
m, ok := result.(map[string]interface{})
t.Assert(ok, true)
@ -92,7 +92,7 @@ func Test_DecodeTo(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
result := make(map[string]interface{})
err := gyaml.DecodeTo([]byte(yamlStr), &result)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, map[string]interface{}{
"url": "https://goframe.org",
"server": g.Slice{"120.168.117.21", "120.168.117.22"},
@ -121,9 +121,9 @@ m:
k: v
`)
v, err := gyaml.Decode(data)
t.Assert(err, nil)
t.AssertNil(err)
b, err := json.Marshal(v)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(b, `{"m":{"k":"v"}}`)
})
}

View File

@ -251,7 +251,7 @@ func Test_Next(t *testing.T) {
t.Assert(err.Error(), "1")
err = gerror.Next(err)
t.Assert(err, nil)
t.AssertNil(err)
})
}

View File

@ -0,0 +1,4 @@
server:
address: ":8199"
openapiPath: "/api.json"
swaggerPath: "/swagger"

View File

@ -0,0 +1,38 @@
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
type HelloReq struct {
g.Meta `path:"/hello" method:"get"`
Name string `v:"required" dc:"Your name"`
}
type HelloRes struct {
Reply string `dc:"Reply content"`
}
type Hello struct{}
func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
g.Log().Debugf(ctx, `receive say: %+v`, req)
res = &HelloRes{
Reply: fmt.Sprintf(`Hi %s`, req.Name),
}
return
}
func main() {
s := g.Server()
s.Use(ghttp.MiddlewareHandlerResponse)
s.Group("/", func(group *ghttp.RouterGroup) {
group.Bind(
new(Hello),
)
})
s.Run()
}

View File

@ -42,15 +42,15 @@ func Test_Config2(t *testing.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dirPath)
name := "config.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), configContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config().GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
@ -65,16 +65,15 @@ func Test_Config2(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(gfile.Mkdir(dirPath))
defer gfile.Remove(dirPath)
name := "config/config.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), configContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config().GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
@ -92,15 +91,15 @@ func Test_Config3(t *testing.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dirPath)
name := "test.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), configContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config("test").GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config("test").GetAdapter().(*gcfg.AdapterFile).Clear()
gins.Config("test").GetAdapter().(*gcfg.AdapterFile).SetFileName("test.toml")
@ -116,15 +115,15 @@ func Test_Config3(t *testing.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dirPath)
name := "config/test.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), configContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config("test").GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config("test").GetAdapter().(*gcfg.AdapterFile).Clear()
gins.Config("test").GetAdapter().(*gcfg.AdapterFile).SetFileName("test.toml")
@ -143,7 +142,7 @@ func Test_Config4(t *testing.T) {
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
file := fmt.Sprintf(`%s/%s`, path, "config.toml")
err := gfile.PutContents(file, configContent)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(file)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
@ -158,7 +157,7 @@ func Test_Config4(t *testing.T) {
path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano())
file := fmt.Sprintf(`%s/%s`, path, "config.toml")
err := gfile.PutContents(file, configContent)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(file)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
t.Assert(gins.Config().GetAdapter().(*gcfg.AdapterFile).AddPath(path), nil)
@ -172,7 +171,7 @@ func Test_Config4(t *testing.T) {
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
file := fmt.Sprintf(`%s/%s`, path, "test.toml")
err := gfile.PutContents(file, configContent)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(file)
defer gins.Config("test").GetAdapter().(*gcfg.AdapterFile).Clear()
gins.Config("test").GetAdapter().(*gcfg.AdapterFile).SetFileName("test.toml")
@ -187,7 +186,7 @@ func Test_Config4(t *testing.T) {
path := fmt.Sprintf(`%s/%d/config`, gfile.Temp(), gtime.TimestampNano())
file := fmt.Sprintf(`%s/%s`, path, "test.toml")
err := gfile.PutContents(file, configContent)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(file)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
gins.Config("test").GetAdapter().(*gcfg.AdapterFile).SetFileName("test.toml")
@ -200,9 +199,11 @@ func Test_Config4(t *testing.T) {
func Test_Basic2(t *testing.T) {
config := `log-path = "logs"`
gtest.C(t, func(t *gtest.T) {
path := gcfg.DefaultConfigFile
err := gfile.PutContents(path, config)
t.Assert(err, nil)
var (
path = gcfg.DefaultConfigFileName
err = gfile.PutContents(path, config)
)
t.AssertNil(err)
defer func() {
_ = gfile.Remove(path)
}()

View File

@ -26,15 +26,15 @@ func Test_Database(t *testing.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dirPath)
name := "config.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), databaseContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config().GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()

View File

@ -27,15 +27,15 @@ func Test_Redis(t *testing.T) {
var err error
dirPath := gfile.Temp(gtime.TimestampNanoStr())
err = gfile.Mkdir(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(dirPath)
name := "config.toml"
err = gfile.PutContents(gfile.Join(dirPath, name), redisContent)
t.Assert(err, nil)
t.AssertNil(err)
err = gins.Config().GetAdapter().(*gcfg.AdapterFile).AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
defer gins.Config().GetAdapter().(*gcfg.AdapterFile).Clear()
@ -58,13 +58,13 @@ func Test_Redis(t *testing.T) {
t.Assert(r, "PONG")
r, err = redisCache.Do(ctx, "PING")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, "PONG")
_, err = redisDisk.Do(ctx, "SET", "k", "v")
t.Assert(err, nil)
t.AssertNil(err)
r, err = redisDisk.Do(ctx, "GET", "k")
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(r, []byte("v"))
})
}

View File

@ -28,7 +28,7 @@ func Test_View(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
tpl := "t.tpl"
err := gfile.PutContents(tpl, `{{"我是中国人" | substr 2 -1}}`)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tpl)
b, e := View().Parse(context.TODO(), "t.tpl", nil)
@ -39,10 +39,10 @@ func Test_View(t *testing.T) {
path := fmt.Sprintf(`%s/%d`, gfile.Temp(), gtime.TimestampNano())
tpl := fmt.Sprintf(`%s/%s`, path, "t.tpl")
err := gfile.PutContents(tpl, `{{"我是中国人" | substr 2 -1}}`)
t.Assert(err, nil)
t.AssertNil(err)
defer gfile.Remove(tpl)
err = View().AddPath(path)
t.Assert(err, nil)
t.AssertNil(err)
b, e := View().Parse(context.TODO(), "t.tpl", nil)
t.Assert(e, nil)
@ -61,16 +61,16 @@ func Test_View_Config(t *testing.T) {
view := View("test1")
t.AssertNE(view, nil)
err := view.AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
str := `hello ${.name},version:${.version}`
view.Assigns(map[string]interface{}{"version": "1.9.0"})
result, err := view.ParseContent(context.TODO(), str, nil)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "hello test1,version:1.9.0")
result, err = view.ParseDefault(context.TODO())
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "test1:test1")
})
// view1 test2
@ -83,16 +83,16 @@ func Test_View_Config(t *testing.T) {
view := View("test2")
t.AssertNE(view, nil)
err := view.AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
str := `hello #{.name},version:#{.version}`
view.Assigns(map[string]interface{}{"version": "1.9.0"})
result, err := view.ParseContent(context.TODO(), str, nil)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "hello test2,version:1.9.0")
result, err = view.ParseDefault(context.TODO())
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "test2:test2")
})
// view2
@ -105,16 +105,16 @@ func Test_View_Config(t *testing.T) {
view := View()
t.AssertNE(view, nil)
err := view.AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
str := `hello {.name},version:{.version}`
view.Assigns(map[string]interface{}{"version": "1.9.0"})
result, err := view.ParseContent(context.TODO(), str, nil)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "hello test,version:1.9.0")
result, err = view.ParseDefault(context.TODO())
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "test:test")
})
// view2
@ -127,16 +127,16 @@ func Test_View_Config(t *testing.T) {
view := View("test100")
t.AssertNE(view, nil)
err := view.AddPath(dirPath)
t.Assert(err, nil)
t.AssertNil(err)
str := `hello {.name},version:{.version}`
view.Assigns(map[string]interface{}{"version": "1.9.0"})
result, err := view.ParseContent(context.TODO(), str, nil)
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "hello test,version:1.9.0")
result, err = view.ParseDefault(context.TODO())
t.Assert(err, nil)
t.AssertNil(err)
t.Assert(result, "test:test")
})
}

View File

@ -85,7 +85,7 @@ func Test_TranslateFormat(t *testing.T) {
func Test_DefaultManager(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
err := gi18n.SetPath(gdebug.TestDataPath("i18n"))
t.Assert(err, nil)
t.AssertNil(err)
gi18n.SetLanguage("none")
t.Assert(gi18n.T(context.Background(), "{#hello}{#world}"), "{#hello}{#world}")
@ -99,7 +99,7 @@ func Test_DefaultManager(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
err := gi18n.SetPath(gdebug.CallerDirectory() + gfile.Separator + "testdata" + gfile.Separator + "i18n-dir")
t.Assert(err, nil)
t.AssertNil(err)
gi18n.SetLanguage("none")
t.Assert(gi18n.Translate(context.Background(), "{#hello}{#world}"), "{#hello}{#world}")
@ -117,7 +117,7 @@ func Test_Instance(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
m := gi18n.Instance()
err := m.SetPath("i18n-dir")
t.Assert(err, nil)
t.AssertNil(err)
m.SetLanguage("zh-CN")
t.Assert(m.T(context.Background(), "{#hello}{#world}"), "你好世界")
})
@ -141,7 +141,7 @@ func Test_Resource(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
m := g.I18n("resource")
err := m.SetPath("i18n-dir")
t.Assert(err, nil)
t.AssertNil(err)
m.SetLanguage("none")
t.Assert(m.T(context.Background(), "{#hello}{#world}"), "{#hello}{#world}")

View File

@ -10,6 +10,8 @@ package empty
import (
"reflect"
"time"
"github.com/gogf/gf/v2/internal/reflection"
)
// iString is used for type assert api for String().
@ -151,8 +153,10 @@ func IsEmpty(value interface{}) bool {
return rv.Len() == 0
case reflect.Struct:
var fieldValueInterface interface{}
for i := 0; i < rv.NumField(); i++ {
if !IsEmpty(rv.Field(i).Interface()) {
fieldValueInterface, _ = reflection.ValueToInterface(rv.Field(i))
if !IsEmpty(fieldValueInterface) {
return false
}
}

View File

@ -4,9 +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 utils
// Package reflection provides some reflection functions for internal usage.
package reflection
import "reflect"
import (
"reflect"
)
type OriginValueAndKindOutput struct {
InputValue reflect.Value
@ -41,6 +44,9 @@ type OriginTypeAndKindOutput struct {
// OriginTypeAndKind retrieves and returns the original reflect type and kind.
func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput) {
if value == nil {
return
}
if reflectType, ok := value.(reflect.Type); ok {
out.InputType = reflectType
} else {
@ -59,3 +65,30 @@ func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput) {
}
return
}
// ValueToInterface converts reflect value to its interface type.
func ValueToInterface(v reflect.Value) (value interface{}, ok bool) {
if v.IsValid() && v.CanInterface() {
return v.Interface(), true
}
switch v.Kind() {
case reflect.Bool:
return v.Bool(), true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint(), true
case reflect.Float32, reflect.Float64:
return v.Float(), true
case reflect.Complex64, reflect.Complex128:
return v.Complex(), true
case reflect.String:
return v.String(), true
case reflect.Ptr:
return ValueToInterface(v.Elem())
case reflect.Interface:
return ValueToInterface(v.Elem())
default:
return nil, false
}
}

View File

@ -0,0 +1,69 @@
// Copyright GoFrame Author(https://goframe.org). 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 reflection_test
import (
"reflect"
"testing"
"github.com/gogf/gf/v2/internal/reflection"
"github.com/gogf/gf/v2/test/gtest"
)
func Test_OriginValueAndKind(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var s = "s"
out := reflection.OriginValueAndKind(s)
t.Assert(out.InputKind, reflect.String)
t.Assert(out.OriginKind, reflect.String)
})
gtest.C(t, func(t *gtest.T) {
var s = "s"
out := reflection.OriginValueAndKind(&s)
t.Assert(out.InputKind, reflect.Ptr)
t.Assert(out.OriginKind, reflect.String)
})
gtest.C(t, func(t *gtest.T) {
var s []int
out := reflection.OriginValueAndKind(s)
t.Assert(out.InputKind, reflect.Slice)
t.Assert(out.OriginKind, reflect.Slice)
})
gtest.C(t, func(t *gtest.T) {
var s []int
out := reflection.OriginValueAndKind(&s)
t.Assert(out.InputKind, reflect.Ptr)
t.Assert(out.OriginKind, reflect.Slice)
})
}
func Test_OriginTypeAndKind(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var s = "s"
out := reflection.OriginTypeAndKind(s)
t.Assert(out.InputKind, reflect.String)
t.Assert(out.OriginKind, reflect.String)
})
gtest.C(t, func(t *gtest.T) {
var s = "s"
out := reflection.OriginTypeAndKind(&s)
t.Assert(out.InputKind, reflect.Ptr)
t.Assert(out.OriginKind, reflect.String)
})
gtest.C(t, func(t *gtest.T) {
var s []int
out := reflection.OriginTypeAndKind(s)
t.Assert(out.InputKind, reflect.Slice)
t.Assert(out.OriginKind, reflect.Slice)
})
gtest.C(t, func(t *gtest.T) {
var s []int
out := reflection.OriginTypeAndKind(&s)
t.Assert(out.InputKind, reflect.Ptr)
t.Assert(out.OriginKind, reflect.Slice)
})
}

Some files were not shown because too many files have changed in this diff Show More