Merge branch 'develop' into develop

This commit is contained in:
Ming Deng 2021-06-16 22:19:00 +08:00 committed by GitHub
commit 13508f2840
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
170 changed files with 634 additions and 815 deletions

124
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,124 @@
name: Test
on:
push:
branches:
- master
- develop
paths:
- "**/*.go"
- "go.mod"
- "go.sum"
- ".github/workflows/test.yml"
pull_request:
types: [opened, synchronize, reopened]
branches:
- master
- develop
paths:
- "**/*.go"
- "go.mod"
- "go.sum"
- ".github/workflows/test.yml"
jobs:
test:
strategy:
fail-fast: false
matrix:
go-version: [1.14, 1.15, 1.16]
runs-on: ubuntu-latest
services:
redis:
image: redis:latest
ports:
- 6379:6379
memcached:
image: memcached:latest
ports:
- 11211:11211
ssdb:
image: wendal/ssdb:latest
ports:
- 8888:8888
postgres:
image: postgres:latest
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: orm_test
ports:
- 5432/tcp
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
steps:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: ${{ matrix.go-version }}
- name: Checkout codebase
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Run etcd
env:
ETCD_VERSION: v3.4.16
run: |
rm -rf /tmp/etcd-data.tmp
mkdir -p /tmp/etcd-data.tmp
docker rmi gcr.io/etcd-development/etcd:${ETCD_VERSION} || true && \
docker run -d \
-p 2379:2379 \
-p 2380:2380 \
--mount type=bind,source=/tmp/etcd-data.tmp,destination=/etcd-data \
--name etcd-gcr-${ETCD_VERSION} \
gcr.io/etcd-development/etcd:${ETCD_VERSION} \
/usr/local/bin/etcd \
--name s1 \
--data-dir /etcd-data \
--listen-client-urls http://0.0.0.0:2379 \
--advertise-client-urls http://0.0.0.0:2379 \
--listen-peer-urls http://0.0.0.0:2380 \
--initial-advertise-peer-urls http://0.0.0.0:2380 \
--initial-cluster s1=http://0.0.0.0:2380 \
--initial-cluster-token tkn \
--initial-cluster-state new
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.float 1.23"
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.bool true"
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.int 11"
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.string hello"
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.serialize.name test"
docker exec etcd-gcr-${ETCD_VERSION} /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put sub.sub.key1 sub.sub.key"
- name: Run ORM tests on sqlite3
env:
GOPATH: /home/runner/go
ORM_DRIVER: sqlite3
ORM_SOURCE: /tmp/sqlite3/orm_test.db
run: |
mkdir -p /tmp/sqlite3 && touch /tmp/sqlite3/orm_test.db
go test -coverprofile=coverage_sqlite3.txt -covermode=atomic $(go list ./... | grep client/orm)
- name: Run ORM tests on postgres
env:
GOPATH: /home/runner/go
ORM_DRIVER: postgres
ORM_SOURCE: host=localhost port=${{ job.services.postgres.ports[5432] }} user=postgres password=postgres dbname=orm_test sslmode=disable
run: |
go test -coverprofile=coverage_postgres.txt -covermode=atomic $(go list ./... | grep client/orm)
- name: Run tests on mysql
env:
GOPATH: /home/runner/go
ORM_DRIVER: mysql
ORM_SOURCE: root:root@/orm_test?charset=utf8
run: |
sudo systemctl start mysql
mysql -u root -proot -e 'create database orm_test;'
go test -coverprofile=coverage.txt -covermode=atomic ./...
- name: Upload codecov
env:
CODECOV_TOKEN: 4f4bc484-32a8-43b7-9f48-20966bd48ceb
run: bash <(curl -s https://codecov.io/bash)

View File

@ -1,77 +0,0 @@
language: go
go:
- "1.14.x"
- "1.15.x"
- "1.16.x"
services:
- redis-server
- mysql
- postgresql
- memcached
- docker
env:
global:
- GO_REPO_FULLNAME="github.com/beego/beego/v2"
matrix:
- ORM_DRIVER=sqlite3 ORM_SOURCE=$TRAVIS_BUILD_DIR/orm_test.db
- ORM_DRIVER=postgres ORM_SOURCE="user=postgres dbname=orm_test sslmode=disable"
- ORM_DRIVER=mysql export ORM_SOURCE="root:@/orm_test?charset=utf8"
before_install:
- export CODECOV_TOKEN="4f4bc484-32a8-43b7-9f48-20966bd48ceb"
# link the local repo with ${GOPATH}/src/<namespace>/<repo>
- GO_REPO_NAMESPACE=${GO_REPO_FULLNAME%/*}
# relies on GOPATH to contain only one directory...
- mkdir -p ${GOPATH}/src/${GO_REPO_NAMESPACE}
- ln -sv ${TRAVIS_BUILD_DIR} ${GOPATH}/src/${GO_REPO_FULLNAME}
- cd ${GOPATH}/src/${GO_REPO_FULLNAME}
# get and build ssdb
- git clone git://github.com/ideawu/ssdb.git
- cd ssdb
- make
- cd ..
# - prepare etcd
# - prepare for etcd unit tests
- rm -rf /tmp/etcd-data.tmp
- mkdir -p /tmp/etcd-data.tmp
- docker rmi gcr.io/etcd-development/etcd:v3.3.25 || true &&
docker run -d
-p 2379:2379
-p 2380:2380
--mount type=bind,source=/tmp/etcd-data.tmp,destination=/etcd-data
--name etcd-gcr-v3.3.25
gcr.io/etcd-development/etcd:v3.3.25
/usr/local/bin/etcd
--name s1
--data-dir /etcd-data
--listen-client-urls http://0.0.0.0:2379
--advertise-client-urls http://0.0.0.0:2379
--listen-peer-urls http://0.0.0.0:2380
--initial-advertise-peer-urls http://0.0.0.0:2380
--initial-cluster s1=http://0.0.0.0:2380
--initial-cluster-token tkn
--initial-cluster-state new
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.float 1.23"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.bool true"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.int 11"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.string hello"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.serialize.name test"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put sub.sub.key1 sub.sub.key"
before_script:
- psql --version
# - prepare for orm unit tests
- sh -c "if [ '$ORM_DRIVER' = 'postgres' ]; then psql -c 'create database orm_test;' -U postgres; fi"
- sh -c "if [ '$ORM_DRIVER' = 'mysql' ]; then mysql -u root -e 'create database orm_test;'; fi"
- sh -c "if [ '$ORM_DRIVER' = 'sqlite' ]; then touch $TRAVIS_BUILD_DIR/orm_test.db; fi"
- sh -c "go list ./... | grep -v vendor | xargs go vet -v"
- mkdir -p res/var
- ./ssdb/ssdb-server ./ssdb/ssdb.conf -d
after_script:
- killall -w ssdb-server
- rm -rf ./res/var/*
after_success:
- bash <(curl -s https://codecov.io/bash)
script:
- GO111MODULE=on go test -coverprofile=coverage.txt -covermode=atomic ./...
addons:
postgresql: "9.6"

View File

@ -1,5 +1,7 @@
# developing # developing
- Add template functions eq,lt to support uint and int compare. [4607](https://github.com/beego/beego/pull/4607) - Add template functions eq,lt to support uint and int compare. [4607](https://github.com/beego/beego/pull/4607)
- Migrate tests to GitHub Actions. [4663](https://github.com/beego/beego/issues/4663)
- Add http client and option func. [4455](https://github.com/beego/beego/issues/4455) - Add http client and option func. [4455](https://github.com/beego/beego/issues/4455)
- Add: Convenient way to generate mock object [4620](https://github.com/beego/beego/issues/4620) - Add: Convenient way to generate mock object [4620](https://github.com/beego/beego/issues/4620)
- Infra: use dependabot to update dependencies. [4623](https://github.com/beego/beego/pull/4623) - Infra: use dependabot to update dependencies. [4623](https://github.com/beego/beego/pull/4623)
@ -59,3 +61,19 @@
- [4474](https://github.com/beego/beego/pull/4474) - [4474](https://github.com/beego/beego/pull/4474)
- [4479](https://github.com/beego/beego/pull/4479) - [4479](https://github.com/beego/beego/pull/4479)
- [4639](https://github.com/beego/beego/pull/4639) - [4639](https://github.com/beego/beego/pull/4639)
## Fix lint and format code
- [4644](https://github.com/beego/beego/pull/4644)
- [4645](https://github.com/beego/beego/pull/4645)
- [4646](https://github.com/beego/beego/pull/4646)
- [4647](https://github.com/beego/beego/pull/4647)
- [4648](https://github.com/beego/beego/pull/4648)
- [4649](https://github.com/beego/beego/pull/4649)
- [4651](https://github.com/beego/beego/pull/4651)
- [4652](https://github.com/beego/beego/pull/4652)
- [4653](https://github.com/beego/beego/pull/4653)
- [4654](https://github.com/beego/beego/pull/4654)
- [4655](https://github.com/beego/beego/pull/4655)
- [4656](https://github.com/beego/beego/pull/4656)
- [4660](https://github.com/beego/beego/pull/4660)

View File

@ -1,14 +1,12 @@
# Beego [![Build Status](https://travis-ci.org/beego/beego.svg?branch=master)](https://travis-ci.org/beego/beego) [![GoDoc](http://godoc.org/github.com/beego/beego?status.svg)](http://godoc.org/github.com/beego/beego) [![Foundation](https://img.shields.io/badge/Golang-Foundation-green.svg)](http://golangfoundation.org) [![Go Report Card](https://goreportcard.com/badge/github.com/beego/beego)](https://goreportcard.com/report/github.com/beego/beego) # Beego [![Test](https://github.com/beego/beego/actions/workflows/test.yml/badge.svg?branch=develop)](https://github.com/beego/beego/actions/workflows/test.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/beego/beego)](https://goreportcard.com/report/github.com/beego/beego) [![Go Reference](https://pkg.go.dev/badge/github.com/beego/beego/v2.svg)](https://pkg.go.dev/github.com/beego/beego/v2)
Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services.
services.
It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct embedding.
embedding.
![architecture](https://cdn.nlark.com/yuque/0/2020/png/755700/1607857489109-1e267fce-d65f-4c5e-b915-5c475df33c58.png) ![architecture](https://cdn.nlark.com/yuque/0/2020/png/755700/1607857489109-1e267fce-d65f-4c5e-b915-5c475df33c58.png)
Beego is compos of four parts: Beego is composed of four parts:
1. Base modules: including log module, config module, governor module; 1. Base modules: including log module, config module, governor module;
2. Task: is used for running timed tasks or periodic tasks; 2. Task: is used for running timed tasks or periodic tasks;
@ -90,11 +88,11 @@ Congratulations! You've just built your first **beego** app.
## Community ## Community
* [http://beego.me/community](http://beego.me/community) * [http://beego.me/community](http://beego.me/community)
* Welcome to join us in Slack: [https://beego.slack.com invite](https://join.slack.com/t/beego/shared_invite/zt-fqlfjaxs-_CRmiITCSbEqQG9NeBqXKA), * Welcome to join us in Slack: [https://beego.slack.com invite](https://join.slack.com/t/beego/shared_invite/zt-fqlfjaxs-_CRmiITCSbEqQG9NeBqXKA),
* QQ Group Group ID:523992905 * QQ Group Group ID:523992905
* [Contribution Guide](https://github.com/beego/beedoc/blob/master/en-US/intro/contributing.md). * [Contribution Guide](https://github.com/beego/beedoc/blob/master/en-US/intro/contributing.md).
## License ## License
beego source code is licensed under the Apache Licence, Version 2.0 beego source code is licensed under the Apache Licence, Version 2.0
(http://www.apache.org/licenses/LICENSE-2.0.html). ([https://www.apache.org/licenses/LICENSE-2.0.html](https://www.apache.org/licenses/LICENSE-2.0.html)).

View File

@ -22,10 +22,8 @@ import (
"github.com/beego/beego/v2/server/web/context" "github.com/beego/beego/v2/server/web/context"
) )
var ( // BeeApp is an application instance
// BeeApp is an application instance var BeeApp *App
BeeApp *App
)
func init() { func init() {
// create beego application // create beego application

View File

@ -36,10 +36,6 @@ type M web.M
// Hook function to run // Hook function to run
type hookfunc func() error type hookfunc func() error
var (
hooks = make([]hookfunc, 0) // hook function slice to store the hookfunc
)
// AddAPPStartHook is used to register the hookfunc // AddAPPStartHook is used to register the hookfunc
// The hookfuncs will run in beego.Run() // The hookfuncs will run in beego.Run()
// such as initiating session , starting middleware , building template, starting admin control and so on. // such as initiating session , starting middleware , building template, starting admin control and so on.

View File

@ -19,15 +19,15 @@ import (
) )
func TestGetString(t *testing.T) { func TestGetString(t *testing.T) {
var t1 = "test1" t1 := "test1"
if "test1" != GetString(t1) { if "test1" != GetString(t1) {
t.Error("get string from string error") t.Error("get string from string error")
} }
var t2 = []byte("test2") t2 := []byte("test2")
if "test2" != GetString(t2) { if "test2" != GetString(t2) {
t.Error("get string from byte array error") t.Error("get string from byte array error")
} }
var t3 = 1 t3 := 1
if "1" != GetString(t3) { if "1" != GetString(t3) {
t.Error("get string from int error") t.Error("get string from int error")
} }
@ -35,7 +35,7 @@ func TestGetString(t *testing.T) {
if "1" != GetString(t4) { if "1" != GetString(t4) {
t.Error("get string from int64 error") t.Error("get string from int64 error")
} }
var t5 = 1.1 t5 := 1.1
if "1.1" != GetString(t5) { if "1.1" != GetString(t5) {
t.Error("get string from float64 error") t.Error("get string from float64 error")
} }
@ -46,7 +46,7 @@ func TestGetString(t *testing.T) {
} }
func TestGetInt(t *testing.T) { func TestGetInt(t *testing.T) {
var t1 = 1 t1 := 1
if 1 != GetInt(t1) { if 1 != GetInt(t1) {
t.Error("get int from int error") t.Error("get int from int error")
} }
@ -58,7 +58,7 @@ func TestGetInt(t *testing.T) {
if 64 != GetInt(t3) { if 64 != GetInt(t3) {
t.Error("get int from int64 error") t.Error("get int from int64 error")
} }
var t4 = "128" t4 := "128"
if 128 != GetInt(t4) { if 128 != GetInt(t4) {
t.Error("get int from num string error") t.Error("get int from num string error")
} }
@ -69,7 +69,7 @@ func TestGetInt(t *testing.T) {
func TestGetInt64(t *testing.T) { func TestGetInt64(t *testing.T) {
var i int64 = 1 var i int64 = 1
var t1 = 1 t1 := 1
if i != GetInt64(t1) { if i != GetInt64(t1) {
t.Error("get int64 from int error") t.Error("get int64 from int error")
} }
@ -81,7 +81,7 @@ func TestGetInt64(t *testing.T) {
if i != GetInt64(t3) { if i != GetInt64(t3) {
t.Error("get int64 from int64 error") t.Error("get int64 from int64 error")
} }
var t4 = "1" t4 := "1"
if i != GetInt64(t4) { if i != GetInt64(t4) {
t.Error("get int64 from num string error") t.Error("get int64 from num string error")
} }
@ -91,22 +91,22 @@ func TestGetInt64(t *testing.T) {
} }
func TestGetFloat64(t *testing.T) { func TestGetFloat64(t *testing.T) {
var f = 1.11 f := 1.11
var t1 float32 = 1.11 var t1 float32 = 1.11
if f != GetFloat64(t1) { if f != GetFloat64(t1) {
t.Error("get float64 from float32 error") t.Error("get float64 from float32 error")
} }
var t2 = 1.11 t2 := 1.11
if f != GetFloat64(t2) { if f != GetFloat64(t2) {
t.Error("get float64 from float64 error") t.Error("get float64 from float64 error")
} }
var t3 = "1.11" t3 := "1.11"
if f != GetFloat64(t3) { if f != GetFloat64(t3) {
t.Error("get float64 from string error") t.Error("get float64 from string error")
} }
var f2 float64 = 1 var f2 float64 = 1
var t4 = 1 t4 := 1
if f2 != GetFloat64(t4) { if f2 != GetFloat64(t4) {
t.Error("get float64 from int error") t.Error("get float64 from int error")
} }
@ -117,11 +117,11 @@ func TestGetFloat64(t *testing.T) {
} }
func TestGetBool(t *testing.T) { func TestGetBool(t *testing.T) {
var t1 = true t1 := true
if !GetBool(t1) { if !GetBool(t1) {
t.Error("get bool from bool error") t.Error("get bool from bool error")
} }
var t2 = "true" t2 := "true"
if !GetBool(t2) { if !GetBool(t2) {
t.Error("get bool from string error") t.Error("get bool from string error")
} }

View File

@ -34,10 +34,8 @@ import (
redis2 "github.com/beego/beego/v2/client/cache/redis" redis2 "github.com/beego/beego/v2/client/cache/redis"
) )
var ( // DefaultKey the collection name of redis for cache adapter.
// DefaultKey the collection name of redis for cache adapter. var DefaultKey = "beecacheRedis"
DefaultKey = "beecacheRedis"
)
// NewRedisCache create new redis cache with default collection name. // NewRedisCache create new redis cache with default collection name.
func NewRedisCache() cache.Cache { func NewRedisCache() cache.Cache {

View File

@ -20,7 +20,6 @@ import (
) )
func TestExpandValueEnv(t *testing.T) { func TestExpandValueEnv(t *testing.T) {
testCases := []struct { testCases := []struct {
item string item string
want string want string
@ -51,5 +50,4 @@ func TestExpandValueEnv(t *testing.T) {
t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got) t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got)
} }
} }
} }

View File

@ -23,7 +23,6 @@ import (
) )
func TestIni(t *testing.T) { func TestIni(t *testing.T) {
var ( var (
inicontext = ` inicontext = `
;comment one ;comment one
@ -129,11 +128,9 @@ password = ${GOPATH}
if iniconf.String("name") != "astaxie" { if iniconf.String("name") != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
} }
func TestIniSave(t *testing.T) { func TestIniSave(t *testing.T) {
const ( const (
inicontext = ` inicontext = `
app = app app = app

View File

@ -23,7 +23,6 @@ import (
) )
func TestJsonStartsWithArray(t *testing.T) { func TestJsonStartsWithArray(t *testing.T) {
const jsoncontextwitharray = `[ const jsoncontextwitharray = `[
{ {
"url": "user", "url": "user",
@ -71,7 +70,6 @@ func TestJsonStartsWithArray(t *testing.T) {
} }
func TestJson(t *testing.T) { func TestJson(t *testing.T) {
var ( var (
jsoncontext = `{ jsoncontext = `{
"appname": "beeapi", "appname": "beeapi",

View File

@ -23,7 +23,6 @@ import (
) )
func TestXML(t *testing.T) { func TestXML(t *testing.T) {
var ( var (
// xml parse should incluce in <config></config> tags // xml parse should incluce in <config></config> tags
xmlcontext = `<?xml version="1.0" encoding="UTF-8"?> xmlcontext = `<?xml version="1.0" encoding="UTF-8"?>

View File

@ -23,7 +23,6 @@ import (
) )
func TestYaml(t *testing.T) { func TestYaml(t *testing.T) {
var ( var (
yamlcontext = ` yamlcontext = `
"appname": beeapi "appname": beeapi
@ -112,5 +111,4 @@ func TestYaml(t *testing.T) {
if yamlconf.String("name") != "astaxie" { if yamlconf.String("name") != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
} }

View File

@ -25,7 +25,6 @@ import (
// Demo is used to test, it's empty // Demo is used to test, it's empty
func Demo(i int) { func Demo(i int) {
} }
func TestConvertParams(t *testing.T) { func TestConvertParams(t *testing.T) {

View File

@ -48,9 +48,11 @@ type ControllerCommentsSlice web.ControllerCommentsSlice
func (p ControllerCommentsSlice) Len() int { func (p ControllerCommentsSlice) Len() int {
return (web.ControllerCommentsSlice)(p).Len() return (web.ControllerCommentsSlice)(p).Len()
} }
func (p ControllerCommentsSlice) Less(i, j int) bool { func (p ControllerCommentsSlice) Less(i, j int) bool {
return (web.ControllerCommentsSlice)(p).Less(i, j) return (web.ControllerCommentsSlice)(p).Less(i, j)
} }
func (p ControllerCommentsSlice) Swap(i, j int) { func (p ControllerCommentsSlice) Swap(i, j int) {
(web.ControllerCommentsSlice)(p).Swap(i, j) (web.ControllerCommentsSlice)(p).Swap(i, j)
} }

View File

@ -26,11 +26,13 @@ import (
"time" "time"
) )
const getUrl = "http://httpbin.org/get" const (
const ipUrl = "http://httpbin.org/ip" getURL = "http://httpbin.org/get"
ipURL = "http://httpbin.org/ip"
)
func TestResponse(t *testing.T) { func TestResponse(t *testing.T) {
req := Get(getUrl) req := Get(getURL)
resp, err := req.Response() resp, err := req.Response()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -63,12 +65,10 @@ func TestDoRequest(t *testing.T) {
if elapsedTime < delayedTime { if elapsedTime < delayedTime {
t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime) t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime)
} }
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
req := Get(getURL)
req := Get(getUrl)
b, err := req.Bytes() b, err := req.Bytes()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -210,7 +210,7 @@ func TestWithSetting(t *testing.T) {
setting.ReadWriteTimeout = 5 * time.Second setting.ReadWriteTimeout = 5 * time.Second
SetDefaultSetting(setting) SetDefaultSetting(setting)
str, err := Get(getUrl).String() str, err := Get(getURL).String()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -223,8 +223,7 @@ func TestWithSetting(t *testing.T) {
} }
func TestToJson(t *testing.T) { func TestToJson(t *testing.T) {
req := Get(ipURL)
req := Get(ipUrl)
resp, err := req.Response() resp, err := req.Response()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -250,12 +249,11 @@ func TestToJson(t *testing.T) {
t.Fatal("response is not valid ip") t.Fatal("response is not valid ip")
} }
} }
} }
func TestToFile(t *testing.T) { func TestToFile(t *testing.T) {
f := "beego_testfile" f := "beego_testfile"
req := Get(ipUrl) req := Get(ipURL)
err := req.ToFile(f) err := req.ToFile(f)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -269,7 +267,7 @@ func TestToFile(t *testing.T) {
func TestToFileDir(t *testing.T) { func TestToFileDir(t *testing.T) {
f := "./files/beego_testfile" f := "./files/beego_testfile"
req := Get(ipUrl) req := Get(ipURL)
err := req.ToFile(f) err := req.ToFile(f)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -18,7 +18,5 @@ import (
"github.com/beego/beego/v2/client/orm" "github.com/beego/beego/v2/client/orm"
) )
var ( // ErrMissPK missing pk error
// ErrMissPK missing pk error var ErrMissPK = orm.ErrMissPK
ErrMissPK = orm.ErrMissPK
)

View File

@ -1,36 +0,0 @@
// Copyright 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orm
import (
"github.com/beego/beego/v2/client/orm"
)
type baseQuerySetter struct {
}
const shouldNotInvoke = "you should not invoke this method."
func (b *baseQuerySetter) ForceIndex(indexes ...string) orm.QuerySeter {
panic(shouldNotInvoke)
}
func (b *baseQuerySetter) UseIndex(indexes ...string) orm.QuerySeter {
panic(shouldNotInvoke)
}
func (b *baseQuerySetter) IgnoreIndex(indexes ...string) orm.QuerySeter {
panic(shouldNotInvoke)
}

View File

@ -72,5 +72,4 @@ func TestRedisSentinel(t *testing.T) {
assert.Nil(t, password) assert.Nil(t, password)
sess.SessionRelease(w) sess.SessionRelease(w)
} }

View File

@ -22,14 +22,14 @@ import (
"time" "time"
) )
const sid = "Session_id" const (
const sidNew = "Session_id_new" sid = "Session_id"
const sessionPath = "./_session_runtime" sidNew = "Session_id_new"
sessionPath = "./_session_runtime"
var (
mutex sync.Mutex
) )
var mutex sync.Mutex
func TestFileProviderSessionExist(t *testing.T) { func TestFileProviderSessionExist(t *testing.T) {
mutex.Lock() mutex.Lock()
defer mutex.Unlock() defer mutex.Unlock()

View File

@ -118,7 +118,6 @@ func AssetsJs(text string) template.HTML {
// AssetsCSS returns stylesheet link tag with src string. // AssetsCSS returns stylesheet link tag with src string.
func AssetsCSS(text string) template.HTML { func AssetsCSS(text string) template.HTML {
text = "<link href=\"" + text + "\" rel=\"stylesheet\" />" text = "<link href=\"" + text + "\" rel=\"stylesheet\" />"
return template.HTML(text) return template.HTML(text)

View File

@ -79,7 +79,6 @@ func TestHtmlunquote(t *testing.T) {
h := `&lt;&#39;&nbsp;&rdquo;&ldquo;&amp;&#34;&gt;` h := `&lt;&#39;&nbsp;&rdquo;&ldquo;&amp;&#34;&gt;`
s := `<' ”“&">` s := `<' ”“&">`
assert.Equal(t, s, Htmlunquote(h)) assert.Equal(t, s, Htmlunquote(h))
} }
func TestParseForm(t *testing.T) { func TestParseForm(t *testing.T) {
@ -234,5 +233,4 @@ func TestMapGet(t *testing.T) {
res, err = MapGet(m5, 5, 4, 3, 2, 1) res, err = MapGet(m5, 5, 4, 3, 2, 1)
assert.Nil(t, err) assert.Nil(t, err)
assert.Nil(t, res) assert.Nil(t, res)
} }

View File

@ -14,12 +14,7 @@
package testing package testing
import ( import "github.com/beego/beego/v2/client/httplib/testing"
"github.com/beego/beego/v2/client/httplib/testing"
)
var port = ""
var baseURL = "http://localhost:"
// TestHTTPRequest beego test request client // TestHTTPRequest beego test request client
type TestHTTPRequest testing.TestHTTPRequest type TestHTTPRequest testing.TestHTTPRequest

View File

@ -16,19 +16,10 @@ package toolbox
import ( import (
"io" "io"
"os"
"time"
"github.com/beego/beego/v2/core/admin" "github.com/beego/beego/v2/core/admin"
) )
var startTime = time.Now()
var pid int
func init() {
pid = os.Getpid()
}
// ProcessInput parse input command string // ProcessInput parse input command string
func ProcessInput(input string, w io.Writer) { func ProcessInput(input string, w io.Writer) {
admin.ProcessInput(input, w) admin.ProcessInput(input, w)

View File

@ -80,7 +80,6 @@ type Task struct {
// NewTask add new task with name, time and func // NewTask add new task with name, time and func
func NewTask(tname string, spec string, f TaskFunc) *Task { func NewTask(tname string, spec string, f TaskFunc) *Task {
task := task.NewTask(tname, spec, func(ctx context.Context) error { task := task.NewTask(tname, spec, func(ctx context.Context) error {
return f() return f()
}) })
@ -98,7 +97,6 @@ func (t *Task) GetSpec() string {
// GetStatus get current task status // GetStatus get current task status
func (t *Task) GetStatus() string { func (t *Task) GetStatus() string {
t.initDelegate() t.initDelegate()
return t.delegate.GetStatus(context.Background()) return t.delegate.GetStatus(context.Background())
@ -222,7 +220,6 @@ type MapSorter task.MapSorter
// NewMapSorter create new tasker map // NewMapSorter create new tasker map
func NewMapSorter(m map[string]Tasker) *MapSorter { func NewMapSorter(m map[string]Tasker) *MapSorter {
newTaskerMap := make(map[string]task.Tasker, len(m)) newTaskerMap := make(map[string]task.Tasker, len(m))
for key, value := range m { for key, value := range m {
@ -249,6 +246,7 @@ func (ms *MapSorter) Less(i, j int) bool {
} }
return ms.Vals[i].GetNext(context.Background()).Before(ms.Vals[j].GetNext(context.Background())) return ms.Vals[i].GetNext(context.Background()).Before(ms.Vals[j].GetNext(context.Background()))
} }
func (ms *MapSorter) Swap(i, j int) { func (ms *MapSorter) Swap(i, j int) {
ms.Vals[i], ms.Vals[j] = ms.Vals[j], ms.Vals[i] ms.Vals[i], ms.Vals[j] = ms.Vals[j], ms.Vals[i]
ms.Keys[i], ms.Keys[j] = ms.Keys[j], ms.Keys[i] ms.Keys[i], ms.Keys[j] = ms.Keys[j], ms.Keys[i]

View File

@ -69,9 +69,7 @@ import (
beecontext "github.com/beego/beego/v2/server/web/context" beecontext "github.com/beego/beego/v2/server/web/context"
) )
var ( var defaultChars = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
defaultChars = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
)
const ( const (
// default captcha attributes // default captcha attributes

View File

@ -28,8 +28,8 @@ func TestPrint(t *testing.T) {
} }
func TestPrintPoint(t *testing.T) { func TestPrintPoint(t *testing.T) {
var v1 = new(mytype) v1 := new(mytype)
var v2 = new(mytype) v2 := new(mytype)
v1.prev = nil v1.prev = nil
v1.next = v2 v1.next = v2

View File

@ -19,6 +19,7 @@ import (
) )
type reducetype func(interface{}) interface{} type reducetype func(interface{}) interface{}
type filtertype func(interface{}) bool type filtertype func(interface{}) bool
// InSlice checks given string in string slice or not. // InSlice checks given string in string slice or not.

View File

@ -27,9 +27,7 @@ const (
LabelTag = validation.LabelTag LabelTag = validation.LabelTag
) )
var ( var ErrInt64On32 = validation.ErrInt64On32
ErrInt64On32 = validation.ErrInt64On32
)
// CustomFunc is for custom validate function // CustomFunc is for custom validate function
type CustomFunc func(v *Validation, obj interface{}, key string) type CustomFunc func(v *Validation, obj interface{}, key string)

View File

@ -50,7 +50,6 @@ func TestMin(t *testing.T) {
assert.False(t, valid.Min(-1, 0, "min0").Ok) assert.False(t, valid.Min(-1, 0, "min0").Ok)
assert.True(t, valid.Min(1, 0, "min0").Ok) assert.True(t, valid.Min(1, 0, "min0").Ok)
} }
func TestMax(t *testing.T) { func TestMax(t *testing.T) {
@ -502,5 +501,4 @@ func TestCanSkipAlso(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.True(t, b) assert.True(t, b)
} }

View File

@ -21,29 +21,29 @@ import (
) )
func TestGetString(t *testing.T) { func TestGetString(t *testing.T) {
var t1 = "test1" t1 := "test1"
assert.Equal(t, "test1", GetString(t1)) assert.Equal(t, "test1", GetString(t1))
var t2 = []byte("test2") t2 := []byte("test2")
assert.Equal(t, "test2", GetString(t2)) assert.Equal(t, "test2", GetString(t2))
var t3 = 1 t3 := 1
assert.Equal(t, "1", GetString(t3)) assert.Equal(t, "1", GetString(t3))
var t4 int64 = 1 var t4 int64 = 1
assert.Equal(t, "1", GetString(t4)) assert.Equal(t, "1", GetString(t4))
var t5 = 1.1 t5 := 1.1
assert.Equal(t, "1.1", GetString(t5)) assert.Equal(t, "1.1", GetString(t5))
assert.Equal(t, "", GetString(nil)) assert.Equal(t, "", GetString(nil))
} }
func TestGetInt(t *testing.T) { func TestGetInt(t *testing.T) {
var t1 = 1 t1 := 1
assert.Equal(t, 1, GetInt(t1)) assert.Equal(t, 1, GetInt(t1))
var t2 int32 = 32 var t2 int32 = 32
assert.Equal(t, 32, GetInt(t2)) assert.Equal(t, 32, GetInt(t2))
var t3 int64 = 64 var t3 int64 = 64
assert.Equal(t, 64, GetInt(t3)) assert.Equal(t, 64, GetInt(t3))
var t4 = "128" t4 := "128"
assert.Equal(t, 128, GetInt(t4)) assert.Equal(t, 128, GetInt(t4))
assert.Equal(t, 0, GetInt(nil)) assert.Equal(t, 0, GetInt(nil))
@ -51,38 +51,38 @@ func TestGetInt(t *testing.T) {
func TestGetInt64(t *testing.T) { func TestGetInt64(t *testing.T) {
var i int64 = 1 var i int64 = 1
var t1 = 1 t1 := 1
assert.Equal(t, i, GetInt64(t1)) assert.Equal(t, i, GetInt64(t1))
var t2 int32 = 1 var t2 int32 = 1
assert.Equal(t, i, GetInt64(t2)) assert.Equal(t, i, GetInt64(t2))
var t3 int64 = 1 var t3 int64 = 1
assert.Equal(t, i, GetInt64(t3)) assert.Equal(t, i, GetInt64(t3))
var t4 = "1" t4 := "1"
assert.Equal(t, i, GetInt64(t4)) assert.Equal(t, i, GetInt64(t4))
assert.Equal(t, int64(0), GetInt64(nil)) assert.Equal(t, int64(0), GetInt64(nil))
} }
func TestGetFloat64(t *testing.T) { func TestGetFloat64(t *testing.T) {
var f = 1.11 f := 1.11
var t1 float32 = 1.11 var t1 float32 = 1.11
assert.Equal(t, f, GetFloat64(t1)) assert.Equal(t, f, GetFloat64(t1))
var t2 = 1.11 t2 := 1.11
assert.Equal(t, f, GetFloat64(t2)) assert.Equal(t, f, GetFloat64(t2))
var t3 = "1.11" t3 := "1.11"
assert.Equal(t, f, GetFloat64(t3)) assert.Equal(t, f, GetFloat64(t3))
var f2 float64 = 1 var f2 float64 = 1
var t4 = 1 t4 := 1
assert.Equal(t, f2, GetFloat64(t4)) assert.Equal(t, f2, GetFloat64(t4))
assert.Equal(t, float64(0), GetFloat64(nil)) assert.Equal(t, float64(0), GetFloat64(nil))
} }
func TestGetBool(t *testing.T) { func TestGetBool(t *testing.T) {
var t1 = true t1 := true
assert.True(t, GetBool(t1)) assert.True(t, GetBool(t1))
var t2 = "true" t2 := "true"
assert.True(t, GetBool(t2)) assert.True(t, GetBool(t2))
assert.False(t, GetBool(nil)) assert.False(t, GetBool(nil))

View File

@ -170,5 +170,7 @@ The reponse from SSDB server is invalid.
Usually it indicates something wrong on server side. Usually it indicates something wrong on server side.
`) `)
var ErrKeyExpired = berror.Error(KeyExpired, "the key is expired") var (
var ErrKeyNotExist = berror.Error(KeyNotExist, "the key isn't exist") ErrKeyExpired = berror.Error(KeyExpired, "the key is expired")
ErrKeyNotExist = berror.Error(KeyNotExist, "the key isn't exist")
)

View File

@ -67,7 +67,6 @@ func NewFileCache() Cache {
// StartAndGC starts gc for file cache. // StartAndGC starts gc for file cache.
// config must be in the format {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"} // config must be in the format {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}
func (fc *FileCache) StartAndGC(config string) error { func (fc *FileCache) StartAndGC(config string) error {
cfg := make(map[string]string) cfg := make(map[string]string)
err := json.Unmarshal([]byte(config), &cfg) err := json.Unmarshal([]byte(config), &cfg)
if err != nil { if err != nil {

View File

@ -25,10 +25,8 @@ import (
"github.com/beego/beego/v2/core/berror" "github.com/beego/beego/v2/core/berror"
) )
var ( // DefaultEvery sets a timer for how often to recycle the expired cache items in memory (in seconds)
// Timer for how often to recycle the expired cache items in memory (in seconds) var DefaultEvery = 60 // 1 minute
DefaultEvery = 60 // 1 minute
)
// MemoryItem stores memory cache item. // MemoryItem stores memory cache item.
type MemoryItem struct { type MemoryItem struct {

View File

@ -43,10 +43,8 @@ import (
"github.com/beego/beego/v2/core/berror" "github.com/beego/beego/v2/core/berror"
) )
var ( // DefaultKey defines the collection name of redis for the cache adapter.
// The collection name of redis for the cache adapter. var DefaultKey = "beecacheRedis"
DefaultKey = "beecacheRedis"
)
// Cache is Redis cache adapter. // Cache is Redis cache adapter.
type Cache struct { type Cache struct {

View File

@ -28,7 +28,6 @@ import (
) )
func TestRedisCache(t *testing.T) { func TestRedisCache(t *testing.T) {
redisAddr := os.Getenv("REDIS_ADDR") redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" { if redisAddr == "" {
redisAddr = "127.0.0.1:6379" redisAddr = "127.0.0.1:6379"

View File

@ -124,7 +124,6 @@ func (rc *Cache) IsExist(ctx context.Context, key string) (bool, error) {
return true, nil return true, nil
} }
return false, nil return false, nil
} }
// ClearAll clears all cached items in ssdb. // ClearAll clears all cached items in ssdb.

View File

@ -15,7 +15,6 @@ import (
) )
func TestSsdbcacheCache(t *testing.T) { func TestSsdbcacheCache(t *testing.T) {
ssdbAddr := os.Getenv("SSDB_ADDR") ssdbAddr := os.Getenv("SSDB_ADDR")
if ssdbAddr == "" { if ssdbAddr == "" {
ssdbAddr = "127.0.0.1:8888" ssdbAddr = "127.0.0.1:8888"

View File

@ -35,9 +35,7 @@ type FilterChainBuilder struct {
} }
func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filter { func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filter {
return func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) { return func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) {
method := req.GetRequest().Method method := req.GetRequest().Method
operationName := method + "#" + req.GetRequest().URL.String() operationName := method + "#" + req.GetRequest().URL.String()

View File

@ -32,11 +32,12 @@ type FilterChainBuilder struct {
RunMode string RunMode string
} }
var summaryVec prometheus.ObserverVec var (
var initSummaryVec sync.Once summaryVec prometheus.ObserverVec
initSummaryVec sync.Once
)
func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filter { func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filter {
initSummaryVec.Do(func() { initSummaryVec.Do(func() {
summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{ summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "beego", Name: "beego",

View File

@ -400,7 +400,6 @@ func (b *BeegoHTTPRequest) handleFileToBody(bodyWriter *multipart.Writer, formna
"could not create form file, formname: %s, filename: %s", formname, filename)) "could not create form file, formname: %s, filename: %s", formname, filename))
} }
fh, err := os.Open(filename) fh, err := os.Open(filename)
if err != nil { if err != nil {
logs.Error(errFmt, berror.Wrapf(err, ReadFileFailed, "could not open this file %s", filename)) logs.Error(errFmt, berror.Wrapf(err, ReadFileFailed, "could not open this file %s", filename))
} }

View File

@ -63,7 +63,6 @@ func TestDoRequest(t *testing.T) {
if elapsedTime < delayedTime { if elapsedTime < delayedTime {
t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime) t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime)
} }
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
@ -248,7 +247,6 @@ func TestToJson(t *testing.T) {
t.Fatal("response is not valid ip") t.Fatal("response is not valid ip")
} }
} }
} }
func TestToFile(t *testing.T) { func TestToFile(t *testing.T) {

View File

@ -23,10 +23,6 @@ import (
"github.com/beego/beego/v2/client/httplib" "github.com/beego/beego/v2/client/httplib"
) )
func init() {
}
func TestSimpleCondition_MatchPath(t *testing.T) { func TestSimpleCondition_MatchPath(t *testing.T) {
sc := NewSimpleCondition("/abc/s") sc := NewSimpleCondition("/abc/s")
res := sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s")) res := sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s"))
@ -72,7 +68,6 @@ func TestSimpleCondition_MatchHeader(t *testing.T) {
} }
func TestSimpleCondition_MatchBodyField(t *testing.T) { func TestSimpleCondition_MatchBodyField(t *testing.T) {
sc := NewSimpleCondition("/abc/s") sc := NewSimpleCondition("/abc/s")
req := httplib.Post("http://localhost:8080/abc/s") req := httplib.Post("http://localhost:8080/abc/s")

View File

@ -26,7 +26,6 @@ import (
) )
func TestStartMock(t *testing.T) { func TestStartMock(t *testing.T) {
// httplib.defaultSetting.FilterChains = []httplib.FilterChain{mockFilter.FilterChain} // httplib.defaultSetting.FilterChains = []httplib.FilterChain{mockFilter.FilterChain}
stub := StartMock() stub := StartMock()
@ -41,7 +40,6 @@ func TestStartMock(t *testing.T) {
assert.Equal(t, expectedErr, err) assert.Equal(t, expectedErr, err)
assert.Equal(t, expectedResp, resp) assert.Equal(t, expectedResp, resp)
} }
// TestStartMock_Isolation Test StartMock that // TestStartMock_Isolation Test StartMock that

View File

@ -68,8 +68,10 @@ var defaultSetting = BeegoHTTPSettings{
FilterChains: make([]FilterChain, 0, 4), FilterChains: make([]FilterChain, 0, 4),
} }
var defaultCookieJar http.CookieJar var (
var settingMutex sync.Mutex defaultCookieJar http.CookieJar
settingMutex sync.Mutex
)
// AddDefaultFilter add a new filter into defaultSetting // AddDefaultFilter add a new filter into defaultSetting
// Be careful about using this method if you invoke SetDefaultSetting somewhere // Be careful about using this method if you invoke SetDefaultSetting somewhere

View File

@ -18,8 +18,10 @@ import (
"github.com/beego/beego/v2/client/httplib" "github.com/beego/beego/v2/client/httplib"
) )
var port = "" var (
var baseURL = "http://localhost:" port = ""
baseURL = "http://localhost:"
)
// TestHTTPRequest beego test request client // TestHTTPRequest beego test request client
type TestHTTPRequest struct { type TestHTTPRequest struct {

View File

@ -5,9 +5,7 @@ import (
) )
func TestClause(t *testing.T) { func TestClause(t *testing.T) {
var ( column := `a`
column = `a`
)
o := Clause( o := Clause(
Column(column), Column(column),
@ -108,7 +106,6 @@ func TestParseOrder(t *testing.T) {
if orders[2].GetColumn() != `user.status` { if orders[2].GetColumn() != `user.status` {
t.Error() t.Error()
} }
} }
func TestOrder_GetColumn(t *testing.T) { func TestOrder_GetColumn(t *testing.T) {

View File

@ -27,9 +27,7 @@ type commander interface {
Run() error Run() error
} }
var ( var commands = make(map[string]commander)
commands = make(map[string]commander)
)
// print help. // print help.
func printHelp(errs ...string) { func printHelp(errs ...string) {

View File

@ -126,9 +126,7 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string {
// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands // Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands
func getColumnDefault(fi *fieldInfo) string { func getColumnDefault(fi *fieldInfo) string {
var ( var v, t, d string
v, t, d string
)
// Skip default attribute if field is in relations // Skip default attribute if field is in relations
if fi.rel || fi.reverse { if fi.rel || fi.reverse {

View File

@ -32,41 +32,37 @@ const (
formatDateTime = "2006-01-02 15:04:05" formatDateTime = "2006-01-02 15:04:05"
) )
var ( // ErrMissPK missing pk error
// ErrMissPK missing pk error var ErrMissPK = errors.New("missed pk value")
ErrMissPK = errors.New("missed pk value")
)
var ( var operators = map[string]bool{
operators = map[string]bool{ "exact": true,
"exact": true, "iexact": true,
"iexact": true, "strictexact": true,
"strictexact": true, "contains": true,
"contains": true, "icontains": true,
"icontains": true, // "regex": true,
// "regex": true, // "iregex": true,
// "iregex": true, "gt": true,
"gt": true, "gte": true,
"gte": true, "lt": true,
"lt": true, "lte": true,
"lte": true, "eq": true,
"eq": true, "nq": true,
"nq": true, "ne": true,
"ne": true, "startswith": true,
"startswith": true, "endswith": true,
"endswith": true, "istartswith": true,
"istartswith": true, "iendswith": true,
"iendswith": true, "in": true,
"in": true, "between": true,
"between": true, // "year": true,
// "year": true, // "month": true,
// "month": true, // "day": true,
// "day": true, // "week_day": true,
// "week_day": true, "isnull": true,
"isnull": true, // "search": true,
// "search": true, }
}
)
// an instance of dbBaser interface/ // an instance of dbBaser interface/
type dbBase struct { type dbBase struct {
@ -537,7 +533,6 @@ func (d *dbBase) InsertOrUpdate(ctx context.Context, q dbQuerier, mi *modelInfo,
names := make([]string, 0, len(mi.fields.dbcols)-1) names := make([]string, 0, len(mi.fields.dbcols)-1)
Q := d.ins.TableQuote() Q := d.ins.TableQuote()
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -934,7 +929,6 @@ func (d *dbBase) DeleteBatch(ctx context.Context, q dbQuerier, qs *querySet, mi
// read related records. // read related records.
func (d *dbBase) ReadBatch(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) { func (d *dbBase) ReadBatch(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) {
val := reflect.ValueOf(container) val := reflect.ValueOf(container)
ind := reflect.Indirect(val) ind := reflect.Indirect(val)
@ -1435,12 +1429,10 @@ end:
} }
return value, nil return value, nil
} }
// set one value to struct column field. // set one value to struct column field.
func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) { func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {
fieldType := fi.fieldType fieldType := fi.fieldType
isNative := !fi.isFielder isNative := !fi.isFielder
@ -1632,7 +1624,6 @@ setValue:
// query sql, read values , save to *[]ParamList. // query sql, read values , save to *[]ParamList.
func (d *dbBase) ReadValues(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) { func (d *dbBase) ReadValues(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) {
var ( var (
maps []Params maps []Params
lists []ParamsList lists []ParamsList

View File

@ -112,8 +112,10 @@ type DB struct {
stmtDecoratorsLimit int stmtDecoratorsLimit int
} }
var _ dbQuerier = new(DB) var (
var _ txer = new(DB) _ dbQuerier = new(DB)
_ txer = new(DB)
)
func (d *DB) Begin() (*sql.Tx, error) { func (d *DB) Begin() (*sql.Tx, error) {
return d.DB.Begin() return d.DB.Begin()
@ -221,8 +223,10 @@ type TxDB struct {
tx *sql.Tx tx *sql.Tx
} }
var _ dbQuerier = new(TxDB) var (
var _ txEnder = new(TxDB) _ dbQuerier = new(TxDB)
_ txEnder = new(TxDB)
)
func (t *TxDB) Commit() error { func (t *TxDB) Commit() error {
return t.tx.Commit() return t.tx.Commit()
@ -240,8 +244,10 @@ func (t *TxDB) RollbackUnlessCommit() error {
return nil return nil
} }
var _ dbQuerier = new(TxDB) var (
var _ txEnder = new(TxDB) _ dbQuerier = new(TxDB)
_ txEnder = new(TxDB)
)
func (t *TxDB) Prepare(query string) (*sql.Stmt, error) { func (t *TxDB) Prepare(query string) (*sql.Stmt, error) {
return t.PrepareContext(context.Background(), query) return t.PrepareContext(context.Background(), query)
@ -365,7 +371,6 @@ func addAliasWthDB(aliasName, driverName string, db *sql.DB, params ...DBOption)
} }
func newAliasWithDb(aliasName, driverName string, db *sql.DB, params ...DBOption) (*alias, error) { func newAliasWithDb(aliasName, driverName string, db *sql.DB, params ...DBOption) (*alias, error) {
al := &alias{} al := &alias{}
al.DB = &DB{ al.DB = &DB{
RWMutex: new(sync.RWMutex), RWMutex: new(sync.RWMutex),

View File

@ -124,7 +124,6 @@ func (d *dbBaseMysql) InsertOrUpdate(ctx context.Context, q dbQuerier, mi *model
names := make([]string, 0, len(mi.fields.dbcols)-1) names := make([]string, 0, len(mi.fields.dbcols)-1)
Q := d.ins.TableQuote() Q := d.ins.TableQuote()
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -106,7 +106,6 @@ func (t *dbTables) loopDepth(depth int, prefix string, fi *fieldInfo, related []
// parse related fields. // parse related fields.
func (t *dbTables) parseRelated(rels []string, depth int) { func (t *dbTables) parseRelated(rels []string, depth int) {
relsNum := len(rels) relsNum := len(rels)
related := make([]string, relsNum) related := make([]string, relsNum)
copy(related, rels) copy(related, rels)

View File

@ -55,7 +55,6 @@ func getExistPk(mi *modelInfo, ind reflect.Value) (column string, value interfac
// get fields description as flatted string. // get fields description as flatted string.
func getFlatParams(fi *fieldInfo, args []interface{}, tz *time.Location) (params []interface{}) { func getFlatParams(fi *fieldInfo, args []interface{}, tz *time.Location) (params []interface{}) {
outFor: outFor:
for _, arg := range args { for _, arg := range args {
val := reflect.ValueOf(arg) val := reflect.ValueOf(arg)

View File

@ -27,8 +27,7 @@ import (
var _ Ormer = new(DoNothingOrm) var _ Ormer = new(DoNothingOrm)
type DoNothingOrm struct { type DoNothingOrm struct{}
}
func (d *DoNothingOrm) Read(md interface{}, cols ...string) error { func (d *DoNothingOrm) Read(md interface{}, cols ...string) error {
return nil return nil

View File

@ -57,7 +57,6 @@ func TestDefaultValueFilterChainBuilder_FilterChain(t *testing.T) {
_, _ = o.InsertMulti(3, []*DefaultValueTestEntity{entity}) _, _ = o.InsertMulti(3, []*DefaultValueTestEntity{entity})
assert.Equal(t, 12, entity.Age) assert.Equal(t, 12, entity.Age)
assert.Equal(t, 13, entity.AgeInOldStyle) assert.Equal(t, 13, entity.AgeInOldStyle)
} }
type defaultValueTestOrm struct { type defaultValueTestOrm struct {

View File

@ -39,11 +39,12 @@ type FilterChainBuilder struct {
RunMode string RunMode string
} }
var summaryVec prometheus.ObserverVec var (
var initSummaryVec sync.Once summaryVec prometheus.ObserverVec
initSummaryVec sync.Once
)
func (builder *FilterChainBuilder) FilterChain(next orm.Filter) orm.Filter { func (builder *FilterChainBuilder) FilterChain(next orm.Filter) orm.Filter {
initSummaryVec.Do(func() { initSummaryVec.Do(func() {
summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{ summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "beego", Name: "beego",

View File

@ -58,5 +58,4 @@ func TestFilterChainBuilder_FilterChain1(t *testing.T) {
inv.Method = "Update" inv.Method = "Update"
builder.report(ctx, inv, time.Second) builder.report(ctx, inv, time.Second)
} }

View File

@ -28,8 +28,10 @@ const (
TxNameKey = "TxName" TxNameKey = "TxName"
) )
var _ Ormer = new(filterOrmDecorator) var (
var _ TxOrmer = new(filterOrmDecorator) _ Ormer = new(filterOrmDecorator)
_ TxOrmer = new(filterOrmDecorator)
)
type filterOrmDecorator struct { type filterOrmDecorator struct {
ormer ormer
@ -120,7 +122,6 @@ func (f *filterOrmDecorator) ReadOrCreate(md interface{}, col1 string, cols ...s
} }
func (f *filterOrmDecorator) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) { func (f *filterOrmDecorator) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "ReadOrCreateWithCtx", Method: "ReadOrCreateWithCtx",
@ -143,7 +144,6 @@ func (f *filterOrmDecorator) LoadRelated(md interface{}, name string, args ...ut
} }
func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) { func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "LoadRelatedWithCtx", Method: "LoadRelatedWithCtx",
@ -162,7 +162,6 @@ func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interfac
} }
func (f *filterOrmDecorator) QueryM2M(md interface{}, name string) QueryM2Mer { func (f *filterOrmDecorator) QueryM2M(md interface{}, name string) QueryM2Mer {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "QueryM2M", Method: "QueryM2M",

View File

@ -27,7 +27,6 @@ import (
) )
func TestFilterOrmDecorator_Read(t *testing.T) { func TestFilterOrmDecorator_Read(t *testing.T) {
register() register()
o := &filterMockOrm{} o := &filterMockOrm{}

View File

@ -116,7 +116,6 @@ func (m *Migration) UniCol(uni, name string) *Column {
// ForeignCol creates a new foreign column and returns the instance of column // ForeignCol creates a new foreign column and returns the instance of column
func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) { func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) {
foreign = &Foreign{ForeignColumn: foreigncol, ForeignTable: foreigntable} foreign = &Foreign{ForeignColumn: foreigncol, ForeignTable: foreigntable}
foreign.Name = colname foreign.Name = colname
m.AddForeign(foreign) m.AddForeign(foreign)
@ -153,7 +152,6 @@ func (c *Column) SetAuto(inc bool) *Column {
func (c *Column) SetNullable(null bool) *Column { func (c *Column) SetNullable(null bool) *Column {
if null { if null {
c.Null = "" c.Null = ""
} else { } else {
c.Null = "NOT NULL" c.Null = "NOT NULL"
} }
@ -184,7 +182,6 @@ func (c *Column) SetDataType(dataType string) *Column {
func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn { func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn {
if null { if null {
c.OldNull = "" c.OldNull = ""
} else { } else {
c.OldNull = "NOT NULL" c.OldNull = "NOT NULL"
} }
@ -219,7 +216,6 @@ func (c *Column) SetPrimary(m *Migration) *Column {
// AddColumnsToUnique adds the columns to Unique Struct // AddColumnsToUnique adds the columns to Unique Struct
func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique { func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
unique.Columns = append(unique.Columns, columns...) unique.Columns = append(unique.Columns, columns...)
return unique return unique
@ -227,7 +223,6 @@ func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
// AddColumns adds columns to m struct // AddColumns adds columns to m struct
func (m *Migration) AddColumns(columns ...*Column) *Migration { func (m *Migration) AddColumns(columns ...*Column) *Migration {
m.Columns = append(m.Columns, columns...) m.Columns = append(m.Columns, columns...)
return m return m

View File

@ -72,9 +72,7 @@ type Migration struct {
RemoveForeigns []*Foreign RemoveForeigns []*Foreign
} }
var ( var migrationMap map[string]Migrationer
migrationMap map[string]Migrationer
)
func init() { func init() {
migrationMap = make(map[string]Migrationer) migrationMap = make(map[string]Migrationer)
@ -82,7 +80,6 @@ func init() {
// Up implement in the Inheritance struct for upgrade // Up implement in the Inheritance struct for upgrade
func (m *Migration) Up() { func (m *Migration) Up() {
switch m.ModifyType { switch m.ModifyType {
case "reverse": case "reverse":
m.ModifyType = "alter" m.ModifyType = "alter"
@ -94,7 +91,6 @@ func (m *Migration) Up() {
// Down implement in the Inheritance struct for down // Down implement in the Inheritance struct for down
func (m *Migration) Down() { func (m *Migration) Down() {
switch m.ModifyType { switch m.ModifyType {
case "alter": case "alter":
m.ModifyType = "reverse" m.ModifyType = "reverse"
@ -311,6 +307,7 @@ func isRollBack(name string) bool {
} }
return false return false
} }
func getAllMigrations() (map[string]string, error) { func getAllMigrations() (map[string]string, error) {
o := orm.NewOrm() o := orm.NewOrm()
var maps []orm.Params var maps []orm.Params

View File

@ -55,7 +55,6 @@ func (o *OrmStub) Clear() {
func (o *OrmStub) FilterChain(next orm.Filter) orm.Filter { func (o *OrmStub) FilterChain(next orm.Filter) orm.Filter {
return func(ctx context.Context, inv *orm.Invocation) []interface{} { return func(ctx context.Context, inv *orm.Invocation) []interface{} {
ms := mockFromCtx(ctx) ms := mockFromCtx(ctx)
ms = append(ms, o.ms...) ms = append(ms, o.ms...)

View File

@ -247,7 +247,7 @@ func TestTransactionRollbackUnlessCommit(t *testing.T) {
mock := errors.New(mockErrorMsg) mock := errors.New(mockErrorMsg)
s.Mock(MockRollbackUnlessCommit(mock)) s.Mock(MockRollbackUnlessCommit(mock))
//u := &User{} // u := &User{}
o := orm.NewOrm() o := orm.NewOrm()
txOrm, _ := o.Begin() txOrm, _ := o.Begin()
err := txOrm.RollbackUnlessCommit() err := txOrm.RollbackUnlessCommit()

View File

@ -22,8 +22,7 @@ import (
// DoNothingQueryM2Mer do nothing // DoNothingQueryM2Mer do nothing
// use it to build mock orm.QueryM2Mer // use it to build mock orm.QueryM2Mer
type DoNothingQueryM2Mer struct { type DoNothingQueryM2Mer struct{}
}
func (d *DoNothingQueryM2Mer) AddWithCtx(ctx context.Context, i ...interface{}) (int64, error) { func (d *DoNothingQueryM2Mer) AddWithCtx(ctx context.Context, i ...interface{}) (int64, error) {
return 0, nil return 0, nil

View File

@ -23,8 +23,7 @@ import (
// DoNothingQuerySetter do nothing // DoNothingQuerySetter do nothing
// usually you use this to build your mock QuerySetter // usually you use this to build your mock QuerySetter
type DoNothingQuerySetter struct { type DoNothingQuerySetter struct{}
}
func (d *DoNothingQuerySetter) OrderClauses(orders ...*order_clause.Order) orm.QuerySeter { func (d *DoNothingQuerySetter) OrderClauses(orders ...*order_clause.Order) orm.QuerySeter {
return d return d

View File

@ -20,8 +20,7 @@ import (
"github.com/beego/beego/v2/client/orm" "github.com/beego/beego/v2/client/orm"
) )
type DoNothingRawSetter struct { type DoNothingRawSetter struct{}
}
func (d *DoNothingRawSetter) Exec() (sql.Result, error) { func (d *DoNothingRawSetter) Exec() (sql.Result, error) {
return nil, nil return nil, nil

View File

@ -32,9 +32,7 @@ const (
defaultStructTagDelim = ";" defaultStructTagDelim = ";"
) )
var ( var modelCache = NewModelCacheHandler()
modelCache = NewModelCacheHandler()
)
// model info collection // model info collection
type _modelCache struct { type _modelCache struct {
@ -332,7 +330,6 @@ end:
// register register models to model cache // register register models to model cache
func (mc *_modelCache) register(prefixOrSuffixStr string, prefixOrSuffix bool, models ...interface{}) (err error) { func (mc *_modelCache) register(prefixOrSuffixStr string, prefixOrSuffix bool, models ...interface{}) (err error) {
for _, model := range models { for _, model := range models {
val := reflect.ValueOf(model) val := reflect.ValueOf(model)
typ := reflect.Indirect(val).Type() typ := reflect.Indirect(val).Type()

View File

@ -387,7 +387,6 @@ checkType:
fi.timePrecision = &v fi.timePrecision = &v
} }
} }
} }
if attrs["auto_now"] { if attrs["auto_now"] {

View File

@ -193,22 +193,24 @@ type DataNull struct {
DateTimePtr *time.Time `orm:"null"` DateTimePtr *time.Time `orm:"null"`
} }
type String string type (
type Boolean bool String string
type Byte byte Boolean bool
type Rune rune Byte byte
type Int int Rune rune
type Int8 int8 Int int
type Int16 int16 Int8 int8
type Int32 int32 Int16 int16
type Int64 int64 Int32 int32
type Uint uint Int64 int64
type Uint8 uint8 Uint uint
type Uint16 uint16 Uint8 uint8
type Uint32 uint32 Uint16 uint16
type Uint64 uint64 Uint32 uint32
type Float32 float64 Uint64 uint64
type Float64 float64 Float32 float64
Float64 float64
)
type DataCustom struct { type DataCustom struct {
ID int `orm:"column(id)"` ID int `orm:"column(id)"`
@ -486,8 +488,7 @@ var (
dDbBaser dbBaser dDbBaser dbBaser
) )
var ( var helpinfo = `need driver and source!
helpinfo = `need driver and source!
Default DB Drivers. Default DB Drivers.
@ -530,7 +531,6 @@ var (
go test -v github.com/beego/beego/v2/pgk/orm go test -v github.com/beego/beego/v2/pgk/orm
` `
)
func init() { func init() {
// Debug, _ = StrTo(DBARGS.Debug).Bool() // Debug, _ = StrTo(DBARGS.Debug).Bool()
@ -542,7 +542,6 @@ func init() {
} }
err := RegisterDataBase("default", DBARGS.Driver, DBARGS.Source, MaxIdleConnections(20)) err := RegisterDataBase("default", DBARGS.Driver, DBARGS.Source, MaxIdleConnections(20))
if err != nil { if err != nil {
panic(fmt.Sprintf("can not register database: %v", err)) panic(fmt.Sprintf("can not register database: %v", err))
} }
@ -551,5 +550,4 @@ func init() {
if alias.Driver == DRMySQL { if alias.Driver == DRMySQL {
alias.Engine = "INNODB" alias.Engine = "INNODB"
} }
} }

View File

@ -101,9 +101,11 @@ type ormBase struct {
db dbQuerier db dbQuerier
} }
var _ DQL = new(ormBase) var (
var _ DML = new(ormBase) _ DQL = new(ormBase)
var _ DriverGetter = new(ormBase) _ DML = new(ormBase)
_ DriverGetter = new(ormBase)
)
// get model info and model reflect value // get model info and model reflect value
func (o *ormBase) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) { func (o *ormBase) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) {
@ -133,6 +135,7 @@ func (o *ormBase) getFieldInfo(mi *modelInfo, name string) *fieldInfo {
func (o *ormBase) Read(md interface{}, cols ...string) error { func (o *ormBase) Read(md interface{}, cols ...string) error {
return o.ReadWithCtx(context.Background(), md, cols...) return o.ReadWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...string) error { func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...string) error {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, false) return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, false)
@ -142,6 +145,7 @@ func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...strin
func (o *ormBase) ReadForUpdate(md interface{}, cols ...string) error { func (o *ormBase) ReadForUpdate(md interface{}, cols ...string) error {
return o.ReadForUpdateWithCtx(context.Background(), md, cols...) return o.ReadForUpdateWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols ...string) error { func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols ...string) error {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, true) return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, true)
@ -151,6 +155,7 @@ func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols
func (o *ormBase) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) { func (o *ormBase) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) {
return o.ReadOrCreateWithCtx(context.Background(), md, col1, cols...) return o.ReadOrCreateWithCtx(context.Background(), md, col1, cols...)
} }
func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) { func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) {
cols = append([]string{col1}, cols...) cols = append([]string{col1}, cols...)
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
@ -177,6 +182,7 @@ func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1
func (o *ormBase) Insert(md interface{}) (int64, error) { func (o *ormBase) Insert(md interface{}) (int64, error) {
return o.InsertWithCtx(context.Background(), md) return o.InsertWithCtx(context.Background(), md)
} }
func (o *ormBase) InsertWithCtx(ctx context.Context, md interface{}) (int64, error) { func (o *ormBase) InsertWithCtx(ctx context.Context, md interface{}) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
id, err := o.alias.DbBaser.Insert(ctx, o.db, mi, ind, o.alias.TZ) id, err := o.alias.DbBaser.Insert(ctx, o.db, mi, ind, o.alias.TZ)
@ -204,6 +210,7 @@ func (o *ormBase) setPk(mi *modelInfo, ind reflect.Value, id int64) {
func (o *ormBase) InsertMulti(bulk int, mds interface{}) (int64, error) { func (o *ormBase) InsertMulti(bulk int, mds interface{}) (int64, error) {
return o.InsertMultiWithCtx(context.Background(), bulk, mds) return o.InsertMultiWithCtx(context.Background(), bulk, mds)
} }
func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interface{}) (int64, error) { func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interface{}) (int64, error) {
var cnt int64 var cnt int64
@ -242,6 +249,7 @@ func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interfac
func (o *ormBase) InsertOrUpdate(md interface{}, colConflictAndArgs ...string) (int64, error) { func (o *ormBase) InsertOrUpdate(md interface{}, colConflictAndArgs ...string) (int64, error) {
return o.InsertOrUpdateWithCtx(context.Background(), md, colConflictAndArgs...) return o.InsertOrUpdateWithCtx(context.Background(), md, colConflictAndArgs...)
} }
func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error) { func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
id, err := o.alias.DbBaser.InsertOrUpdate(ctx, o.db, mi, ind, o.alias, colConflitAndArgs...) id, err := o.alias.DbBaser.InsertOrUpdate(ctx, o.db, mi, ind, o.alias, colConflitAndArgs...)
@ -259,6 +267,7 @@ func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, col
func (o *ormBase) Update(md interface{}, cols ...string) (int64, error) { func (o *ormBase) Update(md interface{}, cols ...string) (int64, error) {
return o.UpdateWithCtx(context.Background(), md, cols...) return o.UpdateWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) { func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Update(ctx, o.db, mi, ind, o.alias.TZ, cols) return o.alias.DbBaser.Update(ctx, o.db, mi, ind, o.alias.TZ, cols)
@ -269,6 +278,7 @@ func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...str
func (o *ormBase) Delete(md interface{}, cols ...string) (int64, error) { func (o *ormBase) Delete(md interface{}, cols ...string) (int64, error) {
return o.DeleteWithCtx(context.Background(), md, cols...) return o.DeleteWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) { func (o *ormBase) DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
num, err := o.alias.DbBaser.Delete(ctx, o.db, mi, ind, o.alias.TZ, cols) num, err := o.alias.DbBaser.Delete(ctx, o.db, mi, ind, o.alias.TZ, cols)
@ -313,6 +323,7 @@ func (o *ormBase) QueryM2MWithCtx(_ context.Context, md interface{}, name string
func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) { func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) {
return o.LoadRelatedWithCtx(context.Background(), md, name, args...) return o.LoadRelatedWithCtx(context.Background(), md, name, args...)
} }
func (o *ormBase) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) { func (o *ormBase) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) {
_, fi, ind, qs := o.queryRelated(md, name) _, fi, ind, qs := o.queryRelated(md, name)
@ -482,6 +493,7 @@ func (o *ormBase) QueryTableWithCtx(_ context.Context, ptrStructOrTableName inte
func (o *ormBase) Raw(query string, args ...interface{}) RawSeter { func (o *ormBase) Raw(query string, args ...interface{}) RawSeter {
return o.RawWithCtx(context.Background(), query, args...) return o.RawWithCtx(context.Background(), query, args...)
} }
func (o *ormBase) RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSeter { func (o *ormBase) RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSeter {
return newRawSet(o, query, args) return newRawSet(o, query, args)
} }
@ -571,7 +583,7 @@ func doTxTemplate(o TxBeginner, ctx context.Context, opts *sql.TxOptions,
} }
} }
}() }()
var taskTxOrm = _txOrm taskTxOrm := _txOrm
err = task(ctx, taskTxOrm) err = task(ctx, taskTxOrm)
panicked = false panicked = false
return err return err

View File

@ -78,7 +78,6 @@ func (c Condition) AndNot(expr string, args ...interface{}) *Condition {
// AndCond combine a condition to current condition // AndCond combine a condition to current condition
func (c *Condition) AndCond(cond *Condition) *Condition { func (c *Condition) AndCond(cond *Condition) *Condition {
if c == cond { if c == cond {
panic(fmt.Errorf("<Condition.AndCond> cannot use self as sub cond")) panic(fmt.Errorf("<Condition.AndCond> cannot use self as sub cond"))
} }

View File

@ -40,7 +40,7 @@ func NewLog(out io.Writer) *Log {
} }
func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) { func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) {
var logMap = make(map[string]interface{}) logMap := make(map[string]interface{})
sub := time.Since(t) / 1e5 sub := time.Since(t) / 1e5
elsp := float64(int(sub)) / 10.0 elsp := float64(int(sub)) / 10.0
logMap["cost_time"] = elsp logMap["cost_time"] = elsp
@ -94,6 +94,7 @@ func (d *stmtQueryLog) ExecContext(ctx context.Context, args ...interface{}) (sq
debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...) debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...)
return res, err return res, err
} }
func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) { func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) {
return d.QueryContext(context.Background(), args...) return d.QueryContext(context.Background(), args...)
} }
@ -133,9 +134,11 @@ type dbQueryLog struct {
txe txEnder txe txEnder
} }
var _ dbQuerier = new(dbQueryLog) var (
var _ txer = new(dbQueryLog) _ dbQuerier = new(dbQueryLog)
var _ txEnder = new(dbQueryLog) _ txer = new(dbQueryLog)
_ txEnder = new(dbQueryLog)
)
func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) { func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) {
return d.PrepareContext(context.Background(), query) return d.PrepareContext(context.Background(), query)

View File

@ -253,7 +253,6 @@ func (o *rawSet) loopSetRefs(refs []interface{}, sInds []reflect.Value, nIndsPtr
} }
cur++ cur++
} }
} else { } else {
value := reflect.ValueOf(refs[cur]).Elem().Interface() value := reflect.ValueOf(refs[cur]).Elem().Interface()
if isPtr && value == nil { if isPtr && value == nil {
@ -437,7 +436,6 @@ func (o *rawSet) QueryRow(containers ...interface{}) error {
sInd.Set(nInd) sInd.Set(nInd)
} }
} }
} else { } else {
return ErrNoRows return ErrNoRows
} }
@ -606,7 +604,6 @@ func (o *rawSet) QueryRows(containers ...interface{}) (int64, error) {
} }
if cnt > 0 { if cnt > 0 {
if structMode { if structMode {
sInds[0].Set(sInd) sInds[0].Set(sInd)
} else { } else {

View File

@ -842,7 +842,6 @@ The program—and web server—godoc processes Go source files to extract docume
throwFailNow(t, AssertIs(nums, num)) throwFailNow(t, AssertIs(nums, num))
} }
} }
} }
func TestCustomField(t *testing.T) { func TestCustomField(t *testing.T) {
@ -1235,7 +1234,6 @@ func TestOne(t *testing.T) {
err = qs.Filter("user_name", "nothing").One(&user) err = qs.Filter("user_name", "nothing").One(&user)
throwFail(t, AssertIs(err, ErrNoRows)) throwFail(t, AssertIs(err, ErrNoRows))
} }
func TestValues(t *testing.T) { func TestValues(t *testing.T) {
@ -1285,8 +1283,8 @@ func TestValuesList(t *testing.T) {
throwFail(t, err) throwFail(t, err)
throwFail(t, AssertIs(num, 3)) throwFail(t, AssertIs(num, 3))
if num == 3 { if num == 3 {
throwFail(t, AssertIs(list[0][1], "slene")) //username throwFail(t, AssertIs(list[0][1], "slene")) // username
throwFail(t, AssertIs(list[2][10], nil)) //profile throwFail(t, AssertIs(list[2][10], nil)) // profile
} }
num, err = qs.OrderBy("Id").ValuesList(&list, "UserName", "Profile__Age") num, err = qs.OrderBy("Id").ValuesList(&list, "UserName", "Profile__Age")
@ -2219,7 +2217,7 @@ func TestTransaction(t *testing.T) {
to, err := o.Begin() to, err := o.Begin()
throwFail(t, err) throwFail(t, err)
var names = []string{"1", "2", "3"} names := []string{"1", "2", "3"}
var tag Tag var tag Tag
tag.Name = names[0] tag.Name = names[0]
@ -2262,7 +2260,6 @@ func TestTransaction(t *testing.T) {
num, err = o.QueryTable("tag").Filter("name", "commit").Delete() num, err = o.QueryTable("tag").Filter("name", "commit").Delete()
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, int64(1), num) assert.Equal(t, int64(1), num)
} }
func TestTxOrmRollbackUnlessCommit(t *testing.T) { func TestTxOrmRollbackUnlessCommit(t *testing.T) {
@ -2763,6 +2760,7 @@ func TestStrPkInsert(t *testing.T) {
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
if err.Error() == "postgres version must 9.5 or higher" || err.Error() == "`sqlite3` nonsupport InsertOrUpdate in beego" { if err.Error() == "postgres version must 9.5 or higher" || err.Error() == "`sqlite3` nonsupport InsertOrUpdate in beego" {
return
} else if err == ErrLastInsertIdUnavailable { } else if err == ErrLastInsertIdUnavailable {
return return
} else { } else {

View File

@ -21,7 +21,6 @@ func processingStr(str []string) string {
// Select will join the fields // Select will join the fields
func (qb *PostgresQueryBuilder) Select(fields ...string) QueryBuilder { func (qb *PostgresQueryBuilder) Select(fields ...string) QueryBuilder {
var str string var str string
n := len(fields) n := len(fields)
@ -80,7 +79,6 @@ func (qb *PostgresQueryBuilder) RightJoin(table string) QueryBuilder {
// On join with on cond // On join with on cond
func (qb *PostgresQueryBuilder) On(cond string) QueryBuilder { func (qb *PostgresQueryBuilder) On(cond string) QueryBuilder {
var str string var str string
cond = strings.Replace(cond, " ", "", -1) cond = strings.Replace(cond, " ", "", -1)
slice := strings.Split(cond, "=") slice := strings.Split(cond, "=")

View File

@ -246,7 +246,7 @@ type ormer interface {
DriverGetter DriverGetter
} }
//QueryExecutor wrapping for ormer // QueryExecutor wrapping for ormer
type QueryExecutor interface { type QueryExecutor interface {
ormer ormer
} }

View File

@ -29,8 +29,10 @@ import (
"github.com/beego/beego/v2/core/utils" "github.com/beego/beego/v2/core/utils"
) )
var startTime = time.Now() var (
var pid int startTime = time.Now()
pid int
)
func init() { func init() {
pid = os.Getpid() pid = os.Getpid()
@ -105,7 +107,6 @@ func PrintGCSummary(w io.Writer) {
} }
func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {
if gcstats.NumGC > 0 { if gcstats.NumGC > 0 {
lastPause := gcstats.Pause[0] lastPause := gcstats.Pause[0]
elapsed := time.Since(startTime) elapsed := time.Since(startTime)

View File

@ -16,5 +16,4 @@ package bean
// ApplicationContext define for future // ApplicationContext define for future
// when we decide to support DI, IoC, this will be core API // when we decide to support DI, IoC, this will be core API
type ApplicationContext interface { type ApplicationContext interface{}
}

View File

@ -46,6 +46,7 @@ func init() {
func goCodeBlock(code string) string { func goCodeBlock(code string) string {
return codeBlock("go", code) return codeBlock("go", code)
} }
func codeBlock(lan string, code string) string { func codeBlock(lan string, code string) string {
return fmt.Sprintf("```%s\n%s\n```", lan, code) return fmt.Sprintf("```%s\n%s\n```", lan, code)
} }

View File

@ -66,7 +66,6 @@ func newBaseConfier(str1 string) *BaseConfiger {
} else { } else {
return "", errors.New("mock error") return "", errors.New("mock error")
} }
}, },
} }
} }

View File

@ -165,6 +165,7 @@ func (c *BaseConfiger) DefaultBool(key string, defaultVal bool) bool {
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 { func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 {
if res, err := c.Float(key); err == nil { if res, err := c.Float(key); err == nil {
return res return res
@ -370,5 +371,4 @@ func ToString(x interface{}) string {
type DecodeOption func(options decodeOptions) type DecodeOption func(options decodeOptions)
type decodeOptions struct { type decodeOptions struct{}
}

View File

@ -20,7 +20,6 @@ import (
) )
func TestExpandValueEnv(t *testing.T) { func TestExpandValueEnv(t *testing.T) {
testCases := []struct { testCases := []struct {
item string item string
want string want string
@ -51,5 +50,4 @@ func TestExpandValueEnv(t *testing.T) {
t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got) t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got)
} }
} }
} }

View File

@ -119,7 +119,6 @@ func (e *EtcdConfiger) Sub(key string) (config.Configer, error) {
// TODO remove this before release v2.0.0 // TODO remove this before release v2.0.0
func (e *EtcdConfiger) OnChange(key string, fn func(value string)) { func (e *EtcdConfiger) OnChange(key string, fn func(value string)) {
buildOptsFunc := func() []clientv3.OpOption { buildOptsFunc := func() []clientv3.OpOption {
return []clientv3.OpOption{} return []clientv3.OpOption{}
} }
@ -144,11 +143,9 @@ func (e *EtcdConfiger) OnChange(key string, fn func(value string)) {
rch = e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...) rch = e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...)
} }
}() }()
} }
type EtcdConfigerProvider struct { type EtcdConfigerProvider struct{}
}
// Parse = ParseData([]byte(key)) // Parse = ParseData([]byte(key))
// key must be json // key must be json

View File

@ -32,7 +32,6 @@ func TestEtcdConfigerProvider_Parse(t *testing.T) {
} }
func TestEtcdConfiger(t *testing.T) { func TestEtcdConfiger(t *testing.T) {
provider := &EtcdConfigerProvider{} provider := &EtcdConfigerProvider{}
cfger, _ := provider.Parse(readEtcdConfig()) cfger, _ := provider.Parse(readEtcdConfig())

View File

@ -42,15 +42,19 @@ func String(key string) (string, error) {
func Strings(key string) ([]string, error) { func Strings(key string) ([]string, error) {
return globalInstance.Strings(key) return globalInstance.Strings(key)
} }
func Int(key string) (int, error) { func Int(key string) (int, error) {
return globalInstance.Int(key) return globalInstance.Int(key)
} }
func Int64(key string) (int64, error) { func Int64(key string) (int64, error) {
return globalInstance.Int64(key) return globalInstance.Int64(key)
} }
func Bool(key string) (bool, error) { func Bool(key string) (bool, error) {
return globalInstance.Bool(key) return globalInstance.Bool(key)
} }
func Float(key string) (float64, error) { func Float(key string) (float64, error) {
return globalInstance.Float(key) return globalInstance.Float(key)
} }
@ -64,15 +68,19 @@ func DefaultString(key string, defaultVal string) string {
func DefaultStrings(key string, defaultVal []string) []string { func DefaultStrings(key string, defaultVal []string) []string {
return globalInstance.DefaultStrings(key, defaultVal) return globalInstance.DefaultStrings(key, defaultVal)
} }
func DefaultInt(key string, defaultVal int) int { func DefaultInt(key string, defaultVal int) int {
return globalInstance.DefaultInt(key, defaultVal) return globalInstance.DefaultInt(key, defaultVal)
} }
func DefaultInt64(key string, defaultVal int64) int64 { func DefaultInt64(key string, defaultVal int64) int64 {
return globalInstance.DefaultInt64(key, defaultVal) return globalInstance.DefaultInt64(key, defaultVal)
} }
func DefaultBool(key string, defaultVal bool) bool { func DefaultBool(key string, defaultVal bool) bool {
return globalInstance.DefaultBool(key, defaultVal) return globalInstance.DefaultBool(key, defaultVal)
} }
func DefaultFloat(key string, defaultVal float64) float64 { func DefaultFloat(key string, defaultVal float64) float64 {
return globalInstance.DefaultFloat(key, defaultVal) return globalInstance.DefaultFloat(key, defaultVal)
} }
@ -89,6 +97,7 @@ func GetSection(section string) (map[string]string, error) {
func Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error { func Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error {
return globalInstance.Unmarshaler(prefix, obj, opt...) return globalInstance.Unmarshaler(prefix, obj, opt...)
} }
func Sub(key string) (Configer, error) { func Sub(key string) (Configer, error) {
return globalInstance.Sub(key) return globalInstance.Sub(key)
} }

View File

@ -46,8 +46,7 @@ var (
) )
// IniConfig implements Config to parse ini file. // IniConfig implements Config to parse ini file.
type IniConfig struct { type IniConfig struct{}
}
// Parse creates a new Config and parses the file configuration from the named file. // Parse creates a new Config and parses the file configuration from the named file.
func (ini *IniConfig) Parse(name string) (Configer, error) { func (ini *IniConfig) Parse(name string) (Configer, error) {

View File

@ -23,7 +23,6 @@ import (
) )
func TestIni(t *testing.T) { func TestIni(t *testing.T) {
var ( var (
inicontext = ` inicontext = `
;comment one ;comment one
@ -129,11 +128,9 @@ password = ${GOPATH}
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
} }
func TestIniSave(t *testing.T) { func TestIniSave(t *testing.T) {
const ( const (
inicontext = ` inicontext = `
app = app app = app

View File

@ -31,8 +31,7 @@ import (
) )
// JSONConfig is a json config parser and implements Config interface. // JSONConfig is a json config parser and implements Config interface.
type JSONConfig struct { type JSONConfig struct{}
}
// Parse returns a ConfigContainer with parsed json config map. // Parse returns a ConfigContainer with parsed json config map.
func (js *JSONConfig) Parse(filename string) (config.Configer, error) { func (js *JSONConfig) Parse(filename string) (config.Configer, error) {
@ -211,7 +210,6 @@ func (c *JSONConfigContainer) String(key string) (string, error) {
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultString(key string, defaultVal string) string { func (c *JSONConfigContainer) DefaultString(key string, defaultVal string) string {
// TODO FIXME should not use "" to replace non existence
if v, err := c.String(key); v != "" && err == nil { if v, err := c.String(key); v != "" && err == nil {
return v return v
} }

View File

@ -25,7 +25,6 @@ import (
) )
func TestJsonStartsWithArray(t *testing.T) { func TestJsonStartsWithArray(t *testing.T) {
const jsoncontextwitharray = `[ const jsoncontextwitharray = `[
{ {
"url": "user", "url": "user",
@ -72,7 +71,6 @@ func TestJsonStartsWithArray(t *testing.T) {
} }
func TestJson(t *testing.T) { func TestJson(t *testing.T) {
var ( var (
jsoncontext = `{ jsoncontext = `{
"appname": "beeapi", "appname": "beeapi",

View File

@ -47,7 +47,6 @@ func (c *Config) ParseData(data []byte) (config.Configer, error) {
return &configContainer{ return &configContainer{
t: t, t: t,
}, nil }, nil
} }
// configContainer support key looks like "a.b.c" // configContainer support key looks like "a.b.c"
@ -70,7 +69,6 @@ func (c *configContainer) Set(key, val string) error {
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) String(key string) (string, error) { func (c *configContainer) String(key string) (string, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -90,7 +88,6 @@ func (c *configContainer) String(key string) (string, error) {
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Strings(key string) ([]string, error) { func (c *configContainer) Strings(key string) ([]string, error) {
val, err := c.get(key) val, err := c.get(key)
if err != nil { if err != nil {
return []string{}, err return []string{}, err
} }
@ -141,9 +138,7 @@ func (c *configContainer) Int64(key string) (int64, error) {
// bool return bool value // bool return bool value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Bool(key string) (bool, error) { func (c *configContainer) Bool(key string) (bool, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -330,7 +325,6 @@ func (c *configContainer) get(key string) (interface{}, error) {
segs := strings.Split(key, keySeparator) segs := strings.Split(key, keySeparator)
t, err := subTree(c.t, segs[0:len(segs)-1]) t, err := subTree(c.t, segs[0:len(segs)-1])
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -102,7 +102,6 @@ func (c *ConfigContainer) Sub(key string) (config.Configer, error) {
return &ConfigContainer{ return &ConfigContainer{
data: sub, data: sub,
}, nil }, nil
} }
func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) { func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) {
@ -170,7 +169,6 @@ func (c *ConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
return defaultVal return defaultVal
} }
return v return v
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.

View File

@ -25,7 +25,6 @@ import (
) )
func TestXML(t *testing.T) { func TestXML(t *testing.T) {
var ( var (
// xml parse should incluce in <config></config> tags // xml parse should incluce in <config></config> tags
xmlcontext = `<?xml version="1.0" encoding="UTF-8"?> xmlcontext = `<?xml version="1.0" encoding="UTF-8"?>
@ -149,7 +148,6 @@ func TestXML(t *testing.T) {
err = xmlconf.Unmarshaler("mysection", sec) err = xmlconf.Unmarshaler("mysection", sec)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "MySection", sec.Name) assert.Equal(t, "MySection", sec.Name)
} }
type Section struct { type Section struct {

View File

@ -302,7 +302,6 @@ func (c *ConfigContainer) DefaultStrings(key string, defaultVal []string) []stri
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *ConfigContainer) GetSection(section string) (map[string]string, error) { func (c *ConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section]; ok { if v, ok := c.data[section]; ok {
return v.(map[string]string), nil return v.(map[string]string), nil
} }
@ -335,7 +334,6 @@ func (c *ConfigContainer) DIY(key string) (v interface{}, err error) {
} }
func (c *ConfigContainer) getData(key string) (interface{}, error) { func (c *ConfigContainer) getData(key string) (interface{}, error) {
if len(key) == 0 { if len(key) == 0 {
return nil, errors.New("key is empty") return nil, errors.New("key is empty")
} }

View File

@ -25,7 +25,6 @@ import (
) )
func TestYaml(t *testing.T) { func TestYaml(t *testing.T) {
var ( var (
yamlcontext = ` yamlcontext = `
"appname": beeapi "appname": beeapi

View File

@ -180,7 +180,6 @@ func (c *aliLSWriter) WriteMsg(lm *logs.LogMsg) error {
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *aliLSWriter) Flush() { func (c *aliLSWriter) Flush() {
// flush all group // flush all group
for _, lg := range c.group { for _, lg := range c.group {
c.flush(lg) c.flush(lg)
@ -192,7 +191,6 @@ func (c *aliLSWriter) Destroy() {
} }
func (c *aliLSWriter) flush(lg *LogGroup) { func (c *aliLSWriter) flush(lg *LogGroup) {
c.lock.Lock() c.lock.Lock()
defer c.lock.Unlock() defer c.lock.Unlock()
err := c.store.PutLogs(lg) err := c.store.PutLogs(lg)

View File

@ -128,7 +128,6 @@ func (p *LogProject) GetLogStore(name string) (s *LogStore, err error) {
// and ttl is time-to-live(in day) of logs, // and ttl is time-to-live(in day) of logs,
// and shardCnt is the number of shards. // and shardCnt is the number of shards.
func (p *LogProject) CreateLogStore(name string, ttl, shardCnt int) (err error) { func (p *LogProject) CreateLogStore(name string, ttl, shardCnt int) (err error) {
type Body struct { type Body struct {
Name string `json:"logstoreName"` Name string `json:"logstoreName"`
TTL int `json:"ttl"` TTL int `json:"ttl"`
@ -212,7 +211,6 @@ func (p *LogProject) DeleteLogStore(name string) (err error) {
// UpdateLogStore updates a logstore according by logstore name, // UpdateLogStore updates a logstore according by logstore name,
// obviously we can't modify the logstore name itself. // obviously we can't modify the logstore name itself.
func (p *LogProject) UpdateLogStore(name string, ttl, shardCnt int) (err error) { func (p *LogProject) UpdateLogStore(name string, ttl, shardCnt int) (err error) {
type Body struct { type Body struct {
Name string `json:"logstoreName"` Name string `json:"logstoreName"`
TTL int `json:"ttl"` TTL int `json:"ttl"`
@ -355,7 +353,6 @@ func (p *LogProject) GetMachineGroup(name string) (m *MachineGroup, err error) {
// CreateMachineGroup creates a new machine group in SLS. // CreateMachineGroup creates a new machine group in SLS.
func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) { func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) {
body, err := json.Marshal(m) body, err := json.Marshal(m)
if err != nil { if err != nil {
return return
@ -395,7 +392,6 @@ func (p *LogProject) CreateMachineGroup(m *MachineGroup) (err error) {
// UpdateMachineGroup updates a machine group. // UpdateMachineGroup updates a machine group.
func (p *LogProject) UpdateMachineGroup(m *MachineGroup) (err error) { func (p *LogProject) UpdateMachineGroup(m *MachineGroup) (err error) {
body, err := json.Marshal(m) body, err := json.Marshal(m)
if err != nil { if err != nil {
return return
@ -555,7 +551,6 @@ func (p *LogProject) GetConfig(name string) (c *LogConfig, err error) {
// UpdateConfig updates a config. // UpdateConfig updates a config.
func (p *LogProject) UpdateConfig(c *LogConfig) (err error) { func (p *LogProject) UpdateConfig(c *LogConfig) (err error) {
body, err := json.Marshal(c) body, err := json.Marshal(c)
if err != nil { if err != nil {
return return
@ -595,7 +590,6 @@ func (p *LogProject) UpdateConfig(c *LogConfig) (err error) {
// CreateConfig creates a new config in SLS. // CreateConfig creates a new config in SLS.
func (p *LogProject) CreateConfig(c *LogConfig) (err error) { func (p *LogProject) CreateConfig(c *LogConfig) (err error) {
body, err := json.Marshal(c) body, err := json.Marshal(c)
if err != nil { if err != nil {
return return

View File

@ -241,7 +241,6 @@ func (s *LogStore) GetLogsBytes(shardID int, cursor string,
// LogsBytesDecode decodes logs binary data retruned by GetLogsBytes API // LogsBytesDecode decodes logs binary data retruned by GetLogsBytes API
func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) { func LogsBytesDecode(data []byte) (gl *LogGroupList, err error) {
gl = &LogGroupList{} gl = &LogGroupList{}
err = proto.Unmarshal(data, gl) err = proto.Unmarshal(data, gl)
if err != nil { if err != nil {

View File

@ -95,7 +95,6 @@ func (c *connWriter) WriteMsg(lm *LogMsg) error {
// Flush implementing method. empty. // Flush implementing method. empty.
func (c *connWriter) Flush() { func (c *connWriter) Flush() {
} }
// Destroy destroy connection writer and close tcp listener. // Destroy destroy connection writer and close tcp listener.

View File

@ -26,7 +26,6 @@ import (
// ConnTCPListener takes a TCP listener and accepts n TCP connections // ConnTCPListener takes a TCP listener and accepts n TCP connections
// Returns connections using connChan // Returns connections using connChan
func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) { func connTCPListener(t *testing.T, n int, ln net.Listener, connChan chan<- net.Conn) {
// Listen and accept n incoming connections // Listen and accept n incoming connections
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
conn, err := ln.Accept() conn, err := ln.Accept()

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