Compare commits

...

52 Commits

Author SHA1 Message Date
c5c2938380 improve command gen ctrl and gen service (#2711) 2023-06-19 20:47:32 +08:00
d6433de4a6 add command gen ctrl for parsing api to generate controller and sdk go files (#2708) 2023-06-15 14:16:10 +08:00
15eaac35a8 bugfix : when using otel, calling gclient *Raw methods may result in null pointer exceptions (#2697) 2023-06-12 20:52:48 +08:00
46f3196297 Update gcompress_zip.go (#2694)
Fix index out of range when zipfile has dir __MAXOSX
2023-06-12 20:46:31 +08:00
842e5a6774 fix gdb_fun.go code comments (#2687) 2023-06-12 19:52:38 +08:00
2ece368810 add new validation rule "enums" (#2690) 2023-06-07 09:48:29 +08:00
1bbfc56121 improve key words transaction for package i18n (#2652) 2023-06-06 21:03:25 +08:00
835b252b5d fix issue in Where when used in field with prefix that not match struct attribute name (#2688) 2023-06-06 20:40:32 +08:00
9bc9fc4545 improve command make version (#2676) 2023-06-06 17:10:32 +08:00
8cc5338870 fix version retrieving of goframe for command version (#2682) 2023-06-02 18:02:24 +08:00
9191003391 feat: improve golangci-lint config (#2681) 2023-06-02 17:09:45 +08:00
99236fd93b version v2.4.2 (#2679) 2023-06-02 11:44:48 +08:00
b34d560bb7 add auto sync ci from github to gitee (#2680) 2023-06-02 10:05:42 +08:00
7bb4ddcfd5 ignore binary building if option Build is empty for command build (#2678)
ignore binary building if option Build is empty for command build
2023-06-01 21:52:59 +08:00
00190abad8 add method ScanAndCount and AllAndCount for Model package gdb (#2635) 2023-06-01 21:33:40 +08:00
aa8eabd853 fix issue #2439 (#2673) 2023-05-30 11:59:00 +08:00
4914517f6b template updates for command gf init (#2671) 2023-05-29 20:12:06 +08:00
0865dbbf75 improve command up for goframe version upgrade (#2670) 2023-05-29 16:29:42 +08:00
d3a3ad0228 add oltp(http&grpc) trace support (#2641) 2023-05-29 10:00:41 +08:00
e075432c40 comment update for package contrib/drivers/mysql (#2649) 2023-05-25 22:00:57 +08:00
e816ab05de refactor: code optimization (#2667) 2023-05-25 21:58:11 +08:00
a4762d0e02 fix issue in http proxy when repeatable reading request body content (#2666) 2023-05-25 11:56:12 +08:00
2329622564 add multiple methods support for united routes registering (#2664) 2023-05-25 10:58:06 +08:00
368312c816 add multiple methods support for object route (#2663) 2023-05-24 17:21:28 +08:00
f6dbe1a40c change parameter prefix of type string to prefixes of type slice for command enums (#2662) 2023-05-24 14:12:49 +08:00
032d085619 fix issue in building binary for command docker (#2660) 2023-05-24 14:12:22 +08:00
a6fff37be8 add DumpJson for package gutil (#2651) 2023-05-24 10:04:19 +08:00
879283685d fix(CLI): install cmd path choose empty not use default (#2655) 2023-05-23 21:59:47 +08:00
0f4f2a6672 fix issue in array border exceeded in RoundRobin of package gsel (#2642) 2023-05-23 21:30:47 +08:00
ff6f5ce237 update default logging time format using SetTimeFormat (#2611) 2023-05-23 20:59:58 +08:00
dc0467e934 add WhereOrNot/WhereOrPrefixNot functions for gdb.Model (#2661) 2023-05-23 17:35:47 +08:00
f0d22fe570 doc: correct level value comment (#2653) 2023-05-22 20:29:24 +08:00
05ee4d489a new logo (#2647) 2023-05-16 09:55:21 +08:00
3c1ded22fd cli command exits with code 1 if error (#2645) 2023-05-15 15:51:28 +08:00
bda5d252b2 fix host ip retrieving for package contrib/trace/jaeger when there is no intranet ip in host (#2640) 2023-05-12 11:59:05 +08:00
0c3e66d6a0 fix: genpbentity type error, []byte => bytes (#2633) 2023-05-12 10:17:07 +08:00
f31bf76f94 feat: modify readme doc address (#2638) 2023-05-11 20:44:56 +08:00
0afedee49d fix: genpbentity invalid proto3 (#2632) 2023-05-11 20:12:58 +08:00
43d439a1cd fix: When repairing protobuf to generate controllers, if the project … (#2630) 2023-05-11 20:11:04 +08:00
b8aeb4f0ee fix missing .exe suffix for cli file for windows downloading, unable replacing self cli binary (#2622) 2023-05-08 21:21:23 +08:00
1408385612 fix duplicated fields in function TableFields of driver pgsql (#2620) 2023-05-05 21:10:05 +08:00
d6471d7d51 v2.4.1 (#2615) 2023-05-05 14:15:01 +08:00
aa9d66c53c feat: improve polaris relation and add copyright for polaris example (#2607) 2023-05-05 10:04:32 +08:00
d9a7ee3e29 use first column name for Model.Array (#2609) 2023-04-28 14:55:53 +08:00
04c70f2037 fix empty string converted to none empty string type slice (#2612) 2023-04-28 14:55:37 +08:00
2198f0cefe fix issue #2561 #2431 (#2598) 2023-04-27 11:35:46 +08:00
c6b9b4d326 fix file registry that not works on windows (#2605) 2023-04-27 11:34:54 +08:00
4c6ebe7808 http context never done (#2602) 2023-04-26 20:20:47 +08:00
a9090e4a72 fix some comments (#2600)
Signed-off-by: cui fliter <imcusg@gmail.com>
2023-04-26 19:34:22 +08:00
0126eb5470 fix: polaris discouvery relation (#2603) 2023-04-26 19:31:28 +08:00
ed63617aa0 fix file permission error when overwriting directory containing .git … (#2599) 2023-04-25 21:36:37 +08:00
30f483a524 correct makefile (#2597) 2023-04-24 21:50:10 +08:00
189 changed files with 5903 additions and 748 deletions

BIN
.github/logo.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

View File

@ -20,9 +20,9 @@ for file in `find . -name go.mod`; do
fi fi
fi fi
# package example needs golang >= v1.18 # package example needs golang >= v1.19
if [ "example" = $(basename $dirpath) ]; then if [ "example" = $(basename $dirpath) ]; then
if ! go version|grep -q "1.18"; then if ! go version|grep -q "1.19"; then
echo "ignore example as go version: $(go version)" echo "ignore example as go version: $(go version)"
continue 1 continue 1
fi fi
@ -31,7 +31,23 @@ for file in `find . -name go.mod`; do
# package cmd/gf needs golang >= v1.18 # package cmd/gf needs golang >= v1.18
if [ "gf" = $(basename $dirpath) ]; then if [ "gf" = $(basename $dirpath) ]; then
if ! go version|grep -q "1.18"; then if ! go version|grep -q "1.18"; then
echo "ignore example as go version: $(go version)" echo "ignore cmd/gf as go version: $(go version)"
continue 1
fi
fi
# package otlpgrpc needs golang >= v1.20
if [ "otlpgrpc" = $(basename $dirpath) ]; then
if ! go version|grep -q "1.20"; then
echo "ignore otlpgrpc as go version: $(go version)"
continue 1
fi
fi
# package otlphttp needs golang >= v1.20
if [ "otlphttp" = $(basename $dirpath) ]; then
if ! go version|grep -q "1.20"; then
echo "ignore otlphttp as go version: $(go version)"
continue 1 continue 1
fi fi
fi fi

View File

@ -21,7 +21,7 @@ jobs:
- name: Set Up Golang Environment - name: Set Up Golang Environment
uses: actions/setup-go@v4 uses: actions/setup-go@v4
with: with:
go-version: 1.20.3 go-version: 1.20.4
- name: Build CLI Binary - name: Build CLI Binary
run: | run: |

View File

@ -120,13 +120,16 @@ jobs:
- 9001:9001 - 9001:9001
# Polaris backend server. # Polaris backend server.
# docker run -d --name polaris -p 8090:8090 -p 8091:8091 -p 8093:8093 loads/polaris-server-standalone:1.11.2 # docker run -d --name polaris -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 loads/polaris-server-standalone:1.11.2
# docker run -d --name polaris -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 loads/polaris-standalone:v1.16.3
polaris: polaris:
image: loads/polaris-server-standalone:1.11.2 image: loads/polaris-standalone:v1.16.4
ports: ports:
- 8090:8090 - 8090:8090
- 8091:8091 - 8091:8091
- 8093:8093 - 8093:8093
- 9090:9090
- 9091:9091
# Oracle 11g server # Oracle 11g server
oracle-server: oracle-server:
@ -153,7 +156,7 @@ jobs:
strategy: strategy:
matrix: matrix:
go-version: [ "1.15", "1.16", "1.17", "1.18" ] go-version: [ "1.15", "1.16", "1.17", "1.18", "1.19", "1.20" ]
goarch: [ "386", "amd64" ] goarch: [ "386", "amd64" ]
steps: steps:

28
.github/workflows/gitee-sync.yml vendored Normal file
View File

@ -0,0 +1,28 @@
on:
push:
branches:
- main
tags:
- "*"
name: Sync to Gitee
jobs:
run:
name: Run
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v3
- name: Mirror Github to Gitee
uses: Yikun/hub-mirror-action@v1.2
with:
src: github/gogf
dst: gitee/johng
dst_key: ${{ secrets.GITEE_PRIVATE_KEY }}
dst_token: ${{ secrets.GITEE_TOKEN }}
src_account_type: org
dst_account_type: user
timeout: 600
debug: true
force_update: true
static_list: "gf"

View File

@ -17,34 +17,38 @@ name: GolangCI-Lint
on: on:
push: push:
branches: branches:
- master - master
- develop - develop
- personal/** - personal/**
- feature/** - feature/**
- enhance/** - enhance/**
- fix/** - fix/**
pull_request: pull_request:
branches: branches:
- master - master
- develop - develop
- personal/** - personal/**
- feature/** - feature/**
- enhance/** - enhance/**
- fix/** - fix/**
jobs: jobs:
golangci: golangci:
strategy: strategy:
matrix: matrix:
go-version: [1.15.x,1.16.x,1.17.x,1.18.x] go-version: [ '1.15','1.16','1.17','1.18','1.19','1.20' ]
name: golangci-lint name: golangci-lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/setup-go@v3 - name: Checkout
- uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Setup Golang ${{ matrix.go-version }}
uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go-version }}
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v3.3.0 uses: golangci/golangci-lint-action@v3
with: with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: latest version: v1.52.2
args: --timeout 3m0s args: --timeout 3m0s

53
.set_version.sh Executable file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env bash
if [ $# -ne 2 ]; then
echo "Parameter exception, please execute in the format of $0 [directory] [version number]"
echo "PS$0 ./ v2.4.0"
exit 1
fi
if [ ! -d "$1" ]; then
echo "Error: Directory does not exist"
exit 1
fi
if [[ "$2" != v* ]]; then
echo "Error: Version number must start with v"
exit 1
fi
workdir=$1
newVersion=$2
echo "Prepare to replace the GF library version numbers in all go.mod files in the ${workdir} directory with ${newVersion}"
if [[ true ]]; then
echo "package gf" > version.go
echo "" >> version.go
echo "const (" >> version.go
echo -e "\t// VERSION is the current GoFrame version." >> version.go
echo -e "\tVERSION = \"${newVersion}\"" >> version.go
echo ")" >> version.go
fi
if [ -f "go.work" ]; then
mv go.work go.work.version.bak
echo "Back up the go.work file to avoid affecting the upgrade"
fi
for file in `find ${workdir} -name go.mod`; do
goModPath=$(dirname $file)
echo ""
echo "processing dir: $goModPath"
cd $goModPath
go mod tidy
# Upgrading only GF related libraries, sometimes even if a version number is specified, it may not be possible to successfully upgrade. Please confirm before submitting the code
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf"
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf" | xargs -L1 go get -v
go mod tidy
cd -
done
if [ -f "go.work.version.bak" ]; then
mv go.work.version.bak go.work
echo "Restore the go.work file"
fi

View File

@ -18,34 +18,9 @@ lint:
# make version to=v2.4.0 # make version to=v2.4.0
.PHONY: version .PHONY: version
version: version:
$(eval files=$(shell find . -name go.mod))
@set -e; \ @set -e; \
newVersion=$(to); \ newVersion=$(to); \
echo "The version will be set to $$newVersion"; \ ./.set_version.sh ./ $$newVersion; \
if [[ $$newVersion =~ "v" ]]; then \ echo "make version to=$(to) done"
latestVersion=$$newVersion; \
echo "package gf" > version.go; \
echo "" >> version.go; \
echo "const (" >> version.go; \
echo -e "\t// VERSION is the current GoFrame version." >> version.go; \
echo -e "\tVERSION = \"$$latestVersion\"" >> version.go; \
echo ")" >> version.go; \
else \
latestVersion=latest; \
fi; \
for file in ${files}; do \
goModPath=$$(dirname $$file); \
if [[ $$goModPath =~ "./contrib" || $$goModPath =~ "./cmd/gf" || $$goModPath =~ "./example" ]]; then \
echo ""; \
echo "processing dir: $$goModPath"; \
# Do not modify the order of any of the following sentences \
cd $$goModPath; \
go mod tidy; \
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@$$latestVersion{{end}}" -m all | grep "^github.com/gogf/gf/contrib" | xargs -L1 go get -v; \
go get -v github.com/gogf/gf/v2@$$latestVersion; \
go mod tidy; \
cd -; \
fi \
done

View File

@ -1,9 +1,9 @@
# GoFrame # GoFrame
<div align=center> <div align=center>
<img src="https://goframe.org/statics/image/gf-head-large.png" width="100"/> <img src="https://goframe.org/statics/image/logo2.png?v=1" width="300"/>
[![Go Doc](https://godoc.org/github.com/gogf/gf?status.svg)](https://godoc.org/github.com/gogf/gf) [![Go Reference](https://pkg.go.dev/badge/github.com/gogf/gf/v2.svg)](https://pkg.go.dev/github.com/gogf/gf/v2)
[![GoFrame CI](https://github.com/gogf/gf/actions/workflows/gf.yml/badge.svg)](https://github.com/gogf/gf/actions/workflows/gf.yml) [![GoFrame CI](https://github.com/gogf/gf/actions/workflows/gf.yml/badge.svg)](https://github.com/gogf/gf/actions/workflows/gf.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/gogf/gf/v2)](https://goreportcard.com/report/github.com/gogf/gf/v2) [![Go Report Card](https://goreportcard.com/badge/github.com/gogf/gf/v2)](https://goreportcard.com/report/github.com/gogf/gf/v2)
[![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf) [![Code Coverage](https://codecov.io/gh/gogf/gf/branch/master/graph/badge.svg)](https://codecov.io/gh/gogf/gf)

112
cmd/gf/gfcmd/gfcmd.go Normal file
View File

@ -0,0 +1,112 @@
// Copyright GoFrame gf 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 gfcmd
import (
_ "github.com/gogf/gf/cmd/gf/v2/internal/packed"
"context"
"github.com/gogf/gf/cmd/gf/v2/internal/cmd"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcfg"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
)
const (
cliFolderName = `hack`
)
// Command manages the CLI command of `gf`.
// This struct can be globally accessible and extended with custom struct.
type Command struct {
*gcmd.Command
}
// Run starts running the command according the command line arguments and options.
func (c *Command) Run(ctx context.Context) {
defer func() {
if exception := recover(); exception != nil {
if err, ok := exception.(error); ok {
mlog.Print(err.Error())
} else {
panic(exception)
}
}
}()
// CLI configuration, using the `hack/config.yaml` in priority.
if path, _ := gfile.Search(cliFolderName); path != "" {
if adapter, ok := g.Cfg().GetAdapter().(*gcfg.AdapterFile); ok {
if err := adapter.SetPath(path); err != nil {
mlog.Fatal(err)
}
}
}
// zsh alias "git fetch" conflicts checks.
handleZshAlias()
// -y option checks.
allyes.Init()
// just run.
if err := c.RunWithError(ctx); err != nil {
// Exit with error message and exit code 1.
// It is very important to exit the command process with code 1.
mlog.Fatalf(`%+v`, err)
}
}
// GetCommand retrieves and returns the root command of CLI `gf`.
func GetCommand(ctx context.Context) (*Command, error) {
root, err := gcmd.NewFromObject(cmd.GF)
if err != nil {
panic(err)
}
err = root.AddObject(
cmd.Up,
cmd.Env,
cmd.Fix,
cmd.Run,
cmd.Gen,
cmd.Tpl,
cmd.Init,
cmd.Pack,
cmd.Build,
cmd.Docker,
cmd.Install,
cmd.Version,
)
if err != nil {
return nil, err
}
command := &Command{
root,
}
return command, nil
}
// zsh alias "git fetch" conflicts checks.
func handleZshAlias() {
if home, err := gfile.Home(); err == nil {
zshPath := gfile.Join(home, ".zshrc")
if gfile.Exists(zshPath) {
var (
aliasCommand = `alias gf=gf`
content = gfile.GetContents(zshPath)
)
if !gstr.Contains(content, aliasCommand) {
_ = gfile.PutContentsAppend(zshPath, "\n"+aliasCommand+"\n")
}
}
}
}

View File

@ -3,18 +3,20 @@ module github.com/gogf/gf/cmd/gf/v2
go 1.18 go 1.18
require ( require (
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.4.4
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/mssql/v2 v2.4.4
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/mysql/v2 v2.4.4
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/oracle/v2 v2.4.4
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.4.4
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.4.0 github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.4.4
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/minio/selfupdate v0.6.0
github.com/olekukonko/tablewriter v0.0.5 github.com/olekukonko/tablewriter v0.0.5
golang.org/x/tools v0.7.0 golang.org/x/tools v0.7.0
) )
require ( require (
aead.dev/minisign v0.2.0 // indirect
github.com/BurntSushi/toml v1.1.0 // indirect github.com/BurntSushi/toml v1.1.0 // indirect
github.com/ClickHouse/clickhouse-go/v2 v2.0.15 // indirect github.com/ClickHouse/clickhouse-go/v2 v2.0.15 // indirect
github.com/clbanning/mxj/v2 v2.5.5 // indirect github.com/clbanning/mxj/v2 v2.5.5 // indirect

View File

@ -1,3 +1,5 @@
aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk=
aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ=
github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I=
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI=
@ -63,6 +65,8 @@ github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/Qd
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM=
github.com/mkevac/debugcharts v0.0.0-20191222103121-ae1c48aa8615/go.mod h1:Ad7oeElCZqA1Ufj0U9/liOF4BtVepxRcTvr2ey7zTvM= github.com/mkevac/debugcharts v0.0.0-20191222103121-ae1c48aa8615/go.mod h1:Ad7oeElCZqA1Ufj0U9/liOF4BtVepxRcTvr2ey7zTvM=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
@ -105,6 +109,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU= golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@ -128,13 +134,16 @@ golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191220220014-0732a990476f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191220220014-0732a990476f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@ -144,6 +153,7 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=

View File

@ -129,7 +129,7 @@ type cBuildInput struct {
VarMap g.Map `short:"r" name:"varMap" brief:"custom built embedded variable into binary"` VarMap g.Map `short:"r" name:"varMap" brief:"custom built embedded variable into binary"`
PackSrc string `short:"ps" name:"packSrc" brief:"pack one or more folders into one go file before building"` PackSrc string `short:"ps" name:"packSrc" brief:"pack one or more folders into one go file before building"`
PackDst string `short:"pd" name:"packDst" brief:"temporary go file path for pack, this go file will be automatically removed after built" d:"internal/packed/build_pack_data.go"` PackDst string `short:"pd" name:"packDst" brief:"temporary go file path for pack, this go file will be automatically removed after built" d:"internal/packed/build_pack_data.go"`
ExitWhenError bool `short:"ew" name:"exitWhenError" brief:"exit building when any error occurs, default is false" orphan:"true"` ExitWhenError bool `short:"ew" name:"exitWhenError" brief:"exit building when any error occurs, specially for multiple arch and system buildings. default is false" orphan:"true"`
DumpENV bool `short:"de" name:"dumpEnv" brief:"dump current go build environment before building binary" orphan:"true"` DumpENV bool `short:"de" name:"dumpEnv" brief:"dump current go build environment before building binary" orphan:"true"`
} }
@ -143,7 +143,7 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e
mlog.SetHeaderPrint(true) mlog.SetHeaderPrint(true)
mlog.Debugf(`build input: %+v`, in) mlog.Debugf(`build command input: %+v`, in)
// Necessary check. // Necessary check.
if gproc.SearchBinary("go") == "" { if gproc.SearchBinary("go") == "" {
mlog.Fatalf(`command "go" not found in your environment, please install golang first to proceed this command`) mlog.Fatalf(`command "go" not found in your environment, please install golang first to proceed this command`)
@ -304,7 +304,7 @@ buildDone:
return return
} }
// getBuildInVarMapJson retrieves and returns the custom build-in variables in configuration // getBuildInVarStr retrieves and returns the custom build-in variables in configuration
// file as json. // file as json.
func (c cBuild) getBuildInVarStr(ctx context.Context, in cBuildInput) string { func (c cBuild) getBuildInVarStr(ctx context.Context, in cBuildInput) string {
buildInVarMap := in.VarMap buildInVarMap := in.VarMap

View File

@ -78,10 +78,10 @@ func init() {
type cDockerInput struct { type cDockerInput struct {
g.Meta `name:"docker" config:"gfcli.docker"` g.Meta `name:"docker" config:"gfcli.docker"`
Main string `name:"MAIN" arg:"true" brief:"{cDockerMainBrief}" d:"main.go"` Main string `name:"MAIN" arg:"true" brief:"{cDockerMainBrief}" d:"main.go"`
File string `name:"file" short:"f" brief:"{cDockerFileBrief}" d:"manifest/docker/Dockerfile"` File string `name:"file" short:"f" brief:"{cDockerFileBrief}" d:"manifest/docker/Dockerfile"`
Shell string `name:"shell" short:"s" brief:"{cDockerShellBrief}" d:"manifest/docker/docker.sh"` Shell string `name:"shell" short:"s" brief:"{cDockerShellBrief}" d:"manifest/docker/docker.sh"`
Build string `name:"build" short:"b" brief:"{cDockerBuildBrief}" d:"-a amd64 -s linux"` Build string `name:"build" short:"b" brief:"{cDockerBuildBrief}"`
Tag string `name:"tag" short:"t" brief:"{cDockerTagBrief}"` Tag string `name:"tag" short:"t" brief:"{cDockerTagBrief}"`
TagName string `name:"tagName" short:"tn" brief:"{cDockerTagNameBrief}" v:"required-with:TagPrefixes"` TagName string `name:"tagName" short:"tn" brief:"{cDockerTagNameBrief}" v:"required-with:TagPrefixes"`
TagPrefixes []string `name:"tagPrefixes" short:"tp" brief:"{cDockerTagPrefixesBrief}" v:"required-with:TagName"` TagPrefixes []string `name:"tagPrefixes" short:"tp" brief:"{cDockerTagPrefixesBrief}" v:"required-with:TagName"`
@ -97,17 +97,23 @@ func (c cDocker) Index(ctx context.Context, in cDockerInput) (out *cDockerOutput
mlog.Fatalf(`command "docker" not found in your environment, please install docker first to proceed this command`) mlog.Fatalf(`command "docker" not found in your environment, please install docker first to proceed this command`)
} }
mlog.Debugf(`docker command input: %+v`, in)
// Binary build. // Binary build.
in.Build += " --exit" if in.Main != "" && in.Build != "" {
if in.Main != "" { in.Build += " --exitWhenError"
if err = gproc.ShellRun(ctx, fmt.Sprintf(`gf build %s %s`, in.Main, in.Build)); err != nil { if in.Main != "" {
return if err = gproc.ShellRun(ctx, fmt.Sprintf(`gf build %s %s`, in.Main, in.Build)); err != nil {
mlog.Debugf(`build binary failed with error: %+v`, err)
return
}
} }
} }
// Shell executing. // Shell executing.
if in.Shell != "" && gfile.Exists(in.Shell) { if in.Shell != "" && gfile.Exists(in.Shell) {
if err = c.exeDockerShell(ctx, in.Shell); err != nil { if err = c.exeDockerShell(ctx, in.Shell); err != nil {
mlog.Debugf(`build docker failed with error: %+v`, err)
return return
} }
} }

View File

@ -19,6 +19,7 @@ type cGen struct {
g.Meta `name:"gen" brief:"{cGenBrief}" dc:"{cGenDc}"` g.Meta `name:"gen" brief:"{cGenBrief}" dc:"{cGenDc}"`
cGenDao cGenDao
cGenEnums cGenEnums
cGenCtrl
cGenPb cGenPb
cGenPbEntity cGenPbEntity
cGenService cGenService

View File

@ -0,0 +1,15 @@
// Copyright GoFrame gf 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 cmd
import (
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/genctrl"
)
type (
cGenCtrl = genctrl.CGenCtrl
)

View File

@ -9,6 +9,7 @@ package cmd
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
@ -16,6 +17,7 @@ import (
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/os/gres" "github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gtag" "github.com/gogf/gf/v2/util/gtag"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes" "github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes"
@ -43,6 +45,10 @@ gf init my-mono-repo -m
name for the project. It will create a folder with NAME in current directory. name for the project. It will create a folder with NAME in current directory.
The NAME will also be the module name for the project. The NAME will also be the module name for the project.
` `
// cInitGitDir the git directory
cInitGitDir = ".git"
// cInitGitignore the gitignore file
cInitGitignore = ".gitignore"
) )
func init() { func init() {
@ -63,17 +69,22 @@ type cInitInput struct {
type cInitOutput struct{} type cInitOutput struct{}
func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err error) { func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err error) {
var (
overwrote = false
)
if !gfile.IsEmpty(in.Name) && !allyes.Check() { if !gfile.IsEmpty(in.Name) && !allyes.Check() {
s := gcmd.Scanf(`the folder "%s" is not empty, files might be overwrote, continue? [y/n]: `, in.Name) s := gcmd.Scanf(`the folder "%s" is not empty, files might be overwrote, continue? [y/n]: `, in.Name)
if strings.EqualFold(s, "n") { if strings.EqualFold(s, "n") {
return return
} }
overwrote = true
} }
mlog.Print("initializing...") mlog.Print("initializing...")
// Create project folder and files. // Create project folder and files.
var ( var (
templateRepoName string templateRepoName string
gitignoreFile = in.Name + "/" + cInitGitignore
) )
if in.Mono { if in.Mono {
templateRepoName = cInitMonoRepo templateRepoName = cInitMonoRepo
@ -87,14 +98,35 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
return return
} }
// build ignoreFiles from the .gitignore file
ignoreFiles := make([]string, 0, 10)
ignoreFiles = append(ignoreFiles, cInitGitDir)
if overwrote {
err = gfile.ReadLines(gitignoreFile, func(line string) error {
// Add only hidden files or directories
// If other directories are added, it may cause the entire directory to be ignored
// such as 'main' in the .gitignore file, but the path is 'D:\main\my-project'
if line != "" && strings.HasPrefix(line, ".") {
ignoreFiles = append(ignoreFiles, line)
}
return nil
})
// if not found the .gitignore file will skip os.ErrNotExist error
if err != nil && !os.IsNotExist(err) {
return
}
}
// Replace template name to project name. // Replace template name to project name.
err = gfile.ReplaceDir( err = gfile.ReplaceDirFunc(func(path, content string) string {
cInitRepoPrefix+templateRepoName, for _, ignoreFile := range ignoreFiles {
gfile.Basename(gfile.RealPath(in.Name)), if strings.Contains(path, ignoreFile) {
in.Name, return content
"*", }
true, }
) return gstr.Replace(gfile.GetContents(path), cInitRepoPrefix+templateRepoName, gfile.Basename(gfile.RealPath(in.Name)))
}, in.Name, "*", true)
if err != nil { if err != nil {
return return
} }

View File

@ -11,10 +11,11 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils" "github.com/minio/selfupdate"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gproc"
@ -124,6 +125,8 @@ func (c cUp) doUpgradeVersion(ctx context.Context, in cUpInput) (out *doUpgradeV
if gfile.Exists(goModPath) { if gfile.Exists(goModPath) {
var packages []Package var packages []Package
err = gfile.ReadLines(goModPath, func(line string) error { err = gfile.ReadLines(goModPath, func(line string) error {
line = gstr.Trim(line)
line = gstr.TrimLeftStr(line, "require ")
line = gstr.Trim(line) line = gstr.Trim(line)
if gstr.HasPrefix(line, gfPackage) { if gstr.HasPrefix(line, gfPackage) {
array := gstr.SplitAndTrim(line, " ") array := gstr.SplitAndTrim(line, " ")
@ -174,6 +177,11 @@ func (c cUp) doUpgradeCLI(ctx context.Context) (err error) {
) )
localSaveFilePath = gfile.SelfPath() + "~" localSaveFilePath = gfile.SelfPath() + "~"
) )
if runtime.GOOS == "windows" {
downloadUrl += ".exe"
}
mlog.Printf(`start downloading "%s" to "%s", it may take some time`, downloadUrl, localSaveFilePath) mlog.Printf(`start downloading "%s" to "%s", it may take some time`, downloadUrl, localSaveFilePath)
err = utils.HTTPDownloadFileWithPercent(downloadUrl, localSaveFilePath) err = utils.HTTPDownloadFileWithPercent(downloadUrl, localSaveFilePath)
if err != nil { if err != nil {
@ -191,17 +199,14 @@ func (c cUp) doUpgradeCLI(ctx context.Context) (err error) {
mlog.Fatalf(`download "%s" to "%s" failed`, downloadUrl, localSaveFilePath) mlog.Fatalf(`download "%s" to "%s" failed`, downloadUrl, localSaveFilePath)
} }
// It replaces self binary with new version cli binary. newFile, err := gfile.Open(localSaveFilePath)
switch runtime.GOOS { if err != nil {
case "windows": return err
if err := gfile.Rename(localSaveFilePath, gfile.SelfPath()); err != nil { }
mlog.Fatalf(`install failed: %s`, err.Error()) // selfupdate
} err = selfupdate.Apply(newFile, selfupdate.Options{})
if err != nil {
default: return err
if err := gfile.PutBytes(gfile.SelfPath(), gfile.GetBytes(localSaveFilePath)); err != nil {
mlog.Fatalf(`install failed: %s`, err.Error())
}
} }
return return
} }

View File

@ -70,6 +70,8 @@ func (c cVersion) getGFVersionOfCurrentProject() (string, error) {
if gfile.Exists(goModPath) { if gfile.Exists(goModPath) {
lines := gstr.SplitAndTrim(gfile.GetContents(goModPath), "\n") lines := gstr.SplitAndTrim(gfile.GetContents(goModPath), "\n")
for _, line := range lines { for _, line := range lines {
line = gstr.Trim(line)
line = gstr.TrimLeftStr(line, "require ")
line = gstr.Trim(line) line = gstr.Trim(line)
// Version 1. // Version 1.
match, err := gregex.MatchString(`^github\.com/gogf/gf\s+(.+)$`, line) match, err := gregex.MatchString(`^github\.com/gogf/gf\s+(.+)$`, line)

View File

@ -0,0 +1,233 @@
// Copyright GoFrame gf 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 genctrl
import (
"context"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
)
const (
CGenCtrlConfig = `gfcli.gen.ctrl`
CGenCtrlUsage = `gf gen ctrl [OPTION]`
CGenCtrlBrief = `parse api definitions to generate controller/sdk go files`
CGenCtrlEg = `
gf gen ctrl
`
CGenCtrlBriefSrcFolder = `source folder path to be parsed. default: api`
CGenCtrlBriefDstFolder = `destination folder path storing automatically generated go files. default: internal/controller`
CGenCtrlBriefWatchFile = `used in file watcher, it re-generates go files only if given file is under srcFolder`
CGenCtrlBriefSdkPath = `also generate SDK go files for api definitions to specified directory`
CGenCtrlBriefSdkStdVersion = `use standard version prefix for generated sdk request path`
CGenCtrlBriefSdkNoV1 = `do not add version suffix for interface module name if version is v1`
CGenCtrlBriefClear = `auto delete generated and unimplemented controller go files if api definitions are missing`
)
const (
PatternApiDefinition = `type\s+(\w+)Req\s+struct\s+{`
PatternCtrlDefinition = `func\s+\(.+?\)\s+\w+\(.+?\*(\w+)\.(\w+)Req\)\s+\(.+?\*(\w+)\.(\w+)Res,\s+\w+\s+error\)\s+{`
)
const (
genCtrlFileLockSeconds = 10
)
func init() {
gtag.Sets(g.MapStrStr{
`CGenCtrlConfig`: CGenCtrlConfig,
`CGenCtrlUsage`: CGenCtrlUsage,
`CGenCtrlBrief`: CGenCtrlBrief,
`CGenCtrlEg`: CGenCtrlEg,
`CGenCtrlBriefSrcFolder`: CGenCtrlBriefSrcFolder,
`CGenCtrlBriefDstFolder`: CGenCtrlBriefDstFolder,
`CGenCtrlBriefWatchFile`: CGenCtrlBriefWatchFile,
`CGenCtrlBriefSdkPath`: CGenCtrlBriefSdkPath,
`CGenCtrlBriefSdkStdVersion`: CGenCtrlBriefSdkStdVersion,
`CGenCtrlBriefSdkNoV1`: CGenCtrlBriefSdkNoV1,
`CGenCtrlBriefClear`: CGenCtrlBriefClear,
})
}
type (
CGenCtrl struct{}
CGenCtrlInput struct {
g.Meta `name:"ctrl" config:"{CGenCtrlConfig}" usage:"{CGenCtrlUsage}" brief:"{CGenCtrlBrief}" eg:"{CGenCtrlEg}"`
SrcFolder string `short:"s" name:"srcFolder" brief:"{CGenCtrlBriefSrcFolder}" d:"api"`
DstFolder string `short:"d" name:"dstFolder" brief:"{CGenCtrlBriefDstFolder}" d:"internal/controller"`
WatchFile string `short:"w" name:"watchFile" brief:"{CGenCtrlBriefWatchFile}"`
SdkPath string `short:"k" name:"sdkPath" brief:"{CGenCtrlBriefSdkPath}"`
SdkStdVersion bool `short:"v" name:"sdkStdVersion" brief:"{CGenCtrlBriefSdkStdVersion}" orphan:"true"`
SdkNoV1 bool `short:"n" name:"sdkNoV1" brief:"{CGenCtrlBriefSdkNoV1}" orphan:"true"`
Clear bool `short:"c" name:"clear" brief:"{CGenCtrlBriefClear}" orphan:"true"`
}
CGenCtrlOutput struct{}
)
func (c CGenCtrl) Ctrl(ctx context.Context, in CGenCtrlInput) (out *CGenCtrlOutput, err error) {
if in.WatchFile != "" {
err = c.generateByWatchFile(
in.WatchFile, in.SdkPath, in.SdkStdVersion, in.SdkNoV1, in.Clear,
)
mlog.Print(`done!`)
return
}
if !gfile.Exists(in.SrcFolder) {
mlog.Fatalf(`source folder path "%s" does not exist`, in.SrcFolder)
}
// retrieve all api modules.
apiModuleFolderPaths, err := gfile.ScanDir(in.SrcFolder, "*", false)
if err != nil {
return nil, err
}
for _, apiModuleFolderPath := range apiModuleFolderPaths {
if !gfile.IsDir(apiModuleFolderPath) {
continue
}
// generate go files by api module.
var (
module = gfile.Basename(apiModuleFolderPath)
dstModuleFolderPath = gfile.Join(in.DstFolder, module)
)
err = c.generateByModule(
apiModuleFolderPath, dstModuleFolderPath, in.SdkPath,
in.SdkStdVersion, in.SdkNoV1, in.Clear,
)
if err != nil {
return nil, err
}
}
mlog.Print(`done!`)
return
}
func (c CGenCtrl) generateByWatchFile(watchFile, sdkPath string, sdkStdVersion, sdkNoV1, clear bool) (err error) {
// File lock to avoid multiple processes.
var (
flockFilePath = gfile.Temp("gf.cli.gen.service.lock")
flockContent = gfile.GetContents(flockFilePath)
)
if flockContent != "" {
if gtime.Timestamp()-gconv.Int64(flockContent) < genCtrlFileLockSeconds {
// If another generating process is running, it just exits.
mlog.Debug(`another "gen service" process is running, exit`)
return
}
}
defer gfile.Remove(flockFilePath)
_ = gfile.PutContents(flockFilePath, gtime.TimestampStr())
// check this updated file is an api file.
// watch file should be in standard goframe project structure.
var (
apiVersionPath = gfile.Dir(watchFile)
apiModuleFolderPath = gfile.Dir(apiVersionPath)
shouldBeNameOfAPi = gfile.Basename(gfile.Dir(apiModuleFolderPath))
)
if shouldBeNameOfAPi != "api" {
return nil
}
// watch file should have api definitions.
if gfile.Exists(watchFile) {
if !gregex.IsMatchString(PatternApiDefinition, gfile.GetContents(watchFile)) {
return nil
}
}
var (
projectRootPath = gfile.Dir(gfile.Dir(apiModuleFolderPath))
module = gfile.Basename(apiModuleFolderPath)
dstModuleFolderPath = gfile.Join(projectRootPath, "internal", "controller", module)
)
return c.generateByModule(
apiModuleFolderPath, dstModuleFolderPath, sdkPath, sdkStdVersion, sdkNoV1, clear,
)
}
// parseApiModule parses certain api and generate associated go files by certain module, not all api modules.
func (c CGenCtrl) generateByModule(
apiModuleFolderPath, dstModuleFolderPath, sdkPath string,
sdkStdVersion, sdkNoV1, clear bool,
) (err error) {
// parse src and dst folder go files.
apiItemsInSrc, err := c.getApiItemsInSrc(apiModuleFolderPath)
if err != nil {
return err
}
apiItemsInDst, err := c.getApiItemsInDst(dstModuleFolderPath)
if err != nil {
return err
}
// generate api interface go files.
if err = newApiInterfaceGenerator().Generate(apiModuleFolderPath, apiItemsInSrc); err != nil {
return
}
// generate controller go files.
// api filtering for already implemented api controllers.
var (
alreadyImplementedCtrlSet = gset.NewStrSet()
toBeImplementedApiItems = make([]apiItem, 0)
)
for _, item := range apiItemsInDst {
alreadyImplementedCtrlSet.Add(item.String())
}
for _, item := range apiItemsInSrc {
if alreadyImplementedCtrlSet.Contains(item.String()) {
continue
}
toBeImplementedApiItems = append(toBeImplementedApiItems, item)
}
if len(toBeImplementedApiItems) > 0 {
err = newControllerGenerator().Generate(dstModuleFolderPath, toBeImplementedApiItems)
if err != nil {
return
}
}
// delete unimplemented controllers if api definitions are missing.
if clear {
var (
apiDefinitionSet = gset.NewStrSet()
extraApiItemsInCtrl = make([]apiItem, 0)
)
for _, item := range apiItemsInSrc {
apiDefinitionSet.Add(item.String())
}
for _, item := range apiItemsInDst {
if apiDefinitionSet.Contains(item.String()) {
continue
}
extraApiItemsInCtrl = append(extraApiItemsInCtrl, item)
}
if len(extraApiItemsInCtrl) > 0 {
err = newControllerClearer().Clear(dstModuleFolderPath, extraApiItemsInCtrl)
if err != nil {
return
}
}
}
// generate sdk go files.
if sdkPath != "" {
if err = newApiSdkGenerator().Generate(apiItemsInSrc, sdkPath, sdkStdVersion, sdkNoV1); err != nil {
return
}
}
return
}

View File

@ -0,0 +1,22 @@
// Copyright GoFrame gf 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 genctrl
import "github.com/gogf/gf/v2/text/gstr"
type apiItem struct {
Import string `eg:"demo.com/api/user/v1"`
Module string `eg:"user"`
Version string `eg:"v1"`
MethodName string `eg:"GetList"`
}
func (a apiItem) String() string {
return gstr.Join([]string{
a.Import, a.Module, a.Version, a.MethodName,
}, ",")
}

View File

@ -0,0 +1,136 @@
// Copyright GoFrame gf 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 genctrl
import (
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
)
func (c CGenCtrl) getApiItemsInSrc(apiModuleFolderPath string) (items []apiItem, err error) {
var (
fileContent string
importPath string
)
// The second level folders: versions.
apiVersionFolderPaths, err := gfile.ScanDir(apiModuleFolderPath, "*", false)
if err != nil {
return nil, err
}
for _, apiVersionFolderPath := range apiVersionFolderPaths {
if !gfile.IsDir(apiVersionFolderPath) {
continue
}
// The second level folders: versions.
apiFileFolderPaths, err := gfile.ScanDir(apiVersionFolderPath, "*.go", false)
if err != nil {
return nil, err
}
importPath = utils.GetImportPath(apiVersionFolderPath)
for _, apiFileFolderPath := range apiFileFolderPaths {
if gfile.IsDir(apiFileFolderPath) {
continue
}
fileContent = gfile.GetContents(apiFileFolderPath)
matches, err := gregex.MatchAllString(PatternApiDefinition, fileContent)
if err != nil {
return nil, err
}
for _, match := range matches {
item := apiItem{
Import: gstr.Trim(importPath, `"`),
Module: gfile.Basename(apiModuleFolderPath),
Version: gfile.Basename(apiVersionFolderPath),
MethodName: match[1],
}
items = append(items, item)
}
}
}
return
}
func (c CGenCtrl) getApiItemsInDst(dstFolder string) (items []apiItem, err error) {
if !gfile.Exists(dstFolder) {
return nil, nil
}
type importItem struct {
Path string
Alias string
}
var fileContent string
filePaths, err := gfile.ScanDir(dstFolder, "*.go", true)
if err != nil {
return nil, err
}
for _, filePath := range filePaths {
fileContent = gfile.GetContents(filePath)
match, err := gregex.MatchString(`import\s+\(([\s\S]+?)\)`, fileContent)
if err != nil {
return nil, err
}
if len(match) < 2 {
continue
}
var (
array []string
importItems []importItem
importLines = gstr.SplitAndTrim(match[1], "\n")
module = gfile.Basename(gfile.Dir(filePath))
)
// retrieve all imports.
for _, importLine := range importLines {
array = gstr.SplitAndTrim(importLine, " ")
if len(array) == 2 {
importItems = append(importItems, importItem{
Path: gstr.Trim(array[1], `"`),
Alias: array[0],
})
} else {
importItems = append(importItems, importItem{
Path: gstr.Trim(array[0], `"`),
})
}
}
// retrieve all api usages.
matches, err := gregex.MatchAllString(PatternCtrlDefinition, fileContent)
if err != nil {
return nil, err
}
for _, match = range matches {
// try to find the import path of the api.
var (
importPath string
version = match[1]
methodName = match[2] // not the function name, but the method name in api definition.
)
for _, item := range importItems {
if item.Alias != "" {
if item.Alias == version {
importPath = item.Path
break
}
continue
}
if gfile.Basename(item.Path) == version {
importPath = item.Path
break
}
}
item := apiItem{
Import: gstr.Trim(importPath, `"`),
Module: module,
Version: gfile.Basename(importPath),
MethodName: methodName,
}
items = append(items, item)
}
}
return
}

View File

@ -0,0 +1,135 @@
// Copyright GoFrame gf 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 genctrl
import (
"fmt"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
)
type controllerGenerator struct{}
func newControllerGenerator() *controllerGenerator {
return &controllerGenerator{}
}
func (c *controllerGenerator) Generate(dstModuleFolderPath string, apiModuleApiItems []apiItem) (err error) {
var (
doneApiItemSet = gset.NewStrSet()
)
for _, item := range apiModuleApiItems {
if doneApiItemSet.Contains(item.String()) {
continue
}
// retrieve all api items of the same module.
subItems := c.getSubItemsByModuleAndVersion(apiModuleApiItems, item.Module, item.Version)
if err = c.doGenerateCtrlNewByModuleAndVersion(
dstModuleFolderPath, item.Module, item.Version, gfile.Dir(item.Import),
); err != nil {
return
}
for _, subItem := range subItems {
if err = c.doGenerateCtrlItem(dstModuleFolderPath, subItem); err != nil {
return
}
doneApiItemSet.Add(subItem.String())
}
}
return
}
func (c *controllerGenerator) getSubItemsByModuleAndVersion(items []apiItem, module, version string) (subItems []apiItem) {
for _, item := range items {
if item.Module == module && item.Version == version {
subItems = append(subItems, item)
}
}
return
}
func (c *controllerGenerator) doGenerateCtrlNewByModuleAndVersion(
dstModuleFolderPath, module, version, importPath string,
) (err error) {
var (
moduleFilePath = gfile.Join(dstModuleFolderPath, module+".go")
moduleFilePathNew = gfile.Join(dstModuleFolderPath, module+"_new.go")
ctrlName = fmt.Sprintf(`Controller%s`, gstr.UcFirst(version))
interfaceName = fmt.Sprintf(`%s.I%s%s`, module, gstr.CaseCamel(module), gstr.UcFirst(version))
newFuncName = fmt.Sprintf(`New%s`, gstr.UcFirst(version))
newFuncNameDefinition = fmt.Sprintf(`func %s()`, newFuncName)
alreadyCreated bool
)
if !gfile.Exists(moduleFilePath) {
content := gstr.ReplaceByMap(consts.TemplateGenCtrlControllerEmpty, g.MapStrStr{
"{Module}": module,
})
if err = gfile.PutContents(moduleFilePath, gstr.TrimLeft(content)); err != nil {
return err
}
mlog.Printf(`generated: %s`, moduleFilePath)
}
if !gfile.Exists(moduleFilePathNew) {
content := gstr.ReplaceByMap(consts.TemplateGenCtrlControllerNewEmpty, g.MapStrStr{
"{Module}": module,
"{ImportPath}": fmt.Sprintf(`"%s"`, importPath),
})
if err = gfile.PutContents(moduleFilePathNew, gstr.TrimLeft(content)); err != nil {
return err
}
mlog.Printf(`generated: %s`, moduleFilePathNew)
}
filePaths, err := gfile.ScanDir(dstModuleFolderPath, "*.go", false)
if err != nil {
return err
}
for _, filePath := range filePaths {
if gstr.Contains(gfile.GetContents(filePath), newFuncNameDefinition) {
alreadyCreated = true
break
}
}
if !alreadyCreated {
content := gstr.ReplaceByMap(consts.TemplateGenCtrlControllerNewFunc, g.MapStrStr{
"{CtrlName}": ctrlName,
"{NewFuncName}": newFuncName,
"{InterfaceName}": interfaceName,
})
err = gfile.PutContentsAppend(moduleFilePathNew, gstr.TrimLeft(content))
if err != nil {
return err
}
}
return
}
func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, item apiItem) (err error) {
var (
methodNameSnake = gstr.CaseSnake(item.MethodName)
ctrlName = fmt.Sprintf(`Controller%s`, gstr.UcFirst(item.Version))
methodFilePath = gfile.Join(dstModuleFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, item.Module, item.Version, methodNameSnake,
))
)
content := gstr.ReplaceByMap(consts.TemplateGenCtrlControllerMethodFunc, g.MapStrStr{
"{Module}": item.Module,
"{ImportPath}": item.Import,
"{CtrlName}": ctrlName,
"{Version}": item.Version,
"{MethodName}": item.MethodName,
})
if err = gfile.PutContents(methodFilePath, gstr.TrimLeft(content)); err != nil {
return err
}
mlog.Printf(`generated: %s`, methodFilePath)
return
}

View File

@ -0,0 +1,57 @@
// Copyright GoFrame gf 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 genctrl
import (
"fmt"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
)
type controllerClearer struct{}
func newControllerClearer() *controllerClearer {
return &controllerClearer{}
}
func (c *controllerClearer) Clear(dstModuleFolderPath string, extraApiItemsInCtrl []apiItem) (err error) {
for _, item := range extraApiItemsInCtrl {
if err = c.doClear(dstModuleFolderPath, item); err != nil {
return err
}
}
return
}
func (c *controllerClearer) doClear(dstModuleFolderPath string, item apiItem) (err error) {
var (
methodNameSnake = gstr.CaseSnake(item.MethodName)
methodFilePath = gfile.Join(dstModuleFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, item.Module, item.Version, methodNameSnake,
))
fileContent = gstr.Trim(gfile.GetContents(methodFilePath))
)
match, err := gregex.MatchString(`.+?Req.+?Res.+?{([\s\S]+?)}`, fileContent)
if err != nil {
return err
}
if len(match) > 1 {
implements := gstr.Trim(match[1])
// One line.
if !gstr.Contains(implements, "\n") && gstr.Contains(implements, `CodeNotImplemented`) {
mlog.Printf(
`remove unimplemented and of no api definitions controller file: %s`,
methodFilePath,
)
err = gfile.Remove(methodFilePath)
}
}
return
}

View File

@ -0,0 +1,111 @@
// Copyright GoFrame gf 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 genctrl
import (
"fmt"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
type apiInterfaceGenerator struct{}
func newApiInterfaceGenerator() *apiInterfaceGenerator {
return &apiInterfaceGenerator{}
}
func (c *apiInterfaceGenerator) Generate(apiModuleFolderPath string, apiModuleApiItems []apiItem) (err error) {
if len(apiModuleApiItems) == 0 {
return nil
}
var firstApiItem = apiModuleApiItems[0]
if err = c.doGenerate(apiModuleFolderPath, firstApiItem.Module, apiModuleApiItems); err != nil {
return
}
return
}
func (c *apiInterfaceGenerator) doGenerate(apiModuleFolderPath string, module string, items []apiItem) (err error) {
var (
moduleFilePath = gfile.Join(apiModuleFolderPath, fmt.Sprintf(`%s.go`, module))
importPathMap = gmap.NewListMap()
importPaths []string
)
// all import paths.
importPathMap.Set("\t"+`"context"`, 1)
importPathMap.Set("\t"+``, 1)
for _, item := range items {
importPathMap.Set(fmt.Sprintf("\t"+`"%s"`, item.Import), 1)
}
importPaths = gconv.Strings(importPathMap.Keys())
// interface definitions.
var (
doneApiItemSet = gset.NewStrSet()
interfaceDefinition string
interfaceContent = gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlApiInterface, g.MapStrStr{
"{Module}": module,
"{ImportPaths}": gstr.Join(importPaths, "\n"),
}))
)
for _, item := range items {
if doneApiItemSet.Contains(item.String()) {
continue
}
// retrieve all api items of the same module.
subItems := c.getSubItemsByModuleAndVersion(items, item.Module, item.Version)
var (
method string
methods = make([]string, 0)
interfaceName = fmt.Sprintf(`I%s%s`, gstr.CaseCamel(item.Module), gstr.UcFirst(item.Version))
)
for _, subItem := range subItems {
method = fmt.Sprintf(
"\t%s(ctx context.Context, req *%s.%sReq) (res *%s.%sRes, err error)",
subItem.MethodName, subItem.Version, subItem.MethodName, subItem.Version, subItem.MethodName,
)
methods = append(methods, method)
doneApiItemSet.Add(subItem.String())
}
interfaceDefinition += fmt.Sprintf("type %s interface {", interfaceName)
interfaceDefinition += "\n"
interfaceDefinition += gstr.Join(methods, "\n")
interfaceDefinition += "\n"
interfaceDefinition += fmt.Sprintf("}")
interfaceDefinition += "\n\n"
}
interfaceContent = gstr.TrimLeft(gstr.ReplaceByMap(interfaceContent, g.MapStrStr{
"{Interfaces}": interfaceDefinition,
}))
err = gfile.PutContents(moduleFilePath, interfaceContent)
mlog.Printf(`generated: %s`, moduleFilePath)
return
}
func (c *apiInterfaceGenerator) getSubItemsByModule(items []apiItem, module string) (subItems []apiItem) {
for _, item := range items {
if item.Module == module {
subItems = append(subItems, item)
}
}
return
}
func (c *apiInterfaceGenerator) getSubItemsByModuleAndVersion(items []apiItem, module, version string) (subItems []apiItem) {
for _, item := range items {
if item.Module == module && item.Version == version {
subItems = append(subItems, item)
}
}
return
}

View File

@ -0,0 +1,194 @@
// Copyright GoFrame gf 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 genctrl
import (
"fmt"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
)
type apiSdkGenerator struct{}
func newApiSdkGenerator() *apiSdkGenerator {
return &apiSdkGenerator{}
}
func (c *apiSdkGenerator) Generate(apiModuleApiItems []apiItem, sdkFolderPath string, sdkStdVersion, sdkNoV1 bool) (err error) {
if err = c.doGenerateSdkPkgFile(sdkFolderPath); err != nil {
return
}
var doneApiItemSet = gset.NewStrSet()
for _, item := range apiModuleApiItems {
if doneApiItemSet.Contains(item.String()) {
continue
}
// retrieve all api items of the same module.
subItems := c.getSubItemsByModuleAndVersion(apiModuleApiItems, item.Module, item.Version)
if err = c.doGenerateSdkIClient(sdkFolderPath, item.Import, item.Module, item.Version, sdkNoV1); err != nil {
return
}
if err = c.doGenerateSdkImplementer(
subItems, sdkFolderPath, item.Import, item.Module, item.Version, sdkStdVersion, sdkNoV1,
); err != nil {
return
}
for _, subItem := range subItems {
doneApiItemSet.Add(subItem.String())
}
}
return
}
func (c *apiSdkGenerator) doGenerateSdkPkgFile(sdkFolderPath string) (err error) {
var (
pkgName = gfile.Basename(sdkFolderPath)
pkgFilePath = gfile.Join(sdkFolderPath, fmt.Sprintf(`%s.go`, pkgName))
fileContent string
)
if gfile.Exists(pkgFilePath) {
return nil
}
fileContent = gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlSdkPkgNew, g.MapStrStr{
"{PkgName}": pkgName,
}))
err = gfile.PutContents(pkgFilePath, fileContent)
mlog.Printf(`generated: %s`, pkgFilePath)
return
}
func (c *apiSdkGenerator) doGenerateSdkIClient(
sdkFolderPath, versionImportPath, module, version string, sdkNoV1 bool,
) (err error) {
var (
fileContent string
isDirty bool
isExist bool
pkgName = gfile.Basename(sdkFolderPath)
funcName = gstr.CaseCamel(module) + gstr.UcFirst(version)
interfaceName = fmt.Sprintf(`I%s`, funcName)
moduleImportPath = fmt.Sprintf(`"%s"`, gfile.Dir(versionImportPath))
iClientFilePath = gfile.Join(sdkFolderPath, fmt.Sprintf(`%s.iclient.go`, pkgName))
interfaceFuncDefinition = fmt.Sprintf(
`%s() %s.%s`,
gstr.CaseCamel(module)+gstr.UcFirst(version), module, interfaceName,
)
)
if sdkNoV1 && version == "v1" {
interfaceFuncDefinition = fmt.Sprintf(
`%s() %s.%s`,
gstr.CaseCamel(module), module, interfaceName,
)
}
if isExist = gfile.Exists(iClientFilePath); isExist {
fileContent = gfile.GetContents(iClientFilePath)
} else {
fileContent = gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlSdkIClient, g.MapStrStr{
"{PkgName}": pkgName,
}))
}
// append the import path to current import paths.
if !gstr.Contains(fileContent, moduleImportPath) {
isDirty = true
fileContent, err = gregex.ReplaceString(
`(import \([\s\S]*?)\)`,
fmt.Sprintf("$1\t%s\n)", moduleImportPath),
fileContent,
)
if err != nil {
return
}
}
// append the function definition to interface definition.
if !gstr.Contains(fileContent, interfaceFuncDefinition) {
isDirty = true
fileContent, err = gregex.ReplaceString(
`(type iClient interface {[\s\S]*?)}`,
fmt.Sprintf("$1\t%s\n}", interfaceFuncDefinition),
fileContent,
)
if err != nil {
return
}
}
if isDirty {
err = gfile.PutContents(iClientFilePath, fileContent)
if isExist {
mlog.Printf(`updated: %s`, iClientFilePath)
} else {
mlog.Printf(`generated: %s`, iClientFilePath)
}
}
return
}
func (c *apiSdkGenerator) doGenerateSdkImplementer(
items []apiItem, sdkFolderPath, versionImportPath, module, version string, sdkStdVersion, sdkNoV1 bool,
) (err error) {
var (
pkgName = gfile.Basename(sdkFolderPath)
moduleNameCamel = gstr.CaseCamel(module)
moduleNameSnake = gstr.CaseSnake(module)
moduleImportPath = gfile.Dir(versionImportPath)
versionPrefix = ""
implementerName = moduleNameCamel + gstr.UcFirst(version)
implementerFilePath = gfile.Join(sdkFolderPath, fmt.Sprintf(
`%s_%s_%s.go`, pkgName, moduleNameSnake, version,
))
)
if sdkNoV1 && version == "v1" {
implementerName = moduleNameCamel
}
// implementer file template.
var importPaths = make([]string, 0)
importPaths = append(importPaths, fmt.Sprintf("\t\"%s\"", moduleImportPath))
importPaths = append(importPaths, fmt.Sprintf("\t\"%s\"", versionImportPath))
implementerFileContent := gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlSdkImplementer, g.MapStrStr{
"{PkgName}": pkgName,
"{ImportPaths}": gstr.Join(importPaths, "\n"),
"{ImplementerName}": implementerName,
}))
// implementer new function definition.
if sdkStdVersion {
versionPrefix = fmt.Sprintf(`/api/%s`, version)
}
implementerFileContent += gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlSdkImplementerNew, g.MapStrStr{
"{Module}": module,
"{VersionPrefix}": versionPrefix,
"{ImplementerName}": implementerName,
}))
// implementer functions definitions.
for _, item := range items {
implementerFileContent += gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlSdkImplementerFunc, g.MapStrStr{
"{Version}": item.Version,
"{MethodName}": item.MethodName,
"{ImplementerName}": implementerName,
}))
implementerFileContent += "\n"
}
err = gfile.PutContents(implementerFilePath, implementerFileContent)
mlog.Printf(`generated: %s`, implementerFilePath)
return
}
func (c *apiSdkGenerator) getSubItemsByModuleAndVersion(items []apiItem, module, version string) (subItems []apiItem) {
for _, item := range items {
if item.Module == module && item.Version == version {
subItems = append(subItems, item)
}
}
return
}

View File

@ -16,7 +16,6 @@ import (
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gtag" "github.com/gogf/gf/v2/util/gtag"
@ -180,7 +179,6 @@ type (
DB gdb.DB DB gdb.DB
TableNames []string TableNames []string
NewTableNames []string NewTableNames []string
ModName string // Module name of current golang project, which is used for import purpose.
} }
) )
@ -204,9 +202,8 @@ func (c CGenDao) Dao(ctx context.Context, in CGenDaoInput) (out *CGenDaoOutput,
// doGenDaoForArray implements the "gen dao" command for configuration array. // doGenDaoForArray implements the "gen dao" command for configuration array.
func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) { func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
var ( var (
err error err error
db gdb.DB db gdb.DB
modName string // Go module name, eg: github.com/gogf/gf.
) )
if index >= 0 { if index >= 0 {
err = g.Cfg().MustGet( err = g.Cfg().MustGet(
@ -221,21 +218,6 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
mlog.Fatalf(`path "%s" does not exist`, in.Path) mlog.Fatalf(`path "%s" does not exist`, in.Path)
} }
removePrefixArray := gstr.SplitAndTrim(in.RemovePrefix, ",") removePrefixArray := gstr.SplitAndTrim(in.RemovePrefix, ",")
if in.ImportPrefix == "" {
mlog.Debug(`import prefix is empty, trying calculating the import package path using go.mod`)
if !gfile.Exists("go.mod") {
mlog.Fatal("go.mod does not exist in current working directory")
}
var (
goModContent = gfile.GetContents("go.mod")
match, _ = gregex.MatchString(`^module\s+(.+)\s*`, goModContent)
)
if len(match) > 1 {
modName = gstr.Trim(match[1])
} else {
mlog.Fatal("module name does not found in go.mod")
}
}
// It uses user passed database configuration. // It uses user passed database configuration.
if in.Link != "" { if in.Link != "" {
@ -287,7 +269,6 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
DB: db, DB: db,
TableNames: tableNames, TableNames: tableNames,
NewTableNames: newTableNames, NewTableNames: newTableNames,
ModName: modName,
}) })
// Do. // Do.
generateDo(ctx, CGenDaoInternalInput{ generateDo(ctx, CGenDaoInternalInput{
@ -295,7 +276,6 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
DB: db, DB: db,
TableNames: tableNames, TableNames: tableNames,
NewTableNames: newTableNames, NewTableNames: newTableNames,
ModName: modName,
}) })
// Entity. // Entity.
generateEntity(ctx, CGenDaoInternalInput{ generateEntity(ctx, CGenDaoInternalInput{
@ -303,7 +283,6 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
DB: db, DB: db,
TableNames: tableNames, TableNames: tableNames,
NewTableNames: newTableNames, NewTableNames: newTableNames,
ModName: modName,
}) })
} }

View File

@ -17,7 +17,6 @@ import (
"github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/cmd/gf/v2/internal/consts" "github.com/gogf/gf/cmd/gf/v2/internal/consts"
@ -60,23 +59,13 @@ func generateDaoSingle(ctx context.Context, in generateDaoSingleInput) {
mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err) mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err)
} }
var ( var (
dirRealPath = gfile.RealPath(in.Path)
tableNameCamelCase = gstr.CaseCamel(in.NewTableName) tableNameCamelCase = gstr.CaseCamel(in.NewTableName)
tableNameCamelLowerCase = gstr.CaseCamelLower(in.NewTableName) tableNameCamelLowerCase = gstr.CaseCamelLower(in.NewTableName)
tableNameSnakeCase = gstr.CaseSnake(in.NewTableName) tableNameSnakeCase = gstr.CaseSnake(in.NewTableName)
importPrefix = in.ImportPrefix importPrefix = in.ImportPrefix
) )
if importPrefix == "" { if importPrefix == "" {
if dirRealPath == "" { importPrefix = utils.GetImportPath(gfile.Join(in.Path, in.DaoPath))
dirRealPath = in.Path
importPrefix = dirRealPath
importPrefix = gstr.Trim(dirRealPath, "./")
} else {
importPrefix = gstr.Replace(dirRealPath, gfile.Pwd(), "")
}
importPrefix = gstr.Replace(importPrefix, gfile.Separator, "/")
importPrefix = gstr.Join(g.SliceStr{in.ModName, importPrefix, in.DaoPath}, "/")
importPrefix, _ = gregex.ReplaceString(`\/{2,}`, `/`, gstr.Trim(importPrefix, "/"))
} else { } else {
importPrefix = gstr.Join(g.SliceStr{importPrefix, in.DaoPath}, "/") importPrefix = gstr.Join(g.SliceStr{importPrefix, in.DaoPath}, "/")
} }

View File

@ -57,7 +57,7 @@ func generateStructDefinition(ctx context.Context, in generateStructDefinitionIn
return buffer.String() return buffer.String()
} }
// generateStructFieldForModel generates and returns the attribute definition for specified field. // generateStructFieldDefinition generates and returns the attribute definition for specified field.
func generateStructFieldDefinition( func generateStructFieldDefinition(
ctx context.Context, field *gdb.TableField, in generateStructDefinitionInput, ctx context.Context, field *gdb.TableField, in generateStructDefinitionInput,
) []string { ) []string {

View File

@ -21,10 +21,10 @@ import (
type ( type (
CGenEnums struct{} CGenEnums struct{}
CGenEnumsInput struct { CGenEnumsInput struct {
g.Meta `name:"enums" config:"{CGenEnumsConfig}" brief:"{CGenEnumsBrief}" eg:"{CGenEnumsEg}"` g.Meta `name:"enums" config:"{CGenEnumsConfig}" brief:"{CGenEnumsBrief}" eg:"{CGenEnumsEg}"`
Src string `name:"src" short:"s" dc:"source folder path to be parsed" d:"."` Src string `name:"src" short:"s" dc:"source folder path to be parsed" d:"."`
Path string `name:"path" short:"p" dc:"output go file path storing enums content" d:"internal/boot/boot_enums.go"` Path string `name:"path" short:"p" dc:"output go file path storing enums content" d:"internal/boot/boot_enums.go"`
Prefix string `name:"prefix" short:"x" dc:"only exports packages that starts with specified prefix"` Prefixes []string `name:"prefixes" short:"x" dc:"only exports packages that starts with specified prefixes"`
} }
CGenEnumsOutput struct{} CGenEnumsOutput struct{}
) )
@ -57,7 +57,7 @@ func (c CGenEnums) Enums(ctx context.Context, in CGenEnumsInput) (out *CGenEnums
if err != nil { if err != nil {
mlog.Fatal(err) mlog.Fatal(err)
} }
mlog.Printf(`scanning: %s`, realPath) mlog.Printf(`scanning for enums: %s`, realPath)
cfg := &packages.Config{ cfg := &packages.Config{
Dir: realPath, Dir: realPath,
Mode: pkgLoadMode, Mode: pkgLoadMode,
@ -67,7 +67,7 @@ func (c CGenEnums) Enums(ctx context.Context, in CGenEnumsInput) (out *CGenEnums
if err != nil { if err != nil {
mlog.Fatal(err) mlog.Fatal(err)
} }
p := NewEnumsParser(in.Prefix) p := NewEnumsParser(in.Prefixes)
p.ParsePackages(pkgs) p.ParsePackages(pkgs)
var enumsContent = gstr.ReplaceByMap(consts.TemplateGenEnums, g.MapStrStr{ var enumsContent = gstr.ReplaceByMap(consts.TemplateGenEnums, g.MapStrStr{
"{PackageName}": gfile.Basename(gfile.Dir(in.Path)), "{PackageName}": gfile.Basename(gfile.Dir(in.Path)),
@ -77,7 +77,7 @@ func (c CGenEnums) Enums(ctx context.Context, in CGenEnumsInput) (out *CGenEnums
if err = gfile.PutContents(in.Path, enumsContent); err != nil { if err = gfile.PutContents(in.Path, enumsContent); err != nil {
return return
} }
mlog.Printf(`generated: %s`, in.Path) mlog.Printf(`generated enums go file: %s`, in.Path)
mlog.Print("done!") mlog.Print("done!")
return return
} }

View File

@ -21,7 +21,7 @@ const pkgLoadMode = 0xffffff
type EnumsParser struct { type EnumsParser struct {
enums []EnumItem enums []EnumItem
parsedPkg map[string]struct{} parsedPkg map[string]struct{}
prefix string prefixes []string
} }
type EnumItem struct { type EnumItem struct {
@ -43,11 +43,11 @@ func init() {
} }
} }
func NewEnumsParser(prefix string) *EnumsParser { func NewEnumsParser(prefixes []string) *EnumsParser {
return &EnumsParser{ return &EnumsParser{
enums: make([]EnumItem, 0), enums: make([]EnumItem, 0),
parsedPkg: make(map[string]struct{}), parsedPkg: make(map[string]struct{}),
prefix: prefix, prefixes: prefixes,
} }
} }
@ -67,9 +67,16 @@ func (p *EnumsParser) ParsePackage(pkg *packages.Package) {
return return
} }
p.parsedPkg[pkg.ID] = struct{}{} p.parsedPkg[pkg.ID] = struct{}{}
// Only parse specified prefix.
if p.prefix != "" { // Only parse specified prefixes.
if !gstr.HasPrefix(pkg.ID, p.prefix) { if len(p.prefixes) > 0 {
var hasPrefix bool
for _, prefix := range p.prefixes {
if hasPrefix = gstr.HasPrefix(pkg.ID, prefix); hasPrefix {
break
}
}
if !hasPrefix {
return return
} }
} }
@ -108,7 +115,6 @@ func (p *EnumsParser) ParsePackage(pkg *packages.Package) {
Type: enumType, Type: enumType,
Kind: enumKind, Kind: enumKind,
}) })
} }
for _, im := range pkg.Imports { for _, im := range pkg.Imports {
p.ParsePackage(im) p.ParsePackage(im)

View File

@ -9,6 +9,7 @@ package genpb
import ( import (
"context" "context"
"fmt" "fmt"
"strings"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils" "github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
@ -85,7 +86,7 @@ func (c CGenPb) parseControllers(filePath string) ([]generateCtrl, error) {
func(match []string) string { func(match []string) string {
ctrl := generateCtrl{ ctrl := generateCtrl{
Name: match[1], Name: match[1],
Package: gfile.Basename(gfile.Dir(gfile.Dir(filePath))), Package: strings.ReplaceAll(gfile.Basename(gfile.Dir(gfile.Dir(filePath))), "-", "_"),
Version: gfile.Basename(gfile.Dir(filePath)), Version: gfile.Basename(gfile.Dir(filePath)),
Methods: make([]generateCtrlMethod, 0), Methods: make([]generateCtrlMethod, 0),
} }

View File

@ -10,7 +10,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"github.com/olekukonko/tablewriter"
"strings" "strings"
"github.com/gogf/gf/cmd/gf/v2/internal/consts" "github.com/gogf/gf/cmd/gf/v2/internal/consts"
@ -24,6 +23,7 @@ import (
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gtag" "github.com/gogf/gf/v2/util/gtag"
"github.com/olekukonko/tablewriter"
) )
type ( type (
@ -317,9 +317,9 @@ func generateMessageFieldForPbEntity(index int, field *gdb.TableField, in CGenPb
gdb.LocalTypeUint64Slice: "repeated uint64", gdb.LocalTypeUint64Slice: "repeated uint64",
gdb.LocalTypeInt64Bytes: "repeated int64", gdb.LocalTypeInt64Bytes: "repeated int64",
gdb.LocalTypeUint64Bytes: "repeated uint64", gdb.LocalTypeUint64Bytes: "repeated uint64",
gdb.LocalTypeFloat32: "float32", gdb.LocalTypeFloat32: "float",
gdb.LocalTypeFloat64: "float64", gdb.LocalTypeFloat64: "double",
gdb.LocalTypeBytes: "[]byte", gdb.LocalTypeBytes: "bytes",
gdb.LocalTypeBool: "bool", gdb.LocalTypeBool: "bool",
gdb.LocalTypeJson: "string", gdb.LocalTypeJson: "string",
gdb.LocalTypeJsonb: "string", gdb.LocalTypeJsonb: "string",

View File

@ -11,10 +11,10 @@ import (
"fmt" "fmt"
"github.com/gogf/gf/v2/container/garray" "github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gset" "github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gregex" "github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
@ -50,7 +50,7 @@ destination file name storing automatically generated go files, cases are as fol
` `
CGenServiceBriefWatchFile = `used in file watcher, it re-generates all service go files only if given file is under srcFolder` CGenServiceBriefWatchFile = `used in file watcher, it re-generates all service go files only if given file is under srcFolder`
CGenServiceBriefStPattern = `regular expression matching struct name for generating service. default: ^s([A-Z]\\\\w+)$` CGenServiceBriefStPattern = `regular expression matching struct name for generating service. default: ^s([A-Z]\\\\w+)$`
CGenServiceBriefPackages = `produce go files only for given source packages` CGenServiceBriefPackages = `produce go files only for given source packages(source folders)`
CGenServiceBriefImportPrefix = `custom import prefix to calculate import path for generated importing go file of logic` CGenServiceBriefImportPrefix = `custom import prefix to calculate import path for generated importing go file of logic`
CGenServiceBriefClear = `delete all generated go files that are not used any further` CGenServiceBriefClear = `delete all generated go files that are not used any further`
) )
@ -93,21 +93,6 @@ const (
) )
func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGenServiceOutput, err error) { func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGenServiceOutput, err error) {
// File lock to avoid multiple processes.
var (
flockFilePath = gfile.Temp("gf.cli.gen.service.lock")
flockContent = gfile.GetContents(flockFilePath)
)
if flockContent != "" {
if gtime.Timestamp()-gconv.Int64(flockContent) < genServiceFileLockSeconds {
// If another "gen service" process is running, it just exits.
mlog.Debug(`another "gen service" process is running, exit`)
return
}
}
defer gfile.Remove(flockFilePath)
_ = gfile.PutContents(flockFilePath, gtime.TimestampStr())
in.SrcFolder = gstr.TrimRight(in.SrcFolder, `\/`) in.SrcFolder = gstr.TrimRight(in.SrcFolder, `\/`)
in.SrcFolder = gstr.Replace(in.SrcFolder, "\\", "/") in.SrcFolder = gstr.Replace(in.SrcFolder, "\\", "/")
in.WatchFile = gstr.TrimRight(in.WatchFile, `\/`) in.WatchFile = gstr.TrimRight(in.WatchFile, `\/`)
@ -115,6 +100,21 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
// Watch file handling. // Watch file handling.
if in.WatchFile != "" { if in.WatchFile != "" {
// File lock to avoid multiple processes.
var (
flockFilePath = gfile.Temp("gf.cli.gen.service.lock")
flockContent = gfile.GetContents(flockFilePath)
)
if flockContent != "" {
if gtime.Timestamp()-gconv.Int64(flockContent) < genServiceFileLockSeconds {
// If another "gen service" process is running, it just exits.
mlog.Debug(`another "gen service" process is running, exit`)
return
}
}
defer gfile.Remove(flockFilePath)
_ = gfile.PutContents(flockFilePath, gtime.TimestampStr())
// It works only if given WatchFile is in SrcFolder. // It works only if given WatchFile is in SrcFolder.
var ( var (
watchFileDir = gfile.Dir(in.WatchFile) watchFileDir = gfile.Dir(in.WatchFile)
@ -131,13 +131,10 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
mlog.Fatalf(`%+v`, err) mlog.Fatalf(`%+v`, err)
} }
mlog.Debug("Chdir:", newWorkingDir) mlog.Debug("Chdir:", newWorkingDir)
_ = gfile.Remove(flockFilePath)
var command = fmt.Sprintf( in.WatchFile = ""
`%s gen service -packages=%s`, in.Packages = []string{gfile.Basename(watchFileDir)}
gfile.SelfName(), gfile.Basename(watchFileDir), return c.Service(ctx, in)
)
err = gproc.ShellRun(ctx, command)
return
} }
if !gfile.Exists(in.SrcFolder) { if !gfile.Exists(in.SrcFolder) {
@ -145,16 +142,7 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
} }
if in.ImportPrefix == "" { if in.ImportPrefix == "" {
if !gfile.Exists("go.mod") { in.ImportPrefix = utils.GetImportPath(in.SrcFolder)
mlog.Fatal("ImportPrefix is empty and go.mod does not exist in current working directory")
}
var (
goModContent = gfile.GetContents("go.mod")
match, _ = gregex.MatchString(`^module\s+(.+)\s*`, goModContent)
)
if len(match) > 1 {
in.ImportPrefix = fmt.Sprintf(`%s/%s`, gstr.Trim(match[1]), gstr.Replace(in.SrcFolder, `\`, `/`))
}
} }
var ( var (
@ -182,34 +170,74 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
if len(files) == 0 { if len(files) == 0 {
continue continue
} }
// Parse single logic package folder.
var ( var (
// StructName => FunctionDefinitions // StructName => FunctionDefinitions
srcPkgInterfaceMap = make(map[string]*garray.StrArray) srcPkgInterfaceMap = make(map[string]*garray.StrArray)
srcImportedPackages = garray.NewSortedStrArray().SetUnique(true) srcImportedPackages = garray.NewSortedStrArray().SetUnique(true)
srcPackageName = gfile.Basename(srcFolderPath) importPackageItemAliasMap = gmap.NewStrStrMap() // for conflict imports check. alias => path
ok bool srcPackageName = gfile.Basename(srcFolderPath)
dstFilePath = gfile.Join(in.DstFolder, aliasIndex = 0
ok bool
dstFilePath = gfile.Join(in.DstFolder,
c.getDstFileNameCase(srcPackageName, in.DstFileNameCase)+".go", c.getDstFileNameCase(srcPackageName, in.DstFileNameCase)+".go",
) )
) )
generatedDstFilePathSet.Add(dstFilePath) generatedDstFilePathSet.Add(dstFilePath)
for _, file := range files { for _, file := range files {
var packageItems []packageItem
fileContent = gfile.GetContents(file) fileContent = gfile.GetContents(file)
fileContent, err := gregex.ReplaceString(`/[/|\*](.+)`, "", fileContent) // remove all comments.
fileContent, err = gregex.ReplaceString(`/[/|\*](.+)`, "", fileContent)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Calculate imported packages of source go files. // Calculate imported packages of source go files.
err = c.calculateImportedPackages(fileContent, srcImportedPackages) packageItems, err = c.calculateImportedPackages(fileContent)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// try finding the conflicts imports between files.
for _, item := range packageItems {
alias := item.Alias
if alias == "" {
alias = gfile.Basename(gstr.Trim(item.Path, `"`))
}
importPath := importPackageItemAliasMap.Get(alias)
if importPath == "" {
importPackageItemAliasMap.Set(alias, item.Path)
srcImportedPackages.Add(item.RawImport)
continue
}
if importPath != item.Path {
// update the conflicted alias with suffix.
item.Alias = fmt.Sprintf(`%s%d`, alias, aliasIndex)
aliasIndex++
importPackageItemAliasMap.Set(item.Alias, item.Path)
item.RawImport = fmt.Sprintf(`%s %s`, item.Alias, item.Path)
// update the file content with new alias import.
fileContent, err = gregex.ReplaceStringFuncMatch(
fmt.Sprintf(`([^\w])%s(\.\w+)`, alias), fileContent,
func(match []string) string {
return match[1] + item.Alias + match[2]
},
)
if err != nil {
return nil, err
}
srcImportedPackages.Add(item.RawImport)
}
}
// Calculate functions and interfaces for service generating. // Calculate functions and interfaces for service generating.
err = c.calculateInterfaceFunctions(in, fileContent, srcPkgInterfaceMap, dstPackageName) err = c.calculateInterfaceFunctions(in, fileContent, srcPkgInterfaceMap)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} }
initImportSrcPackages = append( initImportSrcPackages = append(
initImportSrcPackages, initImportSrcPackages,
fmt.Sprintf(`%s/%s`, in.ImportPrefix, srcPackageName), fmt.Sprintf(`%s/%s`, in.ImportPrefix, srcPackageName),
@ -222,7 +250,7 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
) )
continue continue
} }
// Generating service go file for logic. // Generating service go file for single logic package.
if ok, err = c.generateServiceFile(generateServiceFilesInput{ if ok, err = c.generateServiceFile(generateServiceFilesInput{
CGenServiceInput: in, CGenServiceInput: in,
SrcStructFunctions: srcPkgInterfaceMap, SrcStructFunctions: srcPkgInterfaceMap,
@ -271,6 +299,56 @@ func (c CGenService) Service(ctx context.Context, in CGenServiceInput) (out *CGe
utils.GoFmt(in.DstFolder) utils.GoFmt(in.DstFolder)
} }
// auto update main.go.
if err = c.checkAndUpdateMain(in.SrcFolder); err != nil {
return nil, err
}
mlog.Print(`done!`) mlog.Print(`done!`)
return return
} }
func (c CGenService) checkAndUpdateMain(srcFolder string) (err error) {
var (
logicPackageName = gstr.ToLower(gfile.Basename(srcFolder))
logicFilePath = gfile.Join(srcFolder, logicPackageName+".go")
importPath = utils.GetImportPath(logicFilePath)
importStr = fmt.Sprintf(`_ "%s"`, importPath)
mainFilePath = gfile.Join(gfile.Dir(gfile.Dir(gfile.Dir(logicFilePath))), "main.go")
mainFileContent = gfile.GetContents(mainFilePath)
)
if gstr.Contains(mainFileContent, importStr) {
return nil
}
match, err := gregex.MatchString(`import \(([\s\S]+?)\)`, mainFileContent)
if err != nil {
return err
}
lines := garray.NewStrArrayFrom(gstr.Split(match[1], "\n"))
for i, line := range lines.Slice() {
line = gstr.Trim(line)
if len(line) == 0 {
continue
}
if line[0] == '_' {
continue
}
// Insert the logic import into imports.
if err = lines.InsertBefore(i, fmt.Sprintf("\t%s\n\n", importStr)); err != nil {
return err
}
break
}
mainFileContent, err = gregex.ReplaceString(
`import \(([\s\S]+?)\)`,
fmt.Sprintf(`import (%s)`, lines.Join("\n")),
mainFileContent,
)
if err != nil {
return err
}
mlog.Print(`update main.go`)
err = gfile.PutContents(mainFilePath, mainFileContent)
utils.GoFmt(mainFilePath)
return
}

View File

@ -15,29 +15,44 @@ import (
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
) )
func (c CGenService) calculateImportedPackages(fileContent string, srcImportedPackages *garray.SortedStrArray) (err error) { type packageItem struct {
Alias string
Path string
RawImport string
}
func (c CGenService) calculateImportedPackages(fileContent string) (packages []packageItem, err error) {
f, err := parser.ParseFile(token.NewFileSet(), "", fileContent, parser.ImportsOnly) f, err := parser.ParseFile(token.NewFileSet(), "", fileContent, parser.ImportsOnly)
if err != nil { if err != nil {
return err return nil, err
} }
packages = make([]packageItem, 0)
for _, s := range f.Imports { for _, s := range f.Imports {
if s.Path != nil { if s.Path != nil {
if s.Name != nil { if s.Name != nil {
// If it has alias, and it is not `_`. // If it has alias, and it is not `_`.
if pkgAlias := s.Name.String(); pkgAlias != "_" { if pkgAlias := s.Name.String(); pkgAlias != "_" {
srcImportedPackages.Add(pkgAlias + " " + s.Path.Value) packages = append(packages, packageItem{
Alias: pkgAlias,
Path: s.Path.Value,
RawImport: pkgAlias + " " + s.Path.Value,
})
} }
} else { } else {
// no alias // no alias
srcImportedPackages.Add(s.Path.Value) packages = append(packages, packageItem{
Alias: "",
Path: s.Path.Value,
RawImport: s.Path.Value,
})
} }
} }
} }
return nil return packages, nil
} }
func (c CGenService) calculateInterfaceFunctions( func (c CGenService) calculateInterfaceFunctions(
in CGenServiceInput, fileContent string, srcPkgInterfaceMap map[string]*garray.StrArray, dstPackageName string, in CGenServiceInput, fileContent string, srcPkgInterfaceMap map[string]*garray.StrArray,
) (err error) { ) (err error) {
var ( var (
ok bool ok bool

View File

@ -151,29 +151,30 @@ func (c CGenService) isToGenerateServiceGoFile(dstPackageName, filePath string,
return false return false
} }
// generateInitializationFile generates `logic.go`.
func (c CGenService) generateInitializationFile(in CGenServiceInput, importSrcPackages []string) (err error) { func (c CGenService) generateInitializationFile(in CGenServiceInput, importSrcPackages []string) (err error) {
var ( var (
srcPackageName = gstr.ToLower(gfile.Basename(in.SrcFolder)) logicPackageName = gstr.ToLower(gfile.Basename(in.SrcFolder))
srcFilePath = gfile.Join(in.SrcFolder, srcPackageName+".go") logicFilePath = gfile.Join(in.SrcFolder, logicPackageName+".go")
srcImports string logicImports string
generatedContent string generatedContent string
) )
if !utils.IsFileDoNotEdit(srcFilePath) { if !utils.IsFileDoNotEdit(logicFilePath) {
mlog.Debugf(`ignore file as it is manually maintained: %s`, srcFilePath) mlog.Debugf(`ignore file as it is manually maintained: %s`, logicFilePath)
return nil return nil
} }
for _, importSrcPackage := range importSrcPackages { for _, importSrcPackage := range importSrcPackages {
srcImports += fmt.Sprintf(`%s_ "%s"%s`, "\t", importSrcPackage, "\n") logicImports += fmt.Sprintf(`%s_ "%s"%s`, "\t", importSrcPackage, "\n")
} }
generatedContent = gstr.ReplaceByMap(consts.TemplateGenServiceLogicContent, g.MapStrStr{ generatedContent = gstr.ReplaceByMap(consts.TemplateGenServiceLogicContent, g.MapStrStr{
"{PackageName}": srcPackageName, "{PackageName}": logicPackageName,
"{Imports}": srcImports, "{Imports}": logicImports,
}) })
mlog.Printf(`generating init go file: %s`, srcFilePath) mlog.Printf(`generating init go file: %s`, logicFilePath)
if err = gfile.PutContents(srcFilePath, generatedContent); err != nil { if err = gfile.PutContents(logicFilePath, generatedContent); err != nil {
return err return err
} }
utils.GoFmt(srcFilePath) utils.GoFmt(logicFilePath)
return nil return nil
} }

View File

@ -0,0 +1,65 @@
// Copyright GoFrame gf 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 consts
const TemplateGenCtrlControllerEmpty = `
package {Module}
`
const TemplateGenCtrlControllerNewEmpty = `
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package {Module}
import (
{ImportPath}
)
`
const TemplateGenCtrlControllerNewFunc = `
type {CtrlName} struct{}
func {NewFuncName}() {InterfaceName} {
return &{CtrlName}{}
}
`
const TemplateGenCtrlControllerMethodFunc = `
package {Module}
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"{ImportPath}"
)
func (c *{CtrlName}) {MethodName}(ctx context.Context, req *{Version}.{MethodName}Req) (res *{Version}.{MethodName}Res, err error) {
return nil, gerror.NewCode(gcode.CodeNotImplemented)
}
`
const TemplateGenCtrlApiInterface = `
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package {Module}
import (
{ImportPaths}
)
{Interfaces}
`

View File

@ -0,0 +1,94 @@
// Copyright GoFrame gf 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 consts
const TemplateGenCtrlSdkPkgNew = `
// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================
package {PkgName}
import (
"fmt"
"github.com/gogf/gf/contrib/sdk/httpclient/v2"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gstr"
)
type implementer struct {
config httpclient.Config
}
func New(config httpclient.Config) iClient {
if !gstr.HasPrefix(config.URL, "http") {
config.URL = fmt.Sprintf("http://%s", config.URL)
}
if config.Logger == nil {
config.Logger = g.Log()
}
return &implementer{
config: config,
}
}
`
const TemplateGenCtrlSdkIClient = `
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package {PkgName}
import (
)
type iClient interface {
}
`
const TemplateGenCtrlSdkImplementer = `
// =================================================================================
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// =================================================================================
package {PkgName}
import (
"context"
"github.com/gogf/gf/contrib/sdk/httpclient/v2"
"github.com/gogf/gf/v2/text/gstr"
{ImportPaths}
)
type implementer{ImplementerName} struct {
*httpclient.Client
}
`
const TemplateGenCtrlSdkImplementerNew = `
func (i *implementer) {ImplementerName}() {Module}.I{ImplementerName} {
var (
client = httpclient.New(i.config)
prefix = gstr.TrimRight(i.config.URL, "/") + "{VersionPrefix}"
)
client.Client = client.Prefix(prefix)
return &implementer{ImplementerName}{client}
}
`
const TemplateGenCtrlSdkImplementerFunc = `
func (i *implementer{ImplementerName}) {MethodName}(ctx context.Context, req *{Version}.{MethodName}Req) (res *{Version}.{MethodName}Res, err error) {
err = i.Request(ctx, req, &res)
return
}
`

View File

@ -39,7 +39,7 @@ var (
const TemplateGenDaoInternalContent = ` const TemplateGenDaoInternalContent = `
// ========================================================================== // ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr} // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr}
// ========================================================================== // ==========================================================================
package internal package internal

View File

@ -8,7 +8,7 @@ package consts
const TemplateGenDaoDoContent = ` const TemplateGenDaoDoContent = `
// ================================================================================= // =================================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr} // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr}
// ================================================================================= // =================================================================================
package do package do

View File

@ -8,7 +8,7 @@ package consts
const TemplateGenDaoEntityContent = ` const TemplateGenDaoEntityContent = `
// ================================================================================= // =================================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr} // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT. {TplCreatedAtDatetimeStr}
// ================================================================================= // =================================================================================
package entity package entity

View File

@ -8,7 +8,7 @@ package consts
const TemplateGenEnums = ` const TemplateGenEnums = `
// ================================================================================ // ================================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ================================================================================ // ================================================================================
package {PackageName} package {PackageName}

View File

@ -8,7 +8,7 @@ package consts
const TemplatePbEntityMessageContent = ` const TemplatePbEntityMessageContent = `
// ========================================================================== // ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ========================================================================== // ==========================================================================
syntax = "proto3"; syntax = "proto3";

View File

@ -8,7 +8,7 @@ package consts
const TemplateGenServiceContentHead = ` const TemplateGenServiceContentHead = `
// ================================================================================ // ================================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// You can delete these comments if you wish manually maintain this interface file. // You can delete these comments if you wish manually maintain this interface file.
// ================================================================================ // ================================================================================

View File

@ -8,7 +8,7 @@ package consts
const TemplateGenServiceLogicContent = ` const TemplateGenServiceLogicContent = `
// ========================================================================== // ==========================================================================
// Code generated by GoFrame CLI tool. DO NOT EDIT. // Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
// ========================================================================== // ==========================================================================
package {PackageName} package {PackageName}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -111,6 +111,8 @@ func (s serviceInstall) Run(ctx context.Context) (err error) {
) )
if input != "" { if input != "" {
inputID = gconv.Int(input) inputID = gconv.Int(input)
} else {
break
} }
// Check if out of range. // Check if out of range.
if inputID >= len(paths) || inputID < 0 { if inputID >= len(paths) || inputID < 0 {
@ -148,7 +150,7 @@ func (s serviceInstall) IsInstalled() (*serviceInstallAvailablePath, bool) {
return nil, false return nil, false
} }
// getGoPathBinFilePath retrieves ad returns the GOPATH/bin path for binary. // getGoPathBin retrieves ad returns the GOPATH/bin path for binary.
func (s serviceInstall) getGoPathBin() string { func (s serviceInstall) getGoPathBin() string {
if goPath := genv.Get(`GOPATH`).String(); goPath != "" { if goPath := genv.Get(`GOPATH`).String(); goPath != "" {
return gfile.Join(goPath, "bin") return gfile.Join(goPath, "bin")

View File

@ -15,6 +15,7 @@ import (
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc" "github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
) )
@ -72,3 +73,43 @@ func ReplaceGeneratedContentGFV2(folderPath string) (err error) {
return content return content
}, folderPath, "*.go", true) }, folderPath, "*.go", true)
} }
// GetImportPath calculates and returns the golang import path for given `filePath`.
// Note that it needs a `go.mod` in current working directory or parent directories to detect the path.
func GetImportPath(filePath string) string {
// If `filePath` does not exist, create it firstly to find the import path.
var realPath = gfile.RealPath(filePath)
if realPath == "" {
_ = gfile.Mkdir(filePath)
realPath = gfile.RealPath(filePath)
}
var (
newDir = gfile.Dir(realPath)
oldDir string
suffix string
goModName = "go.mod"
goModPath string
importPath string
)
if gfile.IsDir(filePath) {
suffix = gfile.Basename(filePath)
}
for {
goModPath = gfile.Join(newDir, goModName)
if gfile.Exists(goModPath) {
match, _ := gregex.MatchString(`^module\s+(.+)\s*`, gfile.GetContents(goModPath))
importPath = gstr.Trim(match[1]) + "/" + suffix
importPath = gstr.Replace(importPath, `\`, `/`)
importPath = gstr.TrimRight(importPath, `/`)
return importPath
}
oldDir = newDir
newDir = gfile.Dir(oldDir)
if newDir == oldDir {
return ""
}
suffix = gfile.Basename(oldDir) + "/" + suffix
}
}

View File

@ -7,92 +7,22 @@
package main package main
import ( import (
_ "github.com/gogf/gf/cmd/gf/v2/internal/packed" "github.com/gogf/gf/cmd/gf/v2/gfcmd"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcfg"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/cmd/gf/v2/internal/cmd"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog" "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
) "github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/gctx"
const (
cliFolderName = `hack`
) )
func main() { func main() {
defer func() {
if exception := recover(); exception != nil {
if err, ok := exception.(error); ok {
mlog.Print(err.Error())
} else {
panic(exception)
}
}
}()
// CLI configuration.
if path, _ := gfile.Search(cliFolderName); path != "" {
if adapter, ok := g.Cfg().GetAdapter().(*gcfg.AdapterFile); ok {
if err := adapter.SetPath(path); err != nil {
mlog.Fatal(err)
}
}
}
// zsh alias "git fetch" conflicts checks.
handleZshAlias()
// -y option checks.
allyes.Init()
var ( var (
ctx = gctx.New() ctx = gctx.GetInitCtx()
) )
command, err := gcmd.NewFromObject(cmd.GF) command, err := gfcmd.GetCommand(ctx)
if err != nil { if err != nil {
panic(err) mlog.Fatalf(`%+v`, err)
} }
err = command.AddObject( if command == nil {
cmd.Up, panic(gerror.New(`retrieve root command failed for "gf"`))
cmd.Env,
cmd.Fix,
cmd.Run,
cmd.Gen,
cmd.Tpl,
cmd.Init,
cmd.Pack,
cmd.Build,
cmd.Docker,
cmd.Install,
cmd.Version,
)
if err != nil {
panic(err)
}
err = command.RunWithError(ctx)
if err != nil {
panic(err)
}
}
// zsh alias "git fetch" conflicts checks.
func handleZshAlias() {
if home, err := gfile.Home(); err == nil {
zshPath := gfile.Join(home, ".zshrc")
if gfile.Exists(zshPath) {
var (
aliasCommand = `alias gf=gf`
content = gfile.GetContents(zshPath)
)
if !gstr.Contains(content, aliasCommand) {
_ = gfile.PutContentsAppend(zshPath, "\n"+aliasCommand+"\n")
}
}
} }
command.Run(ctx)
} }

View File

@ -642,6 +642,7 @@ func TestIntArray_Json(t *testing.T) {
a2 := garray.NewIntArray() a2 := garray.NewIntArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s1) t.Assert(a2.Slice(), s1)
var a3 garray.IntArray var a3 garray.IntArray
@ -660,6 +661,7 @@ func TestIntArray_Json(t *testing.T) {
a2 := garray.NewIntArray() a2 := garray.NewIntArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s1) t.Assert(a2.Slice(), s1)
var a3 garray.IntArray var a3 garray.IntArray

View File

@ -654,6 +654,7 @@ func TestStrArray_Json(t *testing.T) {
a2 := garray.NewStrArray() a2 := garray.NewStrArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s1) t.Assert(a2.Slice(), s1)
var a3 garray.StrArray var a3 garray.StrArray
@ -672,6 +673,7 @@ func TestStrArray_Json(t *testing.T) {
a2 := garray.NewStrArray() a2 := garray.NewStrArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s1) t.Assert(a2.Slice(), s1)
var a3 garray.StrArray var a3 garray.StrArray

View File

@ -710,6 +710,7 @@ func TestSortedArray_Json(t *testing.T) {
a2 := garray.NewSortedArray(gutil.ComparatorString) a2 := garray.NewSortedArray(gutil.ComparatorString)
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
var a3 garray.SortedArray var a3 garray.SortedArray
@ -730,6 +731,7 @@ func TestSortedArray_Json(t *testing.T) {
a2 := garray.NewSortedArray(gutil.ComparatorString) a2 := garray.NewSortedArray(gutil.ComparatorString)
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
var a3 garray.SortedArray var a3 garray.SortedArray

View File

@ -613,6 +613,7 @@ func TestSortedIntArray_Json(t *testing.T) {
a2 := garray.NewSortedIntArray() a2 := garray.NewSortedIntArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
var a3 garray.SortedIntArray var a3 garray.SortedIntArray
@ -632,6 +633,7 @@ func TestSortedIntArray_Json(t *testing.T) {
a2 := garray.NewSortedIntArray() a2 := garray.NewSortedIntArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
var a3 garray.SortedIntArray var a3 garray.SortedIntArray

View File

@ -622,6 +622,7 @@ func TestSortedStrArray_Json(t *testing.T) {
a2 := garray.NewSortedStrArray() a2 := garray.NewSortedStrArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
t.Assert(a2.Interfaces(), s2) t.Assert(a2.Interfaces(), s2)
@ -643,6 +644,7 @@ func TestSortedStrArray_Json(t *testing.T) {
a2 := garray.NewSortedStrArray() a2 := garray.NewSortedStrArray()
err1 = json.UnmarshalUseNumber(b2, &a2) err1 = json.UnmarshalUseNumber(b2, &a2)
t.AssertNil(err1)
t.Assert(a2.Slice(), s2) t.Assert(a2.Slice(), s2)
t.Assert(a2.Interfaces(), s2) t.Assert(a2.Interfaces(), s2)

View File

@ -631,10 +631,7 @@ func TestList_IteratorAsc(t *testing.T) {
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
if gconv.Int(e1.Value) > 2 { return gconv.Int(e1.Value) > 2
return true
}
return false
} }
checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1}) checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1})
l.IteratorAsc(fun1) l.IteratorAsc(fun1)
@ -649,10 +646,7 @@ func TestList_IteratorDesc(t *testing.T) {
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
if gconv.Int(e1.Value) > 6 { return gconv.Int(e1.Value) > 6
return true
}
return false
} }
l.IteratorDesc(fun1) l.IteratorDesc(fun1)
t.Assert(l.Len(), 4) t.Assert(l.Len(), 4)
@ -667,10 +661,7 @@ func TestList_Iterator(t *testing.T) {
l.PushFronts(a1) l.PushFronts(a1)
e1 := l.Back() e1 := l.Back()
fun1 := func(e *Element) bool { fun1 := func(e *Element) bool {
if gconv.String(e1.Value) > "c" { return gconv.String(e1.Value) > "c"
return true
}
return false
} }
checkList(t, l, []interface{}{"e", "d", "c", "b", "a"}) checkList(t, l, []interface{}{"e", "d", "c", "b", "a"})
l.Iterator(fun1) l.Iterator(fun1)

View File

@ -102,7 +102,7 @@ func ExampleQueue_Close() {
fmt.Println(q.Len()) fmt.Println(q.Len())
fmt.Println(q.Pop()) fmt.Println(q.Pop())
// Output: // May Output:
// 0 // 0
// <nil> // <nil>
} }

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/apolloconfig/agollo/v4 v4.1.1 github.com/apolloconfig/agollo/v4 v4.1.1
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2
go 1.18 go 1.18
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
k8s.io/api v0.25.2 k8s.io/api v0.25.2
k8s.io/apimachinery v0.25.2 k8s.io/apimachinery v0.25.2
k8s.io/client-go v0.25.2 k8s.io/client-go v0.25.2

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/nacos-group/nacos-sdk-go v1.1.2 github.com/nacos-group/nacos-sdk-go v1.1.2
) )

View File

@ -3,8 +3,13 @@ module github.com/gogf/gf/contrib/config/polaris/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/polarismesh/polaris-go v1.3.0 github.com/polarismesh/polaris-go v1.4.3
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../
replace (
golang.org/x/net v0.2.0 => golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad
golang.org/x/sys v0.2.0 => golang.org/x/sys v0.0.0-20220906165534-d0df966e6959
)

View File

@ -227,8 +227,10 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/polarismesh/polaris-go v1.3.0 h1:KZKX//ow4OPPoS5+s7h07ptprg+2AcNVGrN6WakC9QM= github.com/polarismesh/polaris-go v1.4.3 h1:Ka2ancA4BCLt4pxhEJdRIHMWaj+wkwtw+4AlrSI24c0=
github.com/polarismesh/polaris-go v1.3.0/go.mod h1:HsN0ierETIujHpmnnYJ3qkwQw4QGAECuHvBZTDaw1tI= github.com/polarismesh/polaris-go v1.4.3/go.mod h1:ymxU5F20Bs99P+jvt5tbLn5guOEt1JmT4i69AOmZSVI=
github.com/polarismesh/specification v1.2.1 h1:NcFoinO+aSWIOIyKTAhvEbjaPvZAAm5/DwJAL2FGdXs=
github.com/polarismesh/specification v1.2.1/go.mod h1:rDvMMtl5qebPmqiBLNa5Ps0XtwkP31ZLirbH4kXA0YU=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
@ -276,6 +278,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
@ -302,6 +305,7 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@ -333,8 +337,9 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@ -364,12 +369,14 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad h1:Zx6wVVDwwNJFWXNIvDi7o952w3/1ckSwYk/7eykRmjM=
golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad/go.mod h1:RpDiru2p0u2F0lLpEoqnP2+7xs0ifAuOcJ442g6GU2s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@ -386,6 +393,7 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -430,11 +438,13 @@ golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220906165534-d0df966e6959 h1:qSa+Hg9oBe6UJXrznE+yYvW51V9UbyIj/nj/KpDigo8=
golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@ -445,8 +455,9 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 h1:GLw7MR8AfAG2GmGcmVgObFOHXYypgGjnGno25RDwn3Y=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0= golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0=
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@ -492,8 +503,9 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@ -568,8 +580,8 @@ google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM
google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0=
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc v1.46.2 h1:u+MLGgVf7vRdjEYZ8wDFhAVNmhkbJ5hmrA1LMWK1CAQ= google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U=
google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
@ -583,8 +595,9 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/ClickHouse/clickhouse-go/v2 v2.0.15 github.com/ClickHouse/clickhouse-go/v2 v2.0.15
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
github.com/shopspring/decimal v1.3.1 github.com/shopspring/decimal v1.3.1
) )

View File

@ -6,5 +6,5 @@ replace github.com/gogf/gf/v2 => ../../../
require ( require (
gitee.com/chunanyong/dm v1.8.10 gitee.com/chunanyong/dm v1.8.10
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
) )

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/denisenkom/go-mssqldb v0.11.0 github.com/denisenkom/go-mssqldb v0.11.0
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../

View File

@ -20,6 +20,7 @@ import (
"strings" "strings"
_ "github.com/denisenkom/go-mssqldb" _ "github.com/denisenkom/go-mssqldb"
"github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/errors/gerror"
@ -285,7 +286,6 @@ ORDER BY a.id,a.colorder`,
} }
fields = make(map[string]*gdb.TableField) fields = make(map[string]*gdb.TableField)
for i, m := range result { for i, m := range result {
fields[m["Field"].String()] = &gdb.TableField{ fields[m["Field"].String()] = &gdb.TableField{
Index: i, Index: i,
Name: m["Field"].String(), Name: m["Field"].String(),

View File

@ -256,7 +256,6 @@ func Test_DB_Insert(t *testing.T) {
t.Assert(one["PASSPORT"].String(), "t4") t.Assert(one["PASSPORT"].String(), "t4")
t.Assert(one["PASSWORD"].String(), "25d55ad283aa400af464c76d713c07ad") t.Assert(one["PASSWORD"].String(), "25d55ad283aa400af464c76d713c07ad")
t.Assert(one["NICKNAME"].String(), "name_4") t.Assert(one["NICKNAME"].String(), "name_4")
t.Assert(one["CREATE_TIME"].GTime(), timeNow)
// batch with Insert // batch with Insert
timeNow = gtime.Now() timeNow = gtime.Now()

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/go-sql-driver/mysql v1.6.0 github.com/go-sql-driver/mysql v1.6.0
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../

View File

@ -76,6 +76,7 @@ func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source) source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source)
} }
} else { } else {
// TODO: Do not set charset when charset is not specified (in v2.5.0)
source = fmt.Sprintf( source = fmt.Sprintf(
"%s:%s@%s(%s:%s)/%s?charset=%s", "%s:%s@%s(%s:%s)/%s?charset=%s",
config.User, config.Pass, config.Protocol, config.Host, config.Port, config.Name, config.Charset, config.User, config.Pass, config.Protocol, config.Host, config.Port, config.Name, config.Charset,

View File

@ -11,6 +11,7 @@ import (
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest" "github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
) )
@ -128,7 +129,7 @@ func Test_Model_Update_Data_DO(t *testing.T) {
func Test_Model_Update_Pointer_Data_DO(t *testing.T) { func Test_Model_Update_Pointer_Data_DO(t *testing.T) {
table := createInitTable() table := createInitTable()
defer dropTable(table) defer dropTable(table)
db.SetDebug(true)
gtest.C(t, func(t *gtest.T) { gtest.C(t, func(t *gtest.T) {
type NN string type NN string
type Req struct { type Req struct {
@ -329,3 +330,61 @@ func Test_Model_Where_ForDao(t *testing.T) {
t.Assert(one[`nickname`], `name_1`) t.Assert(one[`nickname`], `name_1`)
}) })
} }
func Test_Model_Where_FieldPrefix(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
array := gstr.SplitAndTrim(gtest.DataContent(`table_with_prefix.sql`), ";")
for _, v := range array {
if _, err := db.Exec(ctx, v); err != nil {
gtest.Error(err)
}
}
defer dropTable("instance")
type Instance struct {
ID int `orm:"f_id"`
Name string
}
type InstanceDo struct {
g.Meta `orm:"table:instance, do:true"`
ID interface{} `orm:"f_id"`
}
var instance *Instance
err := db.Model("instance").Where(InstanceDo{
ID: 1,
}).Scan(&instance)
t.AssertNil(err)
t.AssertNE(instance, nil)
t.Assert(instance.ID, 1)
t.Assert(instance.Name, "john")
})
// With omitempty.
gtest.C(t, func(t *gtest.T) {
array := gstr.SplitAndTrim(gtest.DataContent(`table_with_prefix.sql`), ";")
for _, v := range array {
if _, err := db.Exec(ctx, v); err != nil {
gtest.Error(err)
}
}
defer dropTable("instance")
type Instance struct {
ID int `orm:"f_id,omitempty"`
Name string
}
type InstanceDo struct {
g.Meta `orm:"table:instance, do:true"`
ID interface{} `orm:"f_id,omitempty"`
}
var instance *Instance
err := db.Model("instance").Where(InstanceDo{
ID: 1,
}).Scan(&instance)
t.AssertNil(err)
t.AssertNE(instance, nil)
t.Assert(instance.ID, 1)
t.Assert(instance.Name, "john")
})
}

View File

@ -664,3 +664,99 @@ CREATE TABLE %s (
t.AssertNil(err3) t.AssertNil(err3)
}) })
} }
// https://github.com/gogf/gf/issues/2561
func Test_Issue2561(t *testing.T) {
table := createTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
g.Meta `orm:"do:true"`
Id interface{}
Passport interface{}
Password interface{}
Nickname interface{}
CreateTime interface{}
}
data := g.Slice{
User{
Id: 1,
Passport: "user_1",
},
User{
Id: 2,
Password: "pass_2",
},
User{
Id: 3,
Password: "pass_3",
},
}
result, err := db.Model(table).Data(data).Insert()
t.AssertNil(err)
m, _ := result.LastInsertId()
t.Assert(m, 3)
n, _ := result.RowsAffected()
t.Assert(n, 3)
one, err := db.Model(table).WherePri(1).One()
t.AssertNil(err)
t.Assert(one[`id`], `1`)
t.Assert(one[`passport`], `user_1`)
t.Assert(one[`password`], ``)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
one, err = db.Model(table).WherePri(2).One()
t.AssertNil(err)
t.Assert(one[`id`], `2`)
t.Assert(one[`passport`], ``)
t.Assert(one[`password`], `pass_2`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
one, err = db.Model(table).WherePri(3).One()
t.AssertNil(err)
t.Assert(one[`id`], `3`)
t.Assert(one[`passport`], ``)
t.Assert(one[`password`], `pass_3`)
t.Assert(one[`nickname`], ``)
t.Assert(one[`create_time`], ``)
})
}
// https://github.com/gogf/gf/issues/2439
func Test_Issue2439(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
array := gstr.SplitAndTrim(gtest.DataContent(`issue2439.sql`), ";")
for _, v := range array {
if _, err := db.Exec(ctx, v); err != nil {
gtest.Error(err)
}
}
defer dropTable("a")
defer dropTable("b")
defer dropTable("c")
orm := db.Model("a")
orm = orm.InnerJoin(
"c", "a.id=c.id",
)
orm = orm.InnerJoinOnField("b", "id")
whereFormat := fmt.Sprintf(
"(`%s`.`%s` LIKE ?) ",
"b", "name",
)
orm = orm.WhereOrf(
whereFormat,
"%a%",
)
r, err := orm.All()
t.AssertNil(err)
t.Assert(len(r), 1)
t.Assert(r[0]["id"], 2)
t.Assert(r[0]["name"], "a")
})
}

View File

@ -0,0 +1,19 @@
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB;
INSERT INTO `a` (`id`) VALUES ('2');
CREATE TABLE `b` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL ,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB;
INSERT INTO `b` (`id`, `name`) VALUES ('2', 'a');
INSERT INTO `b` (`id`, `name`) VALUES ('3', 'b');
CREATE TABLE `c` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB;
INSERT INTO `c` (`id`) VALUES ('2');

View File

@ -0,0 +1,7 @@
CREATE TABLE `instance` (
`f_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NULL DEFAULT '',
PRIMARY KEY (`f_id`) USING BTREE
) ENGINE = InnoDB;
INSERT INTO `instance` VALUES (1, 'john');

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/oracle/v2
go 1.17 go 1.17
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/sijms/go-ora/v2 v2.4.20 github.com/sijms/go-ora/v2 v2.4.20
) )

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/drivers/pgsql/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/lib/pq v1.10.4 github.com/lib/pq v1.10.4
) )

View File

@ -17,6 +17,8 @@ import (
"fmt" "fmt"
"strings" "strings"
_ "github.com/lib/pq"
"github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror" "github.com/gogf/gf/v2/errors/gerror"
@ -25,7 +27,6 @@ import (
"github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gutil" "github.com/gogf/gf/v2/util/gutil"
_ "github.com/lib/pq"
) )
// Driver is the driver for postgresql database. // Driver is the driver for postgresql database.
@ -273,9 +274,10 @@ ORDER BY
// Also see DriverMysql.TableFields. // Also see DriverMysql.TableFields.
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) { func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
var ( var (
result gdb.Result result gdb.Result
link gdb.Link link gdb.Link
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...) usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
// TODO duplicated `id` result?
structureSql = fmt.Sprintf(` structureSql = fmt.Sprintf(`
SELECT a.attname AS field, t.typname AS type,a.attnotnull as null, SELECT a.attname AS field, t.typname AS type,a.attnotnull as null,
(case when d.contype is not null then 'pri' else '' end) as key (case when d.contype is not null then 'pri' else '' end) as key
@ -302,16 +304,27 @@ ORDER BY a.attnum`,
return nil, err return nil, err
} }
fields = make(map[string]*gdb.TableField) fields = make(map[string]*gdb.TableField)
for i, m := range result { var (
fields[m["field"].String()] = &gdb.TableField{ index = 0
Index: i, name string
Name: m["field"].String(), ok bool
)
for _, m := range result {
name = m["field"].String()
// Filter duplicated fields.
if _, ok = fields[name]; ok {
continue
}
fields[name] = &gdb.TableField{
Index: index,
Name: name,
Type: m["type"].String(), Type: m["type"].String(),
Null: !m["null"].Bool(), Null: !m["null"].Bool(),
Key: m["key"].String(), Key: m["key"].String(),
Default: m["default_value"].Val(), Default: m["default_value"].Val(),
Comment: m["comment"].String(), Comment: m["comment"].String(),
} }
index++
} }
return fields, nil return fields, nil
} }

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/glebarez/go-sqlite v1.17.3 github.com/glebarez/go-sqlite v1.17.3
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../

View File

@ -20,6 +20,8 @@ import (
"github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/database/gdb" "github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/os/gtime" "github.com/gogf/gf/v2/os/gtime"
@ -571,6 +573,100 @@ func Test_Model_All(t *testing.T) {
}) })
} }
func Test_Model_AllAndCount(t *testing.T) {
table := createInitTable()
defer dropTable(table)
tableName2 := "user_" + gtime.Now().TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id INTEGER PRIMARY KEY AUTOINCREMENT
UNIQUE
NOT NULL,
name varchar(45) NULL,
age int(10)
);
`, tableName2,
)); err != nil {
gtest.AssertNil(err)
}
defer dropTable(tableName2)
r, err := db.Insert(ctx, tableName2, g.Map{
"id": 1,
"name": "table2_1",
"age": 18,
})
gtest.AssertNil(err)
n, _ := r.RowsAffected()
gtest.Assert(n, 1)
// AllAndCount with all data
gtest.C(t, func(t *gtest.T) {
result, count, err := db.Model(table).AllAndCount(false)
t.AssertNil(err)
t.Assert(len(result), TableSize)
t.Assert(count, TableSize)
})
// AllAndCount with no data
gtest.C(t, func(t *gtest.T) {
result, count, err := db.Model(table).Where("id<0").AllAndCount(false)
t.Assert(result, nil)
t.AssertNil(err)
t.Assert(count, 0)
})
// AllAndCount with page
gtest.C(t, func(t *gtest.T) {
result, count, err := db.Model(table).Page(1, 5).AllAndCount(false)
t.AssertNil(err)
t.Assert(len(result), 5)
t.Assert(count, TableSize)
})
// AllAndCount with normal result
gtest.C(t, func(t *gtest.T) {
result, count, err := db.Model(table).Where("id=?", 1).AllAndCount(false)
t.AssertNil(err)
t.Assert(count, 1)
t.Assert(result[0]["id"], 1)
t.Assert(result[0]["nickname"], "name_1")
t.Assert(result[0]["passport"], "user_1")
})
// AllAndCount with distinct
gtest.C(t, func(t *gtest.T) {
result, count, err := db.Model(table).Fields("DISTINCT nickname").AllAndCount(true)
t.AssertNil(err)
t.Assert(count, TableSize)
t.Assert(result[0]["nickname"], "name_1")
t.AssertNil(result[0]["id"])
})
// AllAndCount with Join
gtest.C(t, func(t *gtest.T) {
all, count, err := db.Model(table).As("u1").
LeftJoin(tableName2, "u2", "u2.id=u1.id").
Fields("u1.passport,u1.id,u2.name,u2.age").
Where("u1.id<2").
AllAndCount(false)
t.AssertNil(err)
t.Assert(len(all), 1)
t.Assert(len(all[0]), 4)
t.Assert(all[0]["id"], 1)
t.Assert(all[0]["age"], 18)
t.Assert(all[0]["name"], "table2_1")
t.Assert(all[0]["passport"], "user_1")
t.Assert(count, 1)
})
// AllAndCount with Join return CodeDbOperationError
gtest.C(t, func(t *gtest.T) {
all, count, err := db.Model(table).As("u1").
LeftJoin(tableName2, "u2", "u2.id=u1.id").
Fields("u1.passport,u1.id,u2.name,u2.age").
Where("u1.id<2").
AllAndCount(true)
t.AssertNE(err, nil)
t.AssertEQ(gerror.Code(err), gcode.CodeDbOperationError)
t.Assert(count, 0)
t.Assert(all, nil)
})
}
func Test_Model_Fields(t *testing.T) { func Test_Model_Fields(t *testing.T) {
tableName1 := createInitTable() tableName1 := createInitTable()
defer dropTable(tableName1) defer dropTable(tableName1)
@ -1080,6 +1176,169 @@ func Test_Model_Scan(t *testing.T) {
}) })
} }
func Test_Model_ScanAndCount(t *testing.T) {
table := createInitTable()
defer dropTable(table)
tableName2 := "user_" + gtime.Now().TimestampNanoStr()
if _, err := db.Exec(ctx, fmt.Sprintf(`
CREATE TABLE %s (
id INTEGER PRIMARY KEY AUTOINCREMENT
UNIQUE
NOT NULL,
name varchar(45) NULL,
age int(10)
);
`, tableName2,
)); err != nil {
gtest.AssertNil(err)
}
defer dropTable(tableName2)
r, err := db.Insert(ctx, tableName2, g.Map{
"id": 1,
"name": "table2_1",
"age": 18,
})
gtest.AssertNil(err)
n, _ := r.RowsAffected()
gtest.Assert(n, 1)
// ScanAndCount with normal struct result
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Password string
NickName string
CreateTime *gtime.Time
}
user := new(User)
var count int
err := db.Model(table).Where("id=1").ScanAndCount(user, &count, true)
t.AssertNil(err)
t.Assert(user.NickName, "name_1")
t.Assert(user.CreateTime.String(), CreateTime)
t.Assert(count, 1)
})
// ScanAndCount with normal array result
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Password string
NickName string
CreateTime gtime.Time
}
var users []User
var count int
err := db.Model(table).Order("id asc").ScanAndCount(&users, &count, true)
t.AssertNil(err)
t.Assert(len(users), TableSize)
t.Assert(users[0].Id, 1)
t.Assert(users[1].Id, 2)
t.Assert(users[2].Id, 3)
t.Assert(users[0].NickName, "name_1")
t.Assert(users[1].NickName, "name_2")
t.Assert(users[2].NickName, "name_3")
t.Assert(users[0].CreateTime.String(), CreateTime)
t.Assert(count, len(users))
})
// sql.ErrNoRows
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Password string
NickName string
CreateTime *gtime.Time
}
var (
user = new(User)
users = new([]*User)
)
var count1 int
var count2 int
err1 := db.Model(table).Where("id < 0").ScanAndCount(user, &count1, true)
err2 := db.Model(table).Where("id < 0").ScanAndCount(users, &count2, true)
t.Assert(count1, 0)
t.Assert(count2, 0)
t.Assert(err1, nil)
t.Assert(err2, nil)
})
// ScanAndCount with page
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Password string
NickName string
CreateTime gtime.Time
}
var users []User
var count int
err := db.Model(table).Order("id asc").Page(1, 3).ScanAndCount(&users, &count, true)
t.AssertNil(err)
t.Assert(len(users), 3)
t.Assert(count, TableSize)
})
// ScanAndCount with distinct
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Password string
NickName string
CreateTime gtime.Time
}
var users []User
var count int
err = db.Model(table).Fields("distinct id").ScanAndCount(&users, &count, true)
t.AssertNil(err)
t.Assert(len(users), 10)
t.Assert(count, TableSize)
t.Assert(users[0].Id, 1)
})
// ScanAndCount with join
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Name string
Age int
}
var users []User
var count int
err = db.Model(table).As("u1").
LeftJoin(tableName2, "u2", "u2.id=u1.id").
Fields("u1.passport,u1.id,u2.name,u2.age").
Where("u1.id<2").
ScanAndCount(&users, &count, false)
t.AssertNil(err)
t.Assert(len(users), 1)
t.Assert(count, 1)
t.AssertEQ(users[0].Name, "table2_1")
})
// ScanAndCount with join return CodeDbOperationError
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int
Passport string
Name string
Age int
}
var users []User
var count int
err = db.Model(table).As("u1").
LeftJoin(tableName2, "u2", "u2.id=u1.id").
Fields("u1.passport,u1.id,u2.name,u2.age").
Where("u1.id<2").
ScanAndCount(&users, &count, true)
t.AssertNE(err, nil)
t.Assert(gerror.Code(err), gcode.CodeDbOperationError)
t.Assert(count, 0)
t.AssertEQ(users, nil)
})
}
func Test_Model_Scan_NilSliceAttrWhenNoRecordsFound(t *testing.T) { func Test_Model_Scan_NilSliceAttrWhenNoRecordsFound(t *testing.T) {
table := createTable() table := createTable()
defer dropTable(table) defer dropTable(table)

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/go-redis/redis/v8 v8.11.5 github.com/go-redis/redis/v8 v8.11.5
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
go.opentelemetry.io/otel v1.7.0 go.opentelemetry.io/otel v1.7.0
go.opentelemetry.io/otel/trace v1.7.0 go.opentelemetry.io/otel/trace v1.7.0
) )

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/registry/etcd/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
go.etcd.io/etcd/client/v3 v3.5.4 go.etcd.io/etcd/client/v3 v3.5.4
) )

View File

@ -19,10 +19,11 @@ var (
) )
const ( const (
updateAtKey = "UpdateAt" updateAtKey = "UpdateAt"
serviceTTL = 20 * time.Second serviceTTL = 20 * time.Second
serviceUpdateInterval = 10 * time.Second serviceUpdateInterval = 10 * time.Second
defaultSeparator = "#" defaultSeparator = "#"
defaultEndpointHostPortDelimiter = "-"
) )
// Registry implements interface Registry using file. // Registry implements interface Registry using file.

View File

@ -108,6 +108,8 @@ func (r *Registry) getServiceByFilePath(filePath string) (gsvc.Service, error) {
fileContent = gfile.GetContents(filePath) fileContent = gfile.GetContents(filePath)
serviceKey = gstr.Replace(fileName, defaultSeparator, gsvc.DefaultSeparator) serviceKey = gstr.Replace(fileName, defaultSeparator, gsvc.DefaultSeparator)
) )
serviceKey = gstr.Replace(serviceKey, defaultEndpointHostPortDelimiter, gsvc.EndpointHostPortDelimiter)
serviceKey = gsvc.DefaultSeparator + serviceKey serviceKey = gsvc.DefaultSeparator + serviceKey
return gsvc.NewServiceWithKV(serviceKey, fileContent) return gsvc.NewServiceWithKV(serviceKey, fileContent)
} }

View File

@ -58,5 +58,6 @@ func (r *Registry) getServiceFileName(service gsvc.Service) string {
func (r *Registry) getServiceKeyForFile(key string) string { func (r *Registry) getServiceKeyForFile(key string) string {
key = gstr.Replace(key, gsvc.DefaultSeparator, defaultSeparator) key = gstr.Replace(key, gsvc.DefaultSeparator, defaultSeparator)
key = gstr.Trim(key, defaultSeparator) key = gstr.Trim(key, defaultSeparator)
key = gstr.Replace(key, gsvc.EndpointHostPortDelimiter, defaultEndpointHostPortDelimiter)
return key return key
} }

View File

@ -2,6 +2,6 @@ module github.com/gogf/gf/contrib/registry/file/v2
go 1.15 go 1.15
require github.com/gogf/gf/v2 v2.4.0 require github.com/gogf/gf/v2 v2.4.4
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../

View File

@ -35,10 +35,10 @@ import (
) )
func main() { func main() {
conf := config.NewDefaultConfiguration([]string{"192.168.100.222:8091"}) conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"})
// TTL egt 2*time.Second // TTL egt 2*time.Second
gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(100))) gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(10)))
s := g.Server(`hello.svc`) s := g.Server(`hello.svc`)
s.BindHandler("/", func(r *ghttp.Request) { s.BindHandler("/", func(r *ghttp.Request) {
@ -68,9 +68,9 @@ import (
) )
func main() { func main() {
conf := config.NewDefaultConfiguration([]string{"192.168.100.222:8091"}) conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"})
gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(100))) gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(10)))
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
res, err := g.Client().Get(gctx.New(), `http://hello.svc/`) res, err := g.Client().Get(gctx.New(), `http://hello.svc/`)

View File

@ -41,10 +41,10 @@ import (
) )
func main() { func main() {
conf := config.NewDefaultConfiguration([]string{"192.168.100.222:8091"}) conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"})
// TTL egt 2*time.Second // TTL egt 2*time.Second
gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(100))) gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(10)))
s := g.Server(`hello.svc`) s := g.Server(`hello.svc`)
s.BindHandler("/", func(r *ghttp.Request) { s.BindHandler("/", func(r *ghttp.Request) {
@ -75,9 +75,9 @@ import (
) )
func main() { func main() {
conf := config.NewDefaultConfiguration([]string{"192.168.100.222:8091"}) conf := config.NewDefaultConfiguration([]string{"183.47.111.80:8091"})
gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(100))) gsvc.SetRegistry(polaris.NewRegistryWithConfig(conf, polaris.WithTTL(10)))
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
res, err := g.Client().Get(gctx.New(), `http://hello.svc/`) res, err := g.Client().Get(gctx.New(), `http://hello.svc/`)

View File

@ -3,8 +3,13 @@ module github.com/gogf/gf/contrib/registry/polaris/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
github.com/polarismesh/polaris-go v1.3.0 github.com/polarismesh/polaris-go v1.4.3
) )
replace github.com/gogf/gf/v2 => ../../../ replace github.com/gogf/gf/v2 => ../../../
replace (
golang.org/x/net v0.2.0 => golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad
golang.org/x/sys v0.2.0 => golang.org/x/sys v0.0.0-20220906165534-d0df966e6959
)

View File

@ -227,8 +227,10 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/polarismesh/polaris-go v1.3.0 h1:KZKX//ow4OPPoS5+s7h07ptprg+2AcNVGrN6WakC9QM= github.com/polarismesh/polaris-go v1.4.3 h1:Ka2ancA4BCLt4pxhEJdRIHMWaj+wkwtw+4AlrSI24c0=
github.com/polarismesh/polaris-go v1.3.0/go.mod h1:HsN0ierETIujHpmnnYJ3qkwQw4QGAECuHvBZTDaw1tI= github.com/polarismesh/polaris-go v1.4.3/go.mod h1:ymxU5F20Bs99P+jvt5tbLn5guOEt1JmT4i69AOmZSVI=
github.com/polarismesh/specification v1.2.1 h1:NcFoinO+aSWIOIyKTAhvEbjaPvZAAm5/DwJAL2FGdXs=
github.com/polarismesh/specification v1.2.1/go.mod h1:rDvMMtl5qebPmqiBLNa5Ps0XtwkP31ZLirbH4kXA0YU=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
@ -276,6 +278,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
@ -302,6 +305,7 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@ -333,8 +337,9 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@ -364,12 +369,14 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad h1:Zx6wVVDwwNJFWXNIvDi7o952w3/1ckSwYk/7eykRmjM=
golang.org/x/net v0.0.0-20221019024206-cb67ada4b0ad/go.mod h1:RpDiru2p0u2F0lLpEoqnP2+7xs0ifAuOcJ442g6GU2s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@ -386,6 +393,7 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -430,11 +438,13 @@ golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220906165534-d0df966e6959 h1:qSa+Hg9oBe6UJXrznE+yYvW51V9UbyIj/nj/KpDigo8=
golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@ -445,8 +455,9 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 h1:GLw7MR8AfAG2GmGcmVgObFOHXYypgGjnGno25RDwn3Y=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0= golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0=
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@ -492,8 +503,9 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@ -568,8 +580,8 @@ google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM
google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0=
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
google.golang.org/grpc v1.46.2 h1:u+MLGgVf7vRdjEYZ8wDFhAVNmhkbJ5hmrA1LMWK1CAQ= google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U=
google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
@ -583,8 +595,9 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -47,12 +47,6 @@ type options struct {
// To show service is healthy or not. Default value is True. // To show service is healthy or not. Default value is True.
Healthy bool Healthy bool
// Deprecated: Use RegisterInstance instead.
// Service registration is performed synchronously,
// and heartbeat reporting is automatically performed
// Heartbeat enable .Not in polaris. Default value is True.
Heartbeat bool
// To show service is isolate or not. Default value is False. // To show service is isolate or not. Default value is False.
Isolate bool Isolate bool
@ -78,7 +72,6 @@ type Registry struct {
opt options opt options
provider polaris.ProviderAPI provider polaris.ProviderAPI
consumer polaris.ConsumerAPI consumer polaris.ConsumerAPI
c chan struct{}
} }
// WithNamespace with the Namespace option. // WithNamespace with the Namespace option.
@ -126,12 +119,6 @@ func WithRetryCount(retryCount int) Option {
return func(o *options) { o.RetryCount = retryCount } return func(o *options) { o.RetryCount = retryCount }
} }
// WithHeartbeat with the Heartbeat option.
// Deprecated remove in v2.4.0
func WithHeartbeat(heartbeat bool) Option {
return func(o *options) { o.Heartbeat = heartbeat }
}
// WithLogger with the Logger option. // WithLogger with the Logger option.
func WithLogger(logger glog.ILogger) Option { func WithLogger(logger glog.ILogger) Option {
return func(o *options) { o.Logger = logger } return func(o *options) { o.Logger = logger }
@ -140,13 +127,12 @@ func WithLogger(logger glog.ILogger) Option {
// New create a new registry. // New create a new registry.
func New(provider polaris.ProviderAPI, consumer polaris.ConsumerAPI, opts ...Option) gsvc.Registry { func New(provider polaris.ProviderAPI, consumer polaris.ConsumerAPI, opts ...Option) gsvc.Registry {
op := options{ op := options{
Namespace: "default", Namespace: gsvc.DefaultNamespace,
ServiceToken: "", ServiceToken: "",
Protocol: nil, Protocol: nil,
Weight: 0, Weight: 0,
Priority: 0, Priority: 0,
Healthy: true, Healthy: true,
Heartbeat: true,
Isolate: false, Isolate: false,
TTL: 0, TTL: 0,
Timeout: 0, Timeout: 0,
@ -160,7 +146,6 @@ func New(provider polaris.ProviderAPI, consumer polaris.ConsumerAPI, opts ...Opt
opt: op, opt: op,
provider: provider, provider: provider,
consumer: consumer, consumer: consumer,
c: make(chan struct{}),
} }
} }

View File

@ -7,6 +7,7 @@
package polaris package polaris
import ( import (
"bytes"
"context" "context"
"fmt" "fmt"
"strings" "strings"
@ -28,6 +29,7 @@ func (r *Registry) Search(ctx context.Context, in gsvc.SearchInput) ([]gsvc.Serv
} }
in.Prefix = service.GetPrefix() in.Prefix = service.GetPrefix()
} }
in.Prefix = trimAndReplace(in.Prefix)
// get all instances // get all instances
instancesResponse, err := r.consumer.GetAllInstances(&polaris.GetAllInstancesRequest{ instancesResponse, err := r.consumer.GetAllInstances(&polaris.GetAllInstancesRequest{
GetAllInstancesRequest: model.GetAllInstancesRequest{ GetAllInstancesRequest: model.GetAllInstancesRequest{
@ -44,7 +46,7 @@ func (r *Registry) Search(ctx context.Context, in gsvc.SearchInput) ([]gsvc.Serv
// Service filter. // Service filter.
filteredServices := make([]gsvc.Service, 0) filteredServices := make([]gsvc.Service, 0)
for _, service := range serviceInstances { for _, service := range serviceInstances {
if in.Prefix != "" && !gstr.HasPrefix(service.GetKey(), in.Prefix) { if in.Prefix != "" && !gstr.HasPrefix(trimAndReplace(service.GetKey()), in.Prefix) {
continue continue
} }
if in.Name != "" && service.GetName() != in.Name { if in.Name != "" && service.GetName() != in.Name {
@ -67,8 +69,8 @@ func (r *Registry) Search(ctx context.Context, in gsvc.SearchInput) ([]gsvc.Serv
} }
// Watch creates a watcher according to the service name. // Watch creates a watcher according to the service name.
func (r *Registry) Watch(ctx context.Context, serviceName string) (gsvc.Watcher, error) { func (r *Registry) Watch(ctx context.Context, key string) (gsvc.Watcher, error) {
return newWatcher(ctx, r.opt.Namespace, serviceName, r.consumer) return newWatcher(ctx, r.opt.Namespace, trimAndReplace(key), r.consumer)
} }
func instancesToServiceInstances(instances []model.Instance) []gsvc.Service { func instancesToServiceInstances(instances []model.Instance) []gsvc.Service {
@ -89,11 +91,18 @@ func instanceToServiceInstance(instance model.Instance) gsvc.Service {
endpoints = gsvc.NewEndpoints(fmt.Sprintf("%s:%d", instance.GetHost(), instance.GetPort())) endpoints = gsvc.NewEndpoints(fmt.Sprintf("%s:%d", instance.GetHost(), instance.GetPort()))
) )
if names != nil && len(names) > 4 { if names != nil && len(names) > 4 {
var name bytes.Buffer
for i := 3; i < len(names)-1; i++ {
name.WriteString(names[i])
if i < len(names)-2 {
name.WriteString(instanceIDSeparator)
}
}
s = &gsvc.LocalService{ s = &gsvc.LocalService{
Head: names[0], Head: names[0],
Deployment: names[1], Deployment: names[1],
Namespace: names[2], Namespace: names[2],
Name: names[3], Name: name.String(),
Version: metadata[metadataKeyVersion], Version: metadata[metadataKeyVersion],
Metadata: gconv.Map(metadata), Metadata: gconv.Map(metadata),
Endpoints: endpoints, Endpoints: endpoints,
@ -111,3 +120,10 @@ func instanceToServiceInstance(instance model.Instance) gsvc.Service {
Service: s, Service: s,
} }
} }
// trimAndReplace trims the prefix and suffix separator and replaces the separator in the middle.
func trimAndReplace(key string) string {
key = gstr.Trim(key, gsvc.DefaultSeparator)
key = gstr.Replace(key, gsvc.DefaultSeparator, instanceIDSeparator)
return key
}

View File

@ -8,7 +8,6 @@ package polaris
import ( import (
"context" "context"
"time"
"github.com/polarismesh/polaris-go" "github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model" "github.com/polarismesh/polaris-go/pkg/model"
@ -25,17 +24,18 @@ func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Ser
Service: service, Service: service,
} }
// Register logic. // Register logic.
var ( var ids = make([]string, 0, len(service.GetEndpoints()))
ids = make([]string, 0, len(service.GetEndpoints()))
serviceVersion = service.GetVersion()
)
for _, endpoint := range service.GetEndpoints() { for _, endpoint := range service.GetEndpoints() {
// medata // medata
var rmd map[string]interface{} var (
rmd map[string]interface{}
serviceName = service.GetPrefix()
serviceVersion = service.GetVersion()
)
if service.GetMetadata().IsEmpty() { if service.GetMetadata().IsEmpty() {
rmd = map[string]interface{}{ rmd = map[string]interface{}{
metadataKeyKind: gsvc.DefaultProtocol, metadataKeyKind: gsvc.DefaultProtocol,
metadataKeyVersion: service.GetVersion(), metadataKeyVersion: serviceVersion,
} }
} else { } else {
rmd = make(map[string]interface{}, len(service.GetMetadata())+2) rmd = make(map[string]interface{}, len(service.GetMetadata())+2)
@ -53,7 +53,7 @@ func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Ser
registeredService, err := r.provider.RegisterInstance( registeredService, err := r.provider.RegisterInstance(
&polaris.InstanceRegisterRequest{ &polaris.InstanceRegisterRequest{
InstanceRegisterRequest: model.InstanceRegisterRequest{ InstanceRegisterRequest: model.InstanceRegisterRequest{
Service: service.GetPrefix(), Service: serviceName,
ServiceToken: r.opt.ServiceToken, ServiceToken: r.opt.ServiceToken,
Namespace: r.opt.Namespace, Namespace: r.opt.Namespace,
Host: endpoint.Host(), Host: endpoint.Host(),
@ -73,9 +73,6 @@ func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Ser
if err != nil { if err != nil {
return nil, err return nil, err
} }
if r.opt.Heartbeat {
// r.doHeartBeat(ctx, registeredService.InstanceID, service, endpoint)
}
ids = append(ids, registeredService.InstanceID) ids = append(ids, registeredService.InstanceID)
} }
// need to set InstanceID for Deregister // need to set InstanceID for Deregister
@ -85,7 +82,6 @@ func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Ser
// Deregister the registration. // Deregister the registration.
func (r *Registry) Deregister(ctx context.Context, service gsvc.Service) error { func (r *Registry) Deregister(ctx context.Context, service gsvc.Service) error {
// r.c <- struct{}{}
var ( var (
err error err error
split = gstr.Split(service.(*Service).ID, instanceIDSeparator) split = gstr.Split(service.(*Service).ID, instanceIDSeparator)
@ -112,37 +108,3 @@ func (r *Registry) Deregister(ctx context.Context, service gsvc.Service) error {
} }
return nil return nil
} }
// Deprecated .
func (r *Registry) doHeartBeat(ctx context.Context, instanceID string, service gsvc.Service, endpoint gsvc.Endpoint) {
go func() {
ticker := time.NewTicker(time.Second * time.Duration(r.opt.TTL))
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := r.provider.Heartbeat(&polaris.InstanceHeartbeatRequest{
InstanceHeartbeatRequest: model.InstanceHeartbeatRequest{
Service: service.GetPrefix(),
Namespace: r.opt.Namespace,
Host: endpoint.Host(),
Port: endpoint.Port(),
ServiceToken: r.opt.ServiceToken,
InstanceID: instanceID,
Timeout: &r.opt.Timeout,
RetryCount: &r.opt.RetryCount,
},
})
if err != nil {
r.opt.Logger.Error(ctx, err.Error())
continue
}
r.opt.Logger.Debug(ctx, "heartbeat success")
case <-r.c:
r.opt.Logger.Debug(ctx, "stop heartbeat")
return
}
}
}()
}

View File

@ -9,9 +9,10 @@ package polaris
import ( import (
"context" "context"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/polarismesh/polaris-go" "github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model" "github.com/polarismesh/polaris-go/pkg/model"
"github.com/gogf/gf/v2/net/gsvc"
) )
// Watcher is a service watcher. // Watcher is a service watcher.
@ -24,12 +25,12 @@ type Watcher struct {
ServiceInstances []gsvc.Service ServiceInstances []gsvc.Service
} }
func newWatcher(ctx context.Context, namespace string, serviceName string, consumer polaris.ConsumerAPI) (*Watcher, error) { func newWatcher(ctx context.Context, namespace string, key string, consumer polaris.ConsumerAPI) (*Watcher, error) {
watchServiceResponse, err := consumer.WatchService(&polaris.WatchServiceRequest{ watchServiceResponse, err := consumer.WatchService(&polaris.WatchServiceRequest{
WatchServiceRequest: model.WatchServiceRequest{ WatchServiceRequest: model.WatchServiceRequest{
Key: model.ServiceKey{ Key: model.ServiceKey{
Namespace: namespace, Namespace: namespace,
Service: serviceName, Service: key,
}, },
}, },
}) })
@ -39,7 +40,7 @@ func newWatcher(ctx context.Context, namespace string, serviceName string, consu
w := &Watcher{ w := &Watcher{
Namespace: namespace, Namespace: namespace,
ServiceName: serviceName, ServiceName: key,
Channel: watchServiceResponse.EventChannel, Channel: watchServiceResponse.EventChannel,
ServiceInstances: instancesToServiceInstances(watchServiceResponse.GetAllInstancesResp.GetInstances()), ServiceInstances: instancesToServiceInstances(watchServiceResponse.GetAllInstancesResp.GetInstances()),
} }

View File

@ -8,18 +8,24 @@ package polaris
import ( import (
"context" "context"
"os"
"testing" "testing"
"time" "time"
"github.com/gogf/gf/v2/frame/g" "github.com/polarismesh/polaris-go/api"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gctx"
"github.com/polarismesh/polaris-go/pkg/config" "github.com/polarismesh/polaris-go/pkg/config"
"github.com/gogf/gf/v2/net/gsvc"
) )
// TestRegistry TestRegistryManyService // TestRegistry TestRegistryManyService
func TestRegistry(t *testing.T) { func TestRegistry(t *testing.T) {
conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"}) conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"})
conf.GetGlobal().GetStatReporter().SetEnable(false)
conf.Consumer.LocalCache.SetPersistDir(os.TempDir() + "/polaris-registry/backup")
if err := api.SetLoggersDir(os.TempDir() + "/polaris-registry/log"); err != nil {
t.Fatal(err)
}
r := NewWithConfig( r := NewWithConfig(
conf, conf,
@ -27,8 +33,6 @@ func TestRegistry(t *testing.T) {
WithTTL(100), WithTTL(100),
) )
ctx := context.Background()
svc := &gsvc.LocalService{ svc := &gsvc.LocalService{
Name: "goframe-provider-0-tcp", Name: "goframe-provider-0-tcp",
Version: "test", Version: "test",
@ -36,13 +40,12 @@ func TestRegistry(t *testing.T) {
Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"),
} }
s, err := r.Register(ctx, svc) s, err := r.Register(context.Background(), svc)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = r.Deregister(ctx, s) if err = r.Deregister(context.Background(), s); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@ -50,6 +53,11 @@ func TestRegistry(t *testing.T) {
// TestRegistryMany TestRegistryManyService // TestRegistryMany TestRegistryManyService
func TestRegistryMany(t *testing.T) { func TestRegistryMany(t *testing.T) {
conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"}) conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"})
conf.GetGlobal().GetStatReporter().SetEnable(false)
conf.Consumer.LocalCache.SetPersistDir(os.TempDir() + "/polaris-registry-many/backup")
if err := api.SetLoggersDir(os.TempDir() + "/polaris-registry-many/log"); err != nil {
t.Fatal(err)
}
r := NewWithConfig( r := NewWithConfig(
conf, conf,
@ -91,18 +99,15 @@ func TestRegistryMany(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
err = r.Deregister(context.Background(), s0) if err = r.Deregister(context.Background(), s0); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = r.Deregister(context.Background(), s1) if err = r.Deregister(context.Background(), s1); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = r.Deregister(context.Background(), s2) if err = r.Deregister(context.Background(), s2); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@ -110,6 +115,11 @@ func TestRegistryMany(t *testing.T) {
// TestGetService Test GetService // TestGetService Test GetService
func TestGetService(t *testing.T) { func TestGetService(t *testing.T) {
conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"}) conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"})
conf.GetGlobal().GetStatReporter().SetEnable(false)
conf.Consumer.LocalCache.SetPersistDir(os.TempDir() + "/polaris-get-service/backup")
if err := api.SetLoggersDir(os.TempDir() + "/polaris-get-service/log"); err != nil {
t.Fatal(err)
}
r := NewWithConfig( r := NewWithConfig(
conf, conf,
@ -117,8 +127,6 @@ func TestGetService(t *testing.T) {
WithTTL(100), WithTTL(100),
) )
ctx := context.Background()
svc := &gsvc.LocalService{ svc := &gsvc.LocalService{
Name: "goframe-provider-4-tcp", Name: "goframe-provider-4-tcp",
Version: "test", Version: "test",
@ -126,12 +134,12 @@ func TestGetService(t *testing.T) {
Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"),
} }
s, err := r.Register(ctx, svc) s, err := r.Register(context.Background(), svc)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
time.Sleep(time.Second * 1) time.Sleep(time.Second * 1)
serviceInstances, err := r.Search(ctx, gsvc.SearchInput{ serviceInstances, err := r.Search(context.Background(), gsvc.SearchInput{
Prefix: s.GetPrefix(), Prefix: s.GetPrefix(),
Name: svc.Name, Name: svc.Name,
Version: svc.Version, Version: svc.Version,
@ -141,11 +149,10 @@ func TestGetService(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, instance := range serviceInstances { for _, instance := range serviceInstances {
g.Log().Info(ctx, instance) t.Log(instance)
} }
err = r.Deregister(ctx, s) if err = r.Deregister(context.Background(), s); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@ -153,17 +160,19 @@ func TestGetService(t *testing.T) {
// TestWatch Test Watch // TestWatch Test Watch
func TestWatch(t *testing.T) { func TestWatch(t *testing.T) {
conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"}) conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"})
conf.GetGlobal().GetStatReporter().SetEnable(false)
conf.Consumer.LocalCache.SetPersistDir(os.TempDir() + "/polaris-watch/backup")
if err := api.SetLoggersDir(os.TempDir() + "/polaris-watch/log"); err != nil {
t.Fatal(err)
}
r := NewWithConfig( r := NewWithConfig(
conf, conf,
WithTimeout(time.Second*10), WithTimeout(time.Second*10),
WithTTL(100), WithTTL(100),
) )
ctx := gctx.New()
svc := &gsvc.LocalService{ svc := &gsvc.LocalService{
Name: "goframe-provider-4-tcp", Name: "goframe-provider-5-tcp",
Version: "test", Version: "test",
Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"},
Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"),
@ -192,11 +201,10 @@ func TestWatch(t *testing.T) {
} }
for _, instance := range next { for _, instance := range next {
// it will output one instance // it will output one instance
g.Log().Info(ctx, "Register Proceed service: ", instance) t.Log("Register Proceed service: ", instance)
} }
err = r.Deregister(context.Background(), s1) if err = r.Deregister(context.Background(), s1); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -207,16 +215,48 @@ func TestWatch(t *testing.T) {
} }
for _, instance := range next { for _, instance := range next {
// it will output nothing // it will output nothing
g.Log().Info(ctx, "Deregister Proceed service: ", instance) t.Log("Deregister Proceed service: ", instance)
} }
err = watch.Close() if err = watch.Close(); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
_, err = watch.Proceed() if _, err = watch.Proceed(); err == nil {
if err == nil {
// if nil, stop failed // if nil, stop failed
t.Fatal() t.Fatal()
} }
} }
// BenchmarkRegister
func BenchmarkRegister(b *testing.B) {
for i := 0; i < b.N; i++ {
conf := config.NewDefaultConfiguration([]string{"127.0.0.1:8091"})
conf.GetGlobal().GetStatReporter().SetEnable(false)
conf.Consumer.LocalCache.SetPersistDir(os.TempDir() + "/polaris-registry/backup")
if err := api.SetLoggersDir(os.TempDir() + "/polaris-registry/log"); err != nil {
b.Fatal(err)
}
r := NewWithConfig(
conf,
WithTimeout(time.Second*10),
WithTTL(100),
)
svc := &gsvc.LocalService{
Name: "goframe-provider-0-tcp",
Version: "test",
Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"},
Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"),
}
s, err := r.Register(context.Background(), svc)
if err != nil {
b.Fatal(err)
}
if err = r.Deregister(context.Background(), s); err != nil {
b.Fatal(err)
}
}
}

View File

@ -4,7 +4,7 @@ go 1.15
require ( require (
github.com/go-zookeeper/zk v1.0.3 github.com/go-zookeeper/zk v1.0.3
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
golang.org/x/sync v0.1.0 golang.org/x/sync v0.1.0
) )

View File

@ -3,8 +3,8 @@ module github.com/gogf/gf/contrib/rpc/grpcx/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/contrib/registry/file/v2 v2.4.0 github.com/gogf/gf/contrib/registry/file/v2 v2.4.4
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
go.opentelemetry.io/otel v1.10.0 go.opentelemetry.io/otel v1.10.0
go.opentelemetry.io/otel/trace v1.10.0 go.opentelemetry.io/otel/trace v1.10.0
golang.org/x/net v0.0.0-20220919232410-f2f64ebce3c1 // indirect golang.org/x/net v0.0.0-20220919232410-f2f64ebce3c1 // indirect

View File

@ -0,0 +1,7 @@
module github.com/gogf/gf/contrib/sdk/httpclient/v2
go 1.15
require github.com/gogf/gf/v2 v2.4.4
replace github.com/gogf/gf/v2 => ../../../

View File

@ -0,0 +1,83 @@
github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I=
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/clbanning/mxj/v2 v2.5.5 h1:oT81vUeEiQQ/DcHbzSytRngP6Ky9O+L+0Bw0zSJag9E=
github.com/clbanning/mxj/v2 v2.5.5/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI=
github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0=
github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78=
github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo=
github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.opentelemetry.io/otel v1.7.0 h1:Z2lA3Tdch0iDcrhJXDIlC94XE+bxok1F9B+4Lz/lGsM=
go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
go.opentelemetry.io/otel/sdk v1.7.0 h1:4OmStpcKVOfvDOgCt7UriAPtKolwIhxpnSNI/yK+1B0=
go.opentelemetry.io/otel/sdk v1.7.0/go.mod h1:uTEOTwaqIVuTGiJN7ii13Ibp75wJmYUDe374q6cZwUU=
go.opentelemetry.io/otel/trace v1.7.0 h1:O37Iogk1lEkMRXewVtZ1BBTVn5JEp8GrJvP92bJqC6o=
go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 h1:GLw7MR8AfAG2GmGcmVgObFOHXYypgGjnGno25RDwn3Y=
golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2/go.mod h1:EFNZuWvGYxIRUEX+K8UmCFwYmZjqcrnq15ZuVldZkZ0=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -0,0 +1,109 @@
// 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 httpclient provides http client used for SDK.
package httpclient
import (
"context"
"encoding/json"
"net/http"
"github.com/gogf/gf/v2/encoding/gurl"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gmeta"
"github.com/gogf/gf/v2/util/gtag"
)
// Client is a http client for SDK.
type Client struct {
*gclient.Client
config Config
}
// New creates and returns a http client for SDK.
func New(config Config) *Client {
return &Client{
Client: config.Client,
config: config,
}
}
func (c *Client) handleResponse(ctx context.Context, res *gclient.Response, out interface{}) error {
if c.config.RawDump {
c.config.Logger.Debugf(ctx, "raw request&response:\n%s", res.Raw())
}
var (
responseBytes = res.ReadAll()
result = ghttp.DefaultHandlerResponse{
Data: out,
}
)
if !json.Valid(responseBytes) {
return gerror.Newf(`invalid response content: %s`, responseBytes)
}
if err := json.Unmarshal(responseBytes, &result); err != nil {
return gerror.Wrapf(err, `json.Unmarshal failed with content:%s`, responseBytes)
}
if result.Code != gcode.CodeOK.Code() {
return gerror.NewCode(
gcode.New(result.Code, result.Message, nil),
result.Message,
)
}
return nil
}
// Request sends request to service by struct object `req`, and receives response to struct object `res`.
func (c *Client) Request(ctx context.Context, req, res interface{}) error {
var (
method = gmeta.Get(req, gtag.Method).String()
path = gmeta.Get(req, gtag.Path).String()
)
switch gstr.ToUpper(method) {
case http.MethodGet:
return c.Get(ctx, path, req, res)
default:
result, err := c.ContentJson().DoRequest(ctx, method, c.handlePath(path, req), req)
if err != nil {
return err
}
return c.handleResponse(ctx, result, res)
}
}
// Get sends a request using GET method.
func (c *Client) Get(ctx context.Context, path string, in, out interface{}) error {
if urlParams := ghttp.BuildParams(in); urlParams != "" {
path += "?" + ghttp.BuildParams(in)
}
res, err := c.ContentJson().Get(ctx, c.handlePath(path, in))
if err != nil {
return gerror.Wrap(err, `http request failed`)
}
return c.handleResponse(ctx, res, out)
}
func (c *Client) handlePath(path string, in interface{}) string {
if gstr.Contains(path, "{") {
data := gconv.MapStrStr(in)
path, _ = gregex.ReplaceStringFuncMatch(`\{(\w+)\}`, path, func(match []string) string {
if v, ok := data[match[1]]; ok {
return gurl.Encode(v)
}
return match[1]
})
}
return path
}

View File

@ -0,0 +1,20 @@
// 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 httpclient
import (
"github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/os/glog"
)
// Config is the configuration struct for SDK client.
type Config struct {
URL string `v:"required"` // Service address. Eg: user.svc.local, http://user.svc.local
Client *gclient.Client // Custom underlying client.
Logger *glog.Logger // Custom logger.
RawDump bool // Whether auto dump request&response in stdout.
}

View File

@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/trace/jaeger/v2
go 1.15 go 1.15
require ( require (
github.com/gogf/gf/v2 v2.4.0 github.com/gogf/gf/v2 v2.4.4
go.opentelemetry.io/otel v1.7.0 go.opentelemetry.io/otel v1.7.0
go.opentelemetry.io/otel/exporters/jaeger v1.7.0 go.opentelemetry.io/otel/exporters/jaeger v1.7.0
go.opentelemetry.io/otel/sdk v1.7.0 go.opentelemetry.io/otel/sdk v1.7.0

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