diff --git a/.github/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE index db349198..8e474075 100644 --- a/.github/ISSUE_TEMPLATE +++ b/.github/ISSUE_TEMPLATE @@ -14,4 +14,4 @@ A complete runnable program is good. 4. What did you expect to see? -5. What did you see instead? \ No newline at end of file +5. What did you see instead? diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 00000000..7e4b1032 --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,34 @@ +# This action requires that any PR targeting the master branch should touch at +# least one CHANGELOG file. If a CHANGELOG entry is not required, add the "Skip +# Changelog" label to disable this action. + +name: changelog + +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + branches: + - master + +jobs: + changelog: + runs-on: ubuntu-latest + if: "!contains(github.event.pull_request.labels.*.name, 'Skip Changelog')" + + steps: + - uses: actions/checkout@v2 + + - name: Check for CHANGELOG changes + run: | + # Only the latest commit of the feature branch is available + # automatically. To diff with the base branch, we need to + # fetch that too (and we only need its latest commit). + git fetch origin ${{ github.base_ref }} --depth=1 + if [[ $(git diff --name-only FETCH_HEAD | grep CHANGELOG) ]] + then + echo "A CHANGELOG was modified. Looks good!" + else + echo "No CHANGELOG was modified." + echo "Please add a CHANGELOG entry, or add the \"Skip Changelog\" label if not required." + false + fi \ No newline at end of file diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 3a4d2e9a..412274a3 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -16,4 +16,4 @@ jobs: stale-issue-message: 'This issue is inactive for a long time.' stale-pr-message: 'This PR is inactive for a long time' stale-issue-label: 'inactive-issue' - stale-pr-label: 'inactive-pr' \ No newline at end of file + stale-pr-label: 'inactive-pr' diff --git a/.gitignore b/.gitignore index 304c4b73..0306c438 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ _beeTmp2/ pkg/_beeTmp/ pkg/_beeTmp2/ test/tmp/ + +profile.out diff --git a/.travis.yml b/.travis.yml index 973b40ef..252ec905 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,12 +10,13 @@ services: - docker env: global: - - GO_REPO_FULLNAME="github.com/astaxie/beego" + - 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// - GO_REPO_NAMESPACE=${GO_REPO_FULLNAME%/*} # relies on GOPATH to contain only one directory... @@ -62,6 +63,7 @@ install: - go get github.com/gomodule/redigo/redis - go get github.com/beego/x2j - go get github.com/couchbase/go-couchbase + - go get -u github.com/couchbase/gomemcached@master - go get github.com/beego/goyaml2 - go get gopkg.in/yaml.v2 - go get github.com/belogik/goes @@ -94,12 +96,14 @@ before_script: after_script: - killall -w ssdb-server - rm -rf ./res/var/* +after_success: + - bash <(curl -s https://codecov.io/bash) script: - - go test ./... + - go test -coverprofile=coverage.txt -covermode=atomic ./... - staticcheck -show-ignored -checks "-ST1017,-U1000,-ST1005,-S1034,-S1012,-SA4006,-SA6005,-SA1019,-SA1024" ./ - unconvert $(go list ./... | grep -v /vendor/) - ineffassign . - find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s - golint ./... addons: - postgresql: "9.6" \ No newline at end of file + postgresql: "9.6" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..1a259efc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,6 @@ +# developing +- Fix 4396: Add context.param module into adapter. [4398](https://github.com/beego/beego/pull/4398) +- Remove `duration` from prometheus labels. [4391](https://github.com/beego/beego/pull/4391) +- Fix `unknown escape sequence` in generated code. [4385](https://github.com/beego/beego/pull/4385) +- Using fixed name `commentRouter.go` as generated file name. [4385](https://github.com/beego/beego/pull/4385) +- Fix 4383: ORM Adapter produces panic when using orm.RegisterModelWithPrefix. [4386](https://github.com/beego/beego/pull/4386) \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cb279cbb..2f9189e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,8 +4,8 @@ beego is an open source project. It is the work of hundreds of contributors. We appreciate your help! -Here are instructions to get you started. They are probably not perfect, -please let us know if anything feels wrong or incomplete. +Here are instructions to get you started. They are probably not perfect, please let us know if anything feels wrong or +incomplete. ## Prepare environment @@ -18,6 +18,7 @@ go get -u github.com/gordonklaus/ineffassign ``` Put those lines into your pre-commit githook script: + ```shell script goimports -w -format-only ./ @@ -33,10 +34,13 @@ Beego uses many middlewares, including MySQL, Redis, SSDB and so on. We provide docker compose file to start all middlewares. You can run: + ```shell script docker-compose -f scripts/test_docker_compose.yml up -d ``` + Unit tests read addresses from environment, here is an example: + ```shell script export ORM_DRIVER=mysql export ORM_SOURCE="beego:test@tcp(192.168.0.105:13306)/orm_test?charset=utf8" @@ -45,34 +49,28 @@ export REDIS_ADDR="192.168.0.105:6379" export SSDB_ADDR="192.168.0.105:8888" ``` - ## Contribution guidelines ### Pull requests -First of all. beego follow the gitflow. So please send you pull request -to **develop-2** branch. We will close the pull request to master branch. +First of all. beego follow the gitflow. So please send you pull request to **develop-2** branch. We will close the pull +request to master branch. -We are always happy to receive pull requests, and do our best to -review them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. +We are always happy to receive pull requests, and do our best to review them as fast as possible. Not sure if that typo +is worth a pull request? Do it! We will appreciate it. Don't forget to rebase your commits! -If your pull request is not accepted on the first try, don't be -discouraged! Sometimes we can make a mistake, please do more explaining -for us. We will appreciate it. +If your pull request is not accepted on the first try, don't be discouraged! Sometimes we can make a mistake, please do +more explaining for us. We will appreciate it. -We're trying very hard to keep beego simple and fast. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. But we will give you some advice on how to -do it in other way. +We're trying very hard to keep beego simple and fast. We don't want it to do everything for everybody. This means that +we might decide against incorporating a new feature. But we will give you some advice on how to do it in other way. ### Create issues -Any significant improvement should be documented as [a GitHub -issue](https://github.com/astaxie/beego/issues) before anybody -starts working on it. +Any significant improvement should be documented as [a GitHub issue](https://github.com/beego/beego/v2/issues) before +anybody starts working on it. Also when filing an issue, make sure to answer these five questions: @@ -84,10 +82,8 @@ Also when filing an issue, make sure to answer these five questions: ### but check existing issues and docs first! -Please take a moment to check that an issue doesn't already exist -documenting your bug report or improvement proposal. If it does, it -never hurts to add a quick "+1" or "I have this problem too". This will -help prioritize the most common problems and requests. +Please take a moment to check that an issue doesn't already exist documenting your bug report or improvement proposal. +If it does, it never hurts to add a quick "+1" or "I have this problem too". This will help prioritize the most common +problems and requests. -Also, if you don't know how to use it. please make sure you have read through -the docs in http://beego.me/docs \ No newline at end of file +Also, if you don't know how to use it. please make sure you have read through the docs in http://beego.me/docs diff --git a/LICENSE b/LICENSE index 5dbd4243..26050108 100644 --- a/LICENSE +++ b/LICENSE @@ -10,4 +10,4 @@ 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. \ No newline at end of file +limitations under the License. diff --git a/README.md b/README.md index 934fc429..6450e183 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,57 @@ -# Beego [![Build Status](https://travis-ci.org/astaxie/beego.svg?branch=master)](https://travis-ci.org/astaxie/beego) [![GoDoc](http://godoc.org/github.com/astaxie/beego?status.svg)](http://godoc.org/github.com/astaxie/beego) [![Foundation](https://img.shields.io/badge/Golang-Foundation-green.svg)](http://golangfoundation.org) [![Go Report Card](https://goreportcard.com/badge/github.com/astaxie/beego)](https://goreportcard.com/report/github.com/astaxie/beego) +# Beego [![Build Status](https://travis-ci.org/astaxie/beego.svg?branch=master)](https://travis-ci.org/astaxie/beego) [![GoDoc](http://godoc.org/github.com/beego/beego/v2?status.svg)](http://godoc.org/github.com/beego/beego/v2) [![Foundation](https://img.shields.io/badge/Golang-Foundation-green.svg)](http://golangfoundation.org) [![Go Report Card](https://goreportcard.com/badge/github.com/beego/beego/v2)](https://goreportcard.com/report/github.com/beego/beego/v2) +Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend +services. -beego is used for rapid development of RESTful APIs, web apps and backend services in Go. -It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct embedding. +It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct +embedding. -###### More info at [beego.me](http://beego.me). +![architecture](https://cdn.nlark.com/yuque/0/2020/png/755700/1607857489109-1e267fce-d65f-4c5e-b915-5c475df33c58.png) + +Beego is compos of four parts: + +1. Base modules: including log module, config module, governor module; +2. Task: is used for running timed tasks or periodic tasks; +3. Client: including ORM module, httplib module, cache module; +4. Server: including web module. We will support gRPC in the future; ## Quick Start -###### Please see [Documentation](http://beego.me/docs) for more. +[Officail website](http://beego.me) -###### [beego-example](https://github.com/beego-dev/beego-example) +[Example](https://github.com/beego/beego-example) + +> If you could not open official website, go to [beedoc](https://github.com/beego/beedoc) ### Web Application +![Http Request](https://cdn.nlark.com/yuque/0/2020/png/755700/1607857462507-855ec543-7ce3-402d-a0cb-b2524d5a4b60.png) + #### Create `hello` directory, cd `hello` directory mkdir hello cd hello - + #### Init module go mod init #### Download and install - go get github.com/astaxie/beego + go get github.com/beego/beego/v2@v2.0.0 #### Create file `hello.go` + ```go package main -import "github.com/astaxie/beego/server/web" +import "github.com/beego/beego/v2/server/web" -func main(){ - web.Run() +func main() { + web.Run() } ``` + #### Build and run go build hello.go @@ -46,227 +61,36 @@ func main(){ Congratulations! You've just built your first **beego** app. -### Using ORM module - -```go - -package main - -import ( - "github.com/astaxie/beego/client/orm" - "github.com/astaxie/beego/core/logs" - _ "github.com/go-sql-driver/mysql" -) - -// User - -type User struct { - ID int `orm:"column(id)"` - Name string `orm:"column(name)"` -} - -func init() { - // need to register models in init - orm.RegisterModel(new(User)) - - // need to register db driver - orm.RegisterDriver("mysql", orm.DRMySQL) - - // need to register default database - orm.RegisterDataBase("default", "mysql", "beego:test@tcp(192.168.0.105:13306)/orm_test?charset=utf8") -} - -func main() { - // automatically build table - orm.RunSyncdb("default", false, true) - - // create orm object, and it will use `default` database - o := orm.NewOrm() - - // data - user := new(User) - user.Name = "mike" - - // insert data - id, err := o.Insert(user) - if err != nil { - logs.Info(err) - } - - // ... -} -``` - -### Using httplib as http client -```go -package main - -import ( - "github.com/astaxie/beego/client/httplib" - "github.com/astaxie/beego/core/logs" -) - -func main() { - // Get, more methods please read docs - req := httplib.Get("http://beego.me/") - str, err := req.String() - if err != nil { - logs.Error(err) - } - logs.Info(str) -} - -``` - -### Using config module - -```go -package main - -import ( - "context" - - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" -) - -var ( - ConfigFile = "./app.conf" -) - -func main() { - cfg, err := config.NewConfig("ini", ConfigFile) - if err != nil { - logs.Critical("An error occurred:", err) - panic(err) - } - res, _ := cfg.String(context.Background(), "name") - logs.Info("load config name is", res) -} -``` -### Using logs module -```go -package main - -import ( - "github.com/astaxie/beego/core/logs" -) - -func main() { - err := logs.SetLogger(logs.AdapterFile, `{"filename":"project.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`) - if err != nil { - panic(err) - } - logs.Info("hello beego") -} -``` -### Using timed task - -```go -package main - -import ( - "context" - "time" - - "github.com/astaxie/beego/core/logs" - "github.com/astaxie/beego/task" -) - -func main() { - // create a task - tk1 := task.NewTask("tk1", "0/3 * * * * *", func(ctx context.Context) error { logs.Info("tk1"); return nil }) - - // check task - err := tk1.Run(context.Background()) - if err != nil { - logs.Error(err) - } - - // add task to global todolist - task.AddTask("tk1", tk1) - - // start tasks - task.StartTask() - - // wait 12 second - time.Sleep(12 * time.Second) - defer task.StopTask() -} -``` - -### Using cache module - -```go -package main - -import ( - "context" - "time" - - "github.com/astaxie/beego/client/cache" - - // don't forget this - _ "github.com/astaxie/beego/client/cache/redis" - - "github.com/astaxie/beego/core/logs" -) - -func main() { - // create cache - bm, err := cache.NewCache("redis", `{"key":"default", "conn":":6379", "password":"123456", "dbNum":"0"}`) - if err != nil { - logs.Error(err) - } - - // put - isPut := bm.Put(context.Background(), "astaxie", 1, time.Second*10) - logs.Info(isPut) - - isPut = bm.Put(context.Background(), "hello", "world", time.Second*10) - logs.Info(isPut) - - // get - result, _ := bm.Get(context.Background(),"astaxie") - logs.Info(string(result.([]byte))) - - multiResult, _ := bm.GetMulti(context.Background(), []string{"astaxie", "hello"}) - for i := range multiResult { - logs.Info(string(multiResult[i].([]byte))) - } - - // isExist - isExist, _ := bm.IsExist(context.Background(), "astaxie") - logs.Info(isExist) - - // delete - isDelete := bm.Delete(context.Background(), "astaxie") - logs.Info(isDelete) -} -``` - - ## Features * RESTful support -* MVC architecture +* [MVC architecture](https://github.com/beego/beedoc/tree/master/en-US/mvc) * Modularity -* Auto API documents -* Annotation router -* Namespace -* Powerful development tools +* [Auto API documents](https://github.com/beego/beedoc/blob/master/en-US/advantage/docs.md) +* [Annotation router](https://github.com/beego/beedoc/blob/master/en-US/mvc/controller/router.md) +* [Namespace](https://github.com/beego/beedoc/blob/master/en-US/mvc/controller/router.md#namespace) +* [Powerful development tools](https://github.com/beego/bee) * Full stack for Web & API -## Documentation +## Modules -* [English](http://beego.me/docs/intro/) -* [中文文档](http://beego.me/docs/intro/) -* [Русский](http://beego.me/docs/intro/) +* [orm](https://github.com/beego/beedoc/tree/master/en-US/mvc/model) +* [session](https://github.com/beego/beedoc/blob/master/en-US/module/session.md) +* [logs](https://github.com/beego/beedoc/blob/master/en-US/module/logs.md) +* [config](https://github.com/beego/beedoc/blob/master/en-US/module/config.md) +* [cache](https://github.com/beego/beedoc/blob/master/en-US/module/cache.md) +* [context](https://github.com/beego/beedoc/blob/master/en-US/module/context.md) +* [admin](https://github.com/beego/beedoc/blob/master/en-US/module/admin.md) +* [httplib](https://github.com/beego/beedoc/blob/master/en-US/module/httplib.md) +* [task](https://github.com/beego/beedoc/blob/master/en-US/module/task.md) +* [i18n](https://github.com/beego/beedoc/blob/master/en-US/module/i18n.md) ## Community * [http://beego.me/community](http://beego.me/community) -* Welcome to join us in Slack: [https://beego.slack.com](https://beego.slack.com), you can get invited from [here](https://github.com/beego/beedoc/issues/232) +* 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 +* [Contribution Guide](https://github.com/beego/beedoc/blob/master/en-US/intro/contributing.md). ## License diff --git a/adapter/admin.go b/adapter/admin.go index e555f59e..527cb201 100644 --- a/adapter/admin.go +++ b/adapter/admin.go @@ -17,8 +17,8 @@ package adapter import ( "time" - _ "github.com/astaxie/beego/core/governor" - "github.com/astaxie/beego/server/web" + _ "github.com/beego/beego/v2/core/admin" + "github.com/beego/beego/v2/server/web" ) // FilterMonitorFunc is default monitor filter when admin module is enable. diff --git a/adapter/app.go b/adapter/app.go index e20cd9d2..565a9795 100644 --- a/adapter/app.go +++ b/adapter/app.go @@ -17,9 +17,9 @@ package adapter import ( "net/http" - context2 "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + context2 "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) var ( @@ -74,7 +74,7 @@ func oldMiddlewareToNew(mws []MiddleWare) []web.MiddleWare { // beego.Router("/api/update",&RestController{},"put:UpdateFood") // beego.Router("/api/delete",&RestController{},"delete:DeleteFood") func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App { - return (*App)(web.Router(rootpath, c, mappingMethods...)) + return (*App)(web.Router(rootpath, c, web.SetRouterMethods(c, mappingMethods...))) } // UnregisterFixedRoute unregisters the route with the specified fixedRoute. It is particularly useful diff --git a/adapter/beego.go b/adapter/beego.go index bbe37db8..331aa786 100644 --- a/adapter/beego.go +++ b/adapter/beego.go @@ -15,8 +15,8 @@ package adapter import ( - "github.com/astaxie/beego" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/server/web" ) const ( diff --git a/adapter/cache/cache.go b/adapter/cache/cache.go index 82585c4e..f615b26f 100644 --- a/adapter/cache/cache.go +++ b/adapter/cache/cache.go @@ -16,7 +16,7 @@ // Usage: // // import( -// "github.com/astaxie/beego/cache" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("memory", `{"interval":60}`) diff --git a/adapter/cache/cache_adapter.go b/adapter/cache/cache_adapter.go index 3bfd0bf8..cc46cad7 100644 --- a/adapter/cache/cache_adapter.go +++ b/adapter/cache/cache_adapter.go @@ -18,7 +18,7 @@ import ( "context" "time" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) type newToOldCacheAdapter struct { diff --git a/adapter/cache/cache_test.go b/adapter/cache/cache_test.go index 470c0a43..f6217e1a 100644 --- a/adapter/cache/cache_test.go +++ b/adapter/cache/cache_test.go @@ -26,7 +26,7 @@ func TestCacheIncr(t *testing.T) { if err != nil { t.Error("init err") } - //timeoutDuration := 10 * time.Second + // timeoutDuration := 10 * time.Second bm.Put("edwardhey", 0, time.Second*20) wg := sync.WaitGroup{} @@ -90,7 +90,7 @@ func TestCache(t *testing.T) { t.Error("delete err") } - //test GetMulti + // test GetMulti if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -157,7 +157,7 @@ func TestFileCache(t *testing.T) { t.Error("delete err") } - //test string + // test string if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -168,7 +168,7 @@ func TestFileCache(t *testing.T) { t.Error("get err") } - //test GetMulti + // test GetMulti if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } diff --git a/adapter/cache/conv.go b/adapter/cache/conv.go index 18b8a255..052c4f3b 100644 --- a/adapter/cache/conv.go +++ b/adapter/cache/conv.go @@ -15,7 +15,7 @@ package cache import ( - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) // GetString convert interface to string. diff --git a/adapter/cache/file.go b/adapter/cache/file.go index 74eb980a..b010a031 100644 --- a/adapter/cache/file.go +++ b/adapter/cache/file.go @@ -15,7 +15,7 @@ package cache import ( - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) // NewFileCache Create new file cache with no config. diff --git a/adapter/cache/memcache/memcache.go b/adapter/cache/memcache/memcache.go index b4da1bfe..16948f65 100644 --- a/adapter/cache/memcache/memcache.go +++ b/adapter/cache/memcache/memcache.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/cache/memcache" -// "github.com/astaxie/beego/cache" +// _ "github.com/beego/beego/v2/cache/memcache" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`) @@ -30,8 +30,8 @@ package memcache import ( - "github.com/astaxie/beego/adapter/cache" - "github.com/astaxie/beego/client/cache/memcache" + "github.com/beego/beego/v2/adapter/cache" + "github.com/beego/beego/v2/client/cache/memcache" ) // NewMemCache create new memcache adapter. diff --git a/adapter/cache/memcache/memcache_test.go b/adapter/cache/memcache/memcache_test.go index b9b6dc6b..6382543e 100644 --- a/adapter/cache/memcache/memcache_test.go +++ b/adapter/cache/memcache/memcache_test.go @@ -21,7 +21,7 @@ import ( "testing" "time" - "github.com/astaxie/beego/adapter/cache" + "github.com/beego/beego/v2/adapter/cache" ) func TestMemcacheCache(t *testing.T) { diff --git a/adapter/cache/memory.go b/adapter/cache/memory.go index cf6e3992..dfb80aa4 100644 --- a/adapter/cache/memory.go +++ b/adapter/cache/memory.go @@ -15,7 +15,7 @@ package cache import ( - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) // NewMemoryCache returns a new MemoryCache. diff --git a/adapter/cache/redis/redis.go b/adapter/cache/redis/redis.go index 3562057d..bfbeeb9c 100644 --- a/adapter/cache/redis/redis.go +++ b/adapter/cache/redis/redis.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/cache/redis" -// "github.com/astaxie/beego/cache" +// _ "github.com/beego/beego/v2/cache/redis" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) @@ -30,8 +30,8 @@ package redis import ( - "github.com/astaxie/beego/adapter/cache" - redis2 "github.com/astaxie/beego/client/cache/redis" + "github.com/beego/beego/v2/adapter/cache" + redis2 "github.com/beego/beego/v2/client/cache/redis" ) var ( diff --git a/adapter/cache/redis/redis_test.go b/adapter/cache/redis/redis_test.go index 7ae12197..39a30e8e 100644 --- a/adapter/cache/redis/redis_test.go +++ b/adapter/cache/redis/redis_test.go @@ -22,7 +22,7 @@ import ( "github.com/gomodule/redigo/redis" - "github.com/astaxie/beego/adapter/cache" + "github.com/beego/beego/v2/adapter/cache" ) func TestRedisCache(t *testing.T) { @@ -76,7 +76,7 @@ func TestRedisCache(t *testing.T) { t.Error("delete err") } - //test string + // test string if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -88,7 +88,7 @@ func TestRedisCache(t *testing.T) { t.Error("get err") } - //test GetMulti + // test GetMulti if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } diff --git a/adapter/cache/ssdb/ssdb.go b/adapter/cache/ssdb/ssdb.go index df552043..8f6e50d3 100644 --- a/adapter/cache/ssdb/ssdb.go +++ b/adapter/cache/ssdb/ssdb.go @@ -1,8 +1,8 @@ package ssdb import ( - "github.com/astaxie/beego/adapter/cache" - ssdb2 "github.com/astaxie/beego/client/cache/ssdb" + "github.com/beego/beego/v2/adapter/cache" + ssdb2 "github.com/beego/beego/v2/client/cache/ssdb" ) // NewSsdbCache create new ssdb adapter. diff --git a/adapter/cache/ssdb/ssdb_test.go b/adapter/cache/ssdb/ssdb_test.go index 080167cd..98e805d1 100644 --- a/adapter/cache/ssdb/ssdb_test.go +++ b/adapter/cache/ssdb/ssdb_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/astaxie/beego/adapter/cache" + "github.com/beego/beego/v2/adapter/cache" ) func TestSsdbcacheCache(t *testing.T) { @@ -26,7 +26,7 @@ func TestSsdbcacheCache(t *testing.T) { t.Error("check err") } timeoutDuration := 10 * time.Second - //timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent + // timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -43,7 +43,7 @@ func TestSsdbcacheCache(t *testing.T) { t.Error("get Error") } - //inc/dec test done + // inc/dec test done if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -72,7 +72,7 @@ func TestSsdbcacheCache(t *testing.T) { } } - //test string + // test string if err = ssdb.Put("ssdb", "ssdb", -10*time.Second); err != nil { t.Error("set Error", err) } @@ -83,7 +83,7 @@ func TestSsdbcacheCache(t *testing.T) { t.Error("get err") } - //test GetMulti done + // test GetMulti done if err = ssdb.Put("ssdb1", "ssdb1", -10*time.Second); err != nil { t.Error("set Error", err) } diff --git a/adapter/config.go b/adapter/config.go index 6280b8f8..36e0a9c4 100644 --- a/adapter/config.go +++ b/adapter/config.go @@ -15,9 +15,9 @@ package adapter import ( - "github.com/astaxie/beego/adapter/session" - newCfg "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/adapter/session" + newCfg "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/server/web" ) // Config is the main struct for BConfig diff --git a/adapter/config/adapter.go b/adapter/config/adapter.go index 0a9e1d0c..f7cfcb19 100644 --- a/adapter/config/adapter.go +++ b/adapter/config/adapter.go @@ -17,7 +17,7 @@ package config import ( "github.com/pkg/errors" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) type newToOldConfigerAdapter struct { diff --git a/adapter/config/config.go b/adapter/config/config.go index 703555cd..a935e281 100644 --- a/adapter/config/config.go +++ b/adapter/config/config.go @@ -14,7 +14,7 @@ // Package config is used to parse config. // Usage: -// import "github.com/astaxie/beego/config" +// import "github.com/beego/beego/v2/config" // Examples. // // cnf, err := config.NewConfig("ini", "config.conf") @@ -41,7 +41,7 @@ package config import ( - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) // Configer defines how to get and set value from configuration raw data. diff --git a/adapter/config/env/env.go b/adapter/config/env/env.go index 839c60c1..0be4fe6b 100644 --- a/adapter/config/env/env.go +++ b/adapter/config/env/env.go @@ -17,7 +17,7 @@ package env import ( - "github.com/astaxie/beego/core/config/env" + "github.com/beego/beego/v2/core/config/env" ) // Get returns a value by key. diff --git a/adapter/config/fake.go b/adapter/config/fake.go index 050f0252..a2b53167 100644 --- a/adapter/config/fake.go +++ b/adapter/config/fake.go @@ -15,7 +15,7 @@ package config import ( - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) // NewFakeConfig return a fake Configer diff --git a/adapter/config/ini_test.go b/adapter/config/ini_test.go index ffcdb294..60f1febd 100644 --- a/adapter/config/ini_test.go +++ b/adapter/config/ini_test.go @@ -145,7 +145,7 @@ httpport = 8080 # enable db [dbinfo] # db type name -# suport mysql,sqlserver +# support mysql,sqlserver name = mysql ` @@ -161,7 +161,7 @@ httpport=8080 # enable db [dbinfo] # db type name -# suport mysql,sqlserver +# support mysql,sqlserver name=mysql ` ) diff --git a/adapter/config/json.go b/adapter/config/json.go index d77e6146..b5a481cd 100644 --- a/adapter/config/json.go +++ b/adapter/config/json.go @@ -15,5 +15,5 @@ package config import ( - _ "github.com/astaxie/beego/core/config/json" + _ "github.com/beego/beego/v2/core/config/json" ) diff --git a/adapter/config/xml/xml.go b/adapter/config/xml/xml.go index 28d5f44e..190cee97 100644 --- a/adapter/config/xml/xml.go +++ b/adapter/config/xml/xml.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/config/xml" -// "github.com/astaxie/beego/config" +// _ "github.com/beego/beego/v2/config/xml" +// "github.com/beego/beego/v2/config" // ) // // cnf, err := config.NewConfig("xml", "config.xml") @@ -30,5 +30,5 @@ package xml import ( - _ "github.com/astaxie/beego/core/config/xml" + _ "github.com/beego/beego/v2/core/config/xml" ) diff --git a/adapter/config/xml/xml_test.go b/adapter/config/xml/xml_test.go index ae9b209e..5e43ca0f 100644 --- a/adapter/config/xml/xml_test.go +++ b/adapter/config/xml/xml_test.go @@ -19,13 +19,13 @@ import ( "os" "testing" - "github.com/astaxie/beego/adapter/config" + "github.com/beego/beego/v2/adapter/config" ) func TestXML(t *testing.T) { var ( - //xml parse should incluce in tags + // xml parse should incluce in tags xmlcontext = ` beeapi diff --git a/adapter/config/yaml/yaml.go b/adapter/config/yaml/yaml.go index 196c9725..8d0bb697 100644 --- a/adapter/config/yaml/yaml.go +++ b/adapter/config/yaml/yaml.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/config/yaml" -// "github.com/astaxie/beego/config" +// _ "github.com/beego/beego/v2/config/yaml" +// "github.com/beego/beego/v2/config" // ) // // cnf, err := config.NewConfig("yaml", "config.yaml") @@ -30,5 +30,5 @@ package yaml import ( - _ "github.com/astaxie/beego/core/config/yaml" + _ "github.com/beego/beego/v2/core/config/yaml" ) diff --git a/adapter/config/yaml/yaml_test.go b/adapter/config/yaml/yaml_test.go index a72e435e..d567b554 100644 --- a/adapter/config/yaml/yaml_test.go +++ b/adapter/config/yaml/yaml_test.go @@ -19,7 +19,7 @@ import ( "os" "testing" - "github.com/astaxie/beego/adapter/config" + "github.com/beego/beego/v2/adapter/config" ) func TestYaml(t *testing.T) { diff --git a/adapter/context/acceptencoder.go b/adapter/context/acceptencoder.go index 4bfef95e..69a3acbc 100644 --- a/adapter/context/acceptencoder.go +++ b/adapter/context/acceptencoder.go @@ -19,7 +19,7 @@ import ( "net/http" "os" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // InitGzip init the gzipcompress diff --git a/adapter/context/context.go b/adapter/context/context.go index 123fdb2c..16e631fc 100644 --- a/adapter/context/context.go +++ b/adapter/context/context.go @@ -15,7 +15,7 @@ // Package context provide the context utils // Usage: // -// import "github.com/astaxie/beego/context" +// import "github.com/beego/beego/v2/context" // // ctx := context.Context{Request:req,ResponseWriter:rw} // @@ -27,7 +27,7 @@ import ( "net" "net/http" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // commonly used mime-types diff --git a/adapter/context/input.go b/adapter/context/input.go index 51bb9ea5..ac3e0c72 100644 --- a/adapter/context/input.go +++ b/adapter/context/input.go @@ -15,7 +15,7 @@ package context import ( - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // BeegoInput operates the http request header, data, cookie and body. diff --git a/adapter/context/output.go b/adapter/context/output.go index 0223679b..5152ccf5 100644 --- a/adapter/context/output.go +++ b/adapter/context/output.go @@ -15,7 +15,7 @@ package context import ( - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // BeegoOutput does work for sending response header. diff --git a/adapter/context/param/conv.go b/adapter/context/param/conv.go new file mode 100644 index 00000000..ec4c6b7e --- /dev/null +++ b/adapter/context/param/conv.go @@ -0,0 +1,18 @@ +package param + +import ( + "reflect" + + beecontext "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/context/param" +) + +// ConvertParams converts http method params to values that will be passed to the method controller as arguments +func ConvertParams(methodParams []*MethodParam, methodType reflect.Type, ctx *beecontext.Context) (result []reflect.Value) { + nps := make([]*param.MethodParam, 0, len(methodParams)) + for _, mp := range methodParams { + nps = append(nps, (*param.MethodParam)(mp)) + } + return param.ConvertParams(nps, methodType, (*context.Context)(ctx)) +} diff --git a/adapter/context/param/conv_test.go b/adapter/context/param/conv_test.go new file mode 100644 index 00000000..c27d385a --- /dev/null +++ b/adapter/context/param/conv_test.go @@ -0,0 +1,40 @@ +// Copyright 2020 beego +// +// 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 param + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/beego/beego/v2/adapter/context" +) + +func Demo(i int) { + +} + +func TestConvertParams(t *testing.T) { + res := ConvertParams(nil, reflect.TypeOf(Demo), context.NewContext()) + assert.Equal(t, 0, len(res)) + ctx := context.NewContext() + ctx.Input.RequestBody = []byte("11") + res = ConvertParams([]*MethodParam{ + New("A", InBody), + }, reflect.TypeOf(Demo), ctx) + assert.Equal(t, int64(11), res[0].Int()) +} + diff --git a/adapter/context/param/methodparams.go b/adapter/context/param/methodparams.go new file mode 100644 index 00000000..000539db --- /dev/null +++ b/adapter/context/param/methodparams.go @@ -0,0 +1,29 @@ +package param + +import ( + "github.com/beego/beego/v2/server/web/context/param" +) + +// MethodParam keeps param information to be auto passed to controller methods +type MethodParam param.MethodParam + +// New creates a new MethodParam with name and specific options +func New(name string, opts ...MethodParamOption) *MethodParam { + newOps := make([]param.MethodParamOption, 0, len(opts)) + for _, o := range opts { + newOps = append(newOps, oldMpoToNew(o)) + } + return (*MethodParam)(param.New(name, newOps...)) +} + +// Make creates an array of MethodParmas or an empty array +func Make(list ...*MethodParam) []*MethodParam { + if len(list) > 0 { + return list + } + return nil +} + +func (mp *MethodParam) String() string { + return (*param.MethodParam)(mp).String() +} diff --git a/adapter/context/param/methodparams_test.go b/adapter/context/param/methodparams_test.go new file mode 100644 index 00000000..b240d087 --- /dev/null +++ b/adapter/context/param/methodparams_test.go @@ -0,0 +1,34 @@ +// Copyright 2020 beego +// +// 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 param + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMethodParam_String(t *testing.T) { + method := New("myName", IsRequired, InHeader, Default("abc")) + s := method.String() + assert.Equal(t, `param.New("myName", param.IsRequired, param.InHeader, param.Default("abc"))`, s) +} + +func TestMake(t *testing.T) { + res := Make() + assert.Equal(t, 0, len(res)) + res = Make(New("myName", InBody)) + assert.Equal(t, 1, len(res)) +} diff --git a/adapter/context/param/options.go b/adapter/context/param/options.go new file mode 100644 index 00000000..1d9364c2 --- /dev/null +++ b/adapter/context/param/options.go @@ -0,0 +1,45 @@ +package param + +import ( + "github.com/beego/beego/v2/server/web/context/param" +) + +// MethodParamOption defines a func which apply options on a MethodParam +type MethodParamOption func(*MethodParam) + +// IsRequired indicates that this param is required and can not be omitted from the http request +var IsRequired MethodParamOption = func(p *MethodParam) { + param.IsRequired((*param.MethodParam)(p)) +} + +// InHeader indicates that this param is passed via an http header +var InHeader MethodParamOption = func(p *MethodParam) { + param.InHeader((*param.MethodParam)(p)) +} + +// InPath indicates that this param is part of the URL path +var InPath MethodParamOption = func(p *MethodParam) { + param.InPath((*param.MethodParam)(p)) +} + +// InBody indicates that this param is passed as an http request body +var InBody MethodParamOption = func(p *MethodParam) { + param.InBody((*param.MethodParam)(p)) +} + +// Default provides a default value for the http param +func Default(defaultValue interface{}) MethodParamOption { + return newMpoToOld(param.Default(defaultValue)) +} + +func newMpoToOld(n param.MethodParamOption) MethodParamOption { + return func(methodParam *MethodParam) { + n((*param.MethodParam)(methodParam)) + } +} + +func oldMpoToNew(old MethodParamOption) param.MethodParamOption { + return func(methodParam *param.MethodParam) { + old((*MethodParam)(methodParam)) + } +} diff --git a/adapter/context/renderer.go b/adapter/context/renderer.go index 1309365a..2c5a53c1 100644 --- a/adapter/context/renderer.go +++ b/adapter/context/renderer.go @@ -1,7 +1,7 @@ package context import ( - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // Renderer defines an http response renderer diff --git a/adapter/controller.go b/adapter/controller.go index 14dc9b97..15d813ab 100644 --- a/adapter/controller.go +++ b/adapter/controller.go @@ -18,10 +18,10 @@ import ( "mime/multipart" "net/url" - "github.com/astaxie/beego/adapter/session" - webContext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/adapter/session" + webContext "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) var ( @@ -212,7 +212,8 @@ func (c *Controller) ServeFormatted(encoding ...bool) { // Input returns the input data map from POST or PUT request body and query string. func (c *Controller) Input() url.Values { - return (*web.Controller)(c).Input() + val, _ := (*web.Controller)(c).Input() + return val } // ParseForm maps input data map to obj struct. diff --git a/adapter/error.go b/adapter/error.go index 35ff7f35..a4d0bc00 100644 --- a/adapter/error.go +++ b/adapter/error.go @@ -17,10 +17,10 @@ package adapter import ( "net/http" - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) const ( diff --git a/adapter/filter.go b/adapter/filter.go index 283d8879..660193b9 100644 --- a/adapter/filter.go +++ b/adapter/filter.go @@ -15,9 +15,9 @@ package adapter import ( - "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/server/web" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web" + beecontext "github.com/beego/beego/v2/server/web/context" ) // FilterFunc defines a filter function which is invoked before the controller handler is executed. diff --git a/adapter/flash.go b/adapter/flash.go index 2b47ee62..aab9b3ce 100644 --- a/adapter/flash.go +++ b/adapter/flash.go @@ -15,7 +15,7 @@ package adapter import ( - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) // FlashData is a tools to maintain data when using across request. diff --git a/adapter/fs.go b/adapter/fs.go index e48e75b5..168e312a 100644 --- a/adapter/fs.go +++ b/adapter/fs.go @@ -18,7 +18,7 @@ import ( "net/http" "path/filepath" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) type FileSystem web.FileSystem diff --git a/adapter/grace/grace.go b/adapter/grace/grace.go index 75ceef21..6e582bac 100644 --- a/adapter/grace/grace.go +++ b/adapter/grace/grace.go @@ -22,7 +22,7 @@ // "net/http" // "os" // -// "github.com/astaxie/beego/grace" +// "github.com/beego/beego/v2/grace" // ) // // func handler(w http.ResponseWriter, r *http.Request) { @@ -46,7 +46,7 @@ import ( "net/http" "time" - "github.com/astaxie/beego/server/web/grace" + "github.com/beego/beego/v2/server/web/grace" ) const ( diff --git a/adapter/grace/server.go b/adapter/grace/server.go index 0dfb2fd6..95ca05b4 100644 --- a/adapter/grace/server.go +++ b/adapter/grace/server.go @@ -3,7 +3,7 @@ package grace import ( "os" - "github.com/astaxie/beego/server/web/grace" + "github.com/beego/beego/v2/server/web/grace" ) // Server embedded http.Server diff --git a/adapter/httplib/httplib.go b/adapter/httplib/httplib.go index d9ff1ea5..0a182cae 100644 --- a/adapter/httplib/httplib.go +++ b/adapter/httplib/httplib.go @@ -15,7 +15,7 @@ // Package httplib is used as http.Client // Usage: // -// import "github.com/astaxie/beego/httplib" +// import "github.com/beego/beego/v2/httplib" // // b := httplib.Post("http://beego.me/") // b.Param("username","astaxie") @@ -38,7 +38,7 @@ import ( "net/url" "time" - "github.com/astaxie/beego/client/httplib" + "github.com/beego/beego/v2/client/httplib" ) // SetDefaultSetting Overwrite default settings diff --git a/adapter/log.go b/adapter/log.go index 9d07ec1a..25e82d26 100644 --- a/adapter/log.go +++ b/adapter/log.go @@ -17,13 +17,13 @@ package adapter import ( "strings" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - webLog "github.com/astaxie/beego/core/logs" + webLog "github.com/beego/beego/v2/core/logs" ) // Log levels to control the logging output. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. const ( LevelEmergency = webLog.LevelEmergency LevelAlert = webLog.LevelAlert @@ -36,90 +36,90 @@ const ( ) // BeeLogger references the used application logger. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. var BeeLogger = logs.GetBeeLogger() // SetLevel sets the global log level used by the simple logger. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func SetLevel(l int) { logs.SetLevel(l) } // SetLogFuncCall set the CallDepth, default is 3 -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func SetLogFuncCall(b bool) { logs.SetLogFuncCall(b) } // SetLogger sets a new logger. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func SetLogger(adaptername string, config string) error { return logs.SetLogger(adaptername, config) } // Emergency logs a message at emergency level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Emergency(v ...interface{}) { logs.Emergency(generateFmtStr(len(v)), v...) } // Alert logs a message at alert level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Alert(v ...interface{}) { logs.Alert(generateFmtStr(len(v)), v...) } // Critical logs a message at critical level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Critical(v ...interface{}) { logs.Critical(generateFmtStr(len(v)), v...) } // Error logs a message at error level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Error(v ...interface{}) { logs.Error(generateFmtStr(len(v)), v...) } // Warning logs a message at warning level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Warning(v ...interface{}) { logs.Warning(generateFmtStr(len(v)), v...) } // Warn compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Warn(v ...interface{}) { logs.Warn(generateFmtStr(len(v)), v...) } // Notice logs a message at notice level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Notice(v ...interface{}) { logs.Notice(generateFmtStr(len(v)), v...) } // Informational logs a message at info level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Informational(v ...interface{}) { logs.Informational(generateFmtStr(len(v)), v...) } // Info compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Info(v ...interface{}) { logs.Info(generateFmtStr(len(v)), v...) } // Debug logs a message at debug level. -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Debug(v ...interface{}) { logs.Debug(generateFmtStr(len(v)), v...) } // Trace logs a message at trace level. // compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. +// Deprecated: use github.com/beego/beego/v2/logs instead. func Trace(v ...interface{}) { logs.Trace(generateFmtStr(len(v)), v...) } diff --git a/adapter/logs/accesslog.go b/adapter/logs/accesslog.go index a2150884..f4370a5d 100644 --- a/adapter/logs/accesslog.go +++ b/adapter/logs/accesslog.go @@ -15,7 +15,7 @@ package logs import ( - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // AccessLogRecord struct for holding access log data. diff --git a/adapter/logs/alils/alils.go b/adapter/logs/alils/alils.go index 941cba4c..2f700457 100644 --- a/adapter/logs/alils/alils.go +++ b/adapter/logs/alils/alils.go @@ -1,5 +1,5 @@ package alils import ( - _ "github.com/astaxie/beego/core/logs/alils" + _ "github.com/beego/beego/v2/core/logs/alils" ) diff --git a/adapter/logs/es/es.go b/adapter/logs/es/es.go index 0f0fd607..124e3fdd 100644 --- a/adapter/logs/es/es.go +++ b/adapter/logs/es/es.go @@ -1,5 +1,5 @@ package es import ( - _ "github.com/astaxie/beego/core/logs/es" + _ "github.com/beego/beego/v2/core/logs/es" ) diff --git a/adapter/logs/log.go b/adapter/logs/log.go index 54eb24d5..9d098d8f 100644 --- a/adapter/logs/log.go +++ b/adapter/logs/log.go @@ -15,7 +15,7 @@ // Package logs provide a general log interface // Usage: // -// import "github.com/astaxie/beego/logs" +// import "github.com/beego/beego/v2/logs" // // log := NewLogger(10000) // log.SetLogger("console", "") @@ -37,7 +37,7 @@ import ( "log" "time" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // RFC5424 log message levels. diff --git a/adapter/logs/log_adapter.go b/adapter/logs/log_adapter.go index 6b7022d6..e767724e 100644 --- a/adapter/logs/log_adapter.go +++ b/adapter/logs/log_adapter.go @@ -17,7 +17,7 @@ package logs import ( "time" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) type oldToNewAdapter struct { diff --git a/adapter/logs/logger.go b/adapter/logs/logger.go index 5a8e0a1c..58bdfc30 100644 --- a/adapter/logs/logger.go +++ b/adapter/logs/logger.go @@ -15,7 +15,7 @@ package logs import ( - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // ColorByStatus return color by http code diff --git a/adapter/metric/prometheus.go b/adapter/metric/prometheus.go index 4660f626..6b276171 100644 --- a/adapter/metric/prometheus.go +++ b/adapter/metric/prometheus.go @@ -23,9 +23,9 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/astaxie/beego" - "github.com/astaxie/beego/core/logs" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/server/web" ) func PrometheusMiddleWare(next http.Handler) http.Handler { @@ -38,7 +38,7 @@ func PrometheusMiddleWare(next http.Handler) http.Handler { "appname": web.BConfig.AppName, }, Help: "The statics info for http request", - }, []string{"pattern", "method", "status", "duration"}) + }, []string{"pattern", "method", "status"}) prometheus.MustRegister(summaryVec) @@ -96,5 +96,5 @@ func report(dur time.Duration, writer http.ResponseWriter, q *http.Request, vec logs.Warn("we can not find the router info for this request, so request will be recorded as UNKNOWN: " + q.URL.String()) } ms := dur / time.Millisecond - vec.WithLabelValues(ptn, q.Method, strconv.Itoa(status), strconv.Itoa(int(ms))).Observe(float64(ms)) + vec.WithLabelValues(ptn, q.Method, strconv.Itoa(status)).Observe(float64(ms)) } diff --git a/adapter/metric/prometheus_test.go b/adapter/metric/prometheus_test.go index 751348bf..53984845 100644 --- a/adapter/metric/prometheus_test.go +++ b/adapter/metric/prometheus_test.go @@ -22,7 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/astaxie/beego/adapter/context" + "github.com/beego/beego/v2/adapter/context" ) func TestPrometheusMiddleWare(t *testing.T) { @@ -35,7 +35,7 @@ func TestPrometheusMiddleWare(t *testing.T) { }, Method: "POST", } - vec := prometheus.NewSummaryVec(prometheus.SummaryOpts{}, []string{"pattern", "method", "status", "duration"}) + vec := prometheus.NewSummaryVec(prometheus.SummaryOpts{}, []string{"pattern", "method", "status"}) report(time.Second, writer, request, vec) middleware.ServeHTTP(writer, request) diff --git a/adapter/migration/ddl.go b/adapter/migration/ddl.go index b43b4d34..93be2d7d 100644 --- a/adapter/migration/ddl.go +++ b/adapter/migration/ddl.go @@ -15,7 +15,7 @@ package migration import ( - "github.com/astaxie/beego/client/orm/migration" + "github.com/beego/beego/v2/client/orm/migration" ) // Index struct defines the structure of Index Columns diff --git a/adapter/migration/migration.go b/adapter/migration/migration.go index 677c35ca..57202232 100644 --- a/adapter/migration/migration.go +++ b/adapter/migration/migration.go @@ -28,7 +28,7 @@ package migration import ( - "github.com/astaxie/beego/client/orm/migration" + "github.com/beego/beego/v2/client/orm/migration" ) // const the data format for the bee generate migration datatype diff --git a/adapter/namespace.go b/adapter/namespace.go index 98cbd8a5..af7c77f8 100644 --- a/adapter/namespace.go +++ b/adapter/namespace.go @@ -17,10 +17,10 @@ package adapter import ( "net/http" - adtContext "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/server/web/context" + adtContext "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) type namespaceCond func(*adtContext.Context) bool @@ -91,28 +91,28 @@ func oldToNewFilter(filter []FilterFunc) []web.FilterFunc { } // Router same as beego.Rourer -// refer: https://godoc.org/github.com/astaxie/beego#Router +// refer: https://godoc.org/github.com/beego/beego/v2#Router func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace { (*web.Namespace)(n).Router(rootpath, c, mappingMethods...) return n } // AutoRouter same as beego.AutoRouter -// refer: https://godoc.org/github.com/astaxie/beego#AutoRouter +// refer: https://godoc.org/github.com/beego/beego/v2#AutoRouter func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace { (*web.Namespace)(n).AutoRouter(c) return n } // AutoPrefix same as beego.AutoPrefix -// refer: https://godoc.org/github.com/astaxie/beego#AutoPrefix +// refer: https://godoc.org/github.com/beego/beego/v2#AutoPrefix func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace { (*web.Namespace)(n).AutoPrefix(prefix, c) return n } // Get same as beego.Get -// refer: https://godoc.org/github.com/astaxie/beego#Get +// refer: https://godoc.org/github.com/beego/beego/v2#Get func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Get(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -121,7 +121,7 @@ func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace { } // Post same as beego.Post -// refer: https://godoc.org/github.com/astaxie/beego#Post +// refer: https://godoc.org/github.com/beego/beego/v2#Post func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Post(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -130,7 +130,7 @@ func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace { } // Delete same as beego.Delete -// refer: https://godoc.org/github.com/astaxie/beego#Delete +// refer: https://godoc.org/github.com/beego/beego/v2#Delete func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Delete(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -139,7 +139,7 @@ func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace { } // Put same as beego.Put -// refer: https://godoc.org/github.com/astaxie/beego#Put +// refer: https://godoc.org/github.com/beego/beego/v2#Put func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Put(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -148,7 +148,7 @@ func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace { } // Head same as beego.Head -// refer: https://godoc.org/github.com/astaxie/beego#Head +// refer: https://godoc.org/github.com/beego/beego/v2#Head func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Head(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -157,7 +157,7 @@ func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace { } // Options same as beego.Options -// refer: https://godoc.org/github.com/astaxie/beego#Options +// refer: https://godoc.org/github.com/beego/beego/v2#Options func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Options(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -166,7 +166,7 @@ func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace { } // Patch same as beego.Patch -// refer: https://godoc.org/github.com/astaxie/beego#Patch +// refer: https://godoc.org/github.com/beego/beego/v2#Patch func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Patch(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -175,7 +175,7 @@ func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace { } // Any same as beego.Any -// refer: https://godoc.org/github.com/astaxie/beego#Any +// refer: https://godoc.org/github.com/beego/beego/v2#Any func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace { (*web.Namespace)(n).Any(rootpath, func(ctx *context.Context) { f((*adtContext.Context)(ctx)) @@ -184,14 +184,14 @@ func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace { } // Handler same as beego.Handler -// refer: https://godoc.org/github.com/astaxie/beego#Handler +// refer: https://godoc.org/github.com/beego/beego/v2#Handler func (n *Namespace) Handler(rootpath string, h http.Handler) *Namespace { (*web.Namespace)(n).Handler(rootpath, h) return n } // Include add include class -// refer: https://godoc.org/github.com/astaxie/beego#Include +// refer: https://godoc.org/github.com/beego/beego/v2#Include func (n *Namespace) Include(cList ...ControllerInterface) *Namespace { nL := oldToNewCtrlIntfs(cList) (*web.Namespace)(n).Include(nL...) @@ -238,141 +238,158 @@ func AddNamespace(nl ...*Namespace) { // NSCond is Namespace Condition func NSCond(cond namespaceCond) LinkNamespace { + wc := web.NSCond(func(b *context.Context) bool { + return cond((*adtContext.Context)(b)) + }) return func(namespace *Namespace) { - web.NSCond(func(b *context.Context) bool { - return cond((*adtContext.Context)(b)) - }) + wc((*web.Namespace)(namespace)) } } // NSBefore Namespace BeforeRouter filter func NSBefore(filterList ...FilterFunc) LinkNamespace { + nfs := oldToNewFilter(filterList) + wf := web.NSBefore(nfs...) return func(namespace *Namespace) { - nfs := oldToNewFilter(filterList) - web.NSBefore(nfs...) + wf((*web.Namespace)(namespace)) } } // NSAfter add Namespace FinishRouter filter func NSAfter(filterList ...FilterFunc) LinkNamespace { + nfs := oldToNewFilter(filterList) + wf := web.NSAfter(nfs...) return func(namespace *Namespace) { - nfs := oldToNewFilter(filterList) - web.NSAfter(nfs...) + wf((*web.Namespace)(namespace)) } } // NSInclude Namespace Include ControllerInterface func NSInclude(cList ...ControllerInterface) LinkNamespace { + nfs := oldToNewCtrlIntfs(cList) + wi := web.NSInclude(nfs...) return func(namespace *Namespace) { - nfs := oldToNewCtrlIntfs(cList) - web.NSInclude(nfs...) + wi((*web.Namespace)(namespace)) } } // NSRouter call Namespace Router func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) LinkNamespace { + wn := web.NSRouter(rootpath, c, mappingMethods...) return func(namespace *Namespace) { - web.Router(rootpath, c, mappingMethods...) + wn((*web.Namespace)(namespace)) } } // NSGet call Namespace Get func NSGet(rootpath string, f FilterFunc) LinkNamespace { + ln := web.NSGet(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSGet(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + ln((*web.Namespace)(ns)) } } // NSPost call Namespace Post func NSPost(rootpath string, f FilterFunc) LinkNamespace { + wp := web.NSPost(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.Post(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wp((*web.Namespace)(ns)) } } // NSHead call Namespace Head func NSHead(rootpath string, f FilterFunc) LinkNamespace { + wb := web.NSHead(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSHead(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wb((*web.Namespace)(ns)) } } // NSPut call Namespace Put func NSPut(rootpath string, f FilterFunc) LinkNamespace { + wn := web.NSPut(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSPut(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wn((*web.Namespace)(ns)) } } // NSDelete call Namespace Delete func NSDelete(rootpath string, f FilterFunc) LinkNamespace { + wn := web.NSDelete(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSDelete(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wn((*web.Namespace)(ns)) } } // NSAny call Namespace Any func NSAny(rootpath string, f FilterFunc) LinkNamespace { + wn := web.NSAny(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSAny(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wn((*web.Namespace)(ns)) } } // NSOptions call Namespace Options func NSOptions(rootpath string, f FilterFunc) LinkNamespace { + wo := web.NSOptions(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSOptions(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wo((*web.Namespace)(ns)) } } // NSPatch call Namespace Patch func NSPatch(rootpath string, f FilterFunc) LinkNamespace { + wn := web.NSPatch(rootpath, func(ctx *context.Context) { + f((*adtContext.Context)(ctx)) + }) return func(ns *Namespace) { - web.NSPatch(rootpath, func(ctx *context.Context) { - f((*adtContext.Context)(ctx)) - }) + wn((*web.Namespace)(ns)) } } // NSAutoRouter call Namespace AutoRouter func NSAutoRouter(c ControllerInterface) LinkNamespace { + wn := web.NSAutoRouter(c) return func(ns *Namespace) { - web.NSAutoRouter(c) + wn((*web.Namespace)(ns)) } } // NSAutoPrefix call Namespace AutoPrefix func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace { + wn := web.NSAutoPrefix(prefix, c) return func(ns *Namespace) { - web.NSAutoPrefix(prefix, c) + wn((*web.Namespace)(ns)) } } // NSNamespace add sub Namespace func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace { + nps := oldToNewLinkNs(params) + wn := web.NSNamespace(prefix, nps...) return func(ns *Namespace) { - nps := oldToNewLinkNs(params) - web.NSNamespace(prefix, nps...) + wn((*web.Namespace)(ns)) } } // NSHandler add handler func NSHandler(rootpath string, h http.Handler) LinkNamespace { + wn := web.NSHandler(rootpath, h) return func(ns *Namespace) { - web.NSHandler(rootpath, h) + wn((*web.Namespace)(ns)) } } diff --git a/adapter/orm/cmd.go b/adapter/orm/cmd.go index fcbd1be4..d8399c90 100644 --- a/adapter/orm/cmd.go +++ b/adapter/orm/cmd.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // RunCommand listen for orm command and then run it if command arguments passed. diff --git a/adapter/orm/db.go b/adapter/orm/db.go index fd878732..3cdd33cd 100644 --- a/adapter/orm/db.go +++ b/adapter/orm/db.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) var ( diff --git a/adapter/orm/db_alias.go b/adapter/orm/db_alias.go index 81a07207..f910c3f9 100644 --- a/adapter/orm/db_alias.go +++ b/adapter/orm/db_alias.go @@ -19,7 +19,7 @@ import ( "database/sql" "time" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // DriverType database driver constant int. diff --git a/adapter/orm/models.go b/adapter/orm/models.go index 5df64d6d..ee6b9194 100644 --- a/adapter/orm/models.go +++ b/adapter/orm/models.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // ResetModelCache Clean model cache. Then you can re-RegisterModel. diff --git a/adapter/orm/models_boot.go b/adapter/orm/models_boot.go index 0b07de59..678b86e6 100644 --- a/adapter/orm/models_boot.go +++ b/adapter/orm/models_boot.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // RegisterModel register models @@ -25,7 +25,7 @@ func RegisterModel(models ...interface{}) { // RegisterModelWithPrefix register models with a prefix func RegisterModelWithPrefix(prefix string, models ...interface{}) { - orm.RegisterModelWithPrefix(prefix, models) + orm.RegisterModelWithPrefix(prefix, models...) } // RegisterModelWithSuffix register models with a suffix diff --git a/adapter/orm/models_boot_test.go b/adapter/orm/models_boot_test.go new file mode 100644 index 00000000..37dbfabd --- /dev/null +++ b/adapter/orm/models_boot_test.go @@ -0,0 +1,30 @@ +// Copyright 2020 beego +// +// 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 ( + "testing" +) + +type User struct { + Id int +} + +type Seller struct { + Id int +} +func TestRegisterModelWithPrefix(t *testing.T) { + RegisterModelWithPrefix("test", &User{}, &Seller{}) +} diff --git a/adapter/orm/models_fields.go b/adapter/orm/models_fields.go index 6210567b..ff0b0e87 100644 --- a/adapter/orm/models_fields.go +++ b/adapter/orm/models_fields.go @@ -17,7 +17,7 @@ package orm import ( "time" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // Define the Type enum diff --git a/adapter/orm/orm.go b/adapter/orm/orm.go index 15df76ed..c603de2f 100644 --- a/adapter/orm/orm.go +++ b/adapter/orm/orm.go @@ -21,7 +21,7 @@ // // import ( // "fmt" -// "github.com/astaxie/beego/orm" +// "github.com/beego/beego/v2/orm" // _ "github.com/go-sql-driver/mysql" // import your used driver // ) // @@ -58,9 +58,9 @@ import ( "database/sql" "errors" - "github.com/astaxie/beego/client/orm" - "github.com/astaxie/beego/client/orm/hints" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/client/orm" + "github.com/beego/beego/v2/client/orm/hints" + "github.com/beego/beego/v2/core/utils" ) // DebugQueries define the debug diff --git a/adapter/orm/orm_conds.go b/adapter/orm/orm_conds.go index f70f0f5b..387caac2 100644 --- a/adapter/orm/orm_conds.go +++ b/adapter/orm/orm_conds.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // ExprSep define the expression separation diff --git a/adapter/orm/orm_log.go b/adapter/orm/orm_log.go index 3ff7f01c..98c1522e 100644 --- a/adapter/orm/orm_log.go +++ b/adapter/orm/orm_log.go @@ -17,7 +17,7 @@ package orm import ( "io" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // Log implement the log.Logger diff --git a/adapter/orm/orm_queryset.go b/adapter/orm/orm_queryset.go index 1926a6c0..b1f4c165 100644 --- a/adapter/orm/orm_queryset.go +++ b/adapter/orm/orm_queryset.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // define Col operations diff --git a/adapter/orm/qb.go b/adapter/orm/qb.go index 63eaed8a..57c8d62a 100644 --- a/adapter/orm/qb.go +++ b/adapter/orm/qb.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // QueryBuilder is the Query builder interface diff --git a/adapter/orm/qb_mysql.go b/adapter/orm/qb_mysql.go index ef87ebab..10b38ea9 100644 --- a/adapter/orm/qb_mysql.go +++ b/adapter/orm/qb_mysql.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // CommaSpace is the separation diff --git a/adapter/orm/qb_tidb.go b/adapter/orm/qb_tidb.go index 18631ef0..d3c94e0f 100644 --- a/adapter/orm/qb_tidb.go +++ b/adapter/orm/qb_tidb.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // TiDBQueryBuilder is the SQL build diff --git a/adapter/orm/query_setter_adapter.go b/adapter/orm/query_setter_adapter.go index d6c268b6..7f506759 100644 --- a/adapter/orm/query_setter_adapter.go +++ b/adapter/orm/query_setter_adapter.go @@ -15,7 +15,7 @@ package orm import ( - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) type baseQuerySetter struct { diff --git a/adapter/orm/types.go b/adapter/orm/types.go index 6db5066c..428f8b14 100644 --- a/adapter/orm/types.go +++ b/adapter/orm/types.go @@ -18,7 +18,7 @@ import ( "context" "database/sql" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // Params stores the Params diff --git a/adapter/orm/utils.go b/adapter/orm/utils.go index 37ba86d8..22bf8d63 100644 --- a/adapter/orm/utils.go +++ b/adapter/orm/utils.go @@ -21,7 +21,7 @@ import ( "strings" "time" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) type fn func(string) string diff --git a/adapter/plugins/apiauth/apiauth.go b/adapter/plugins/apiauth/apiauth.go index 90311d8f..fd0c7ff4 100644 --- a/adapter/plugins/apiauth/apiauth.go +++ b/adapter/plugins/apiauth/apiauth.go @@ -16,8 +16,8 @@ // // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/apiauth" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/apiauth" // ) // // func main(){ @@ -58,10 +58,10 @@ package apiauth import ( "net/url" - beego "github.com/astaxie/beego/adapter" - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/filter/apiauth" + beego "github.com/beego/beego/v2/adapter" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/filter/apiauth" ) // AppIDToAppSecret is used to get appsecret throw appid diff --git a/adapter/plugins/auth/basic.go b/adapter/plugins/auth/basic.go index 578a16d9..4ef3343f 100644 --- a/adapter/plugins/auth/basic.go +++ b/adapter/plugins/auth/basic.go @@ -15,8 +15,8 @@ // Package auth provides handlers to enable basic auth support. // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/auth" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/auth" // ) // // func main(){ @@ -38,10 +38,10 @@ package auth import ( "net/http" - beego "github.com/astaxie/beego/adapter" - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/filter/auth" + beego "github.com/beego/beego/v2/adapter" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/filter/auth" ) // Basic is the http basic auth diff --git a/adapter/plugins/authz/authz.go b/adapter/plugins/authz/authz.go index 3f84467e..114c8c9a 100644 --- a/adapter/plugins/authz/authz.go +++ b/adapter/plugins/authz/authz.go @@ -15,8 +15,8 @@ // Package authz provides handlers to enable ACL, RBAC, ABAC authorization support. // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/authz" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/authz" // "github.com/casbin/casbin" // ) // @@ -44,10 +44,10 @@ import ( "github.com/casbin/casbin" - beego "github.com/astaxie/beego/adapter" - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/filter/authz" + beego "github.com/beego/beego/v2/adapter" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/filter/authz" ) // NewAuthorizer returns the authorizer. diff --git a/adapter/plugins/authz/authz_model.conf b/adapter/plugins/authz/authz_model.conf index d1b3dbd7..fd2f08df 100644 --- a/adapter/plugins/authz/authz_model.conf +++ b/adapter/plugins/authz/authz_model.conf @@ -11,4 +11,4 @@ g = _, _ e = some(where (p.eft == allow)) [matchers] -m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") \ No newline at end of file +m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") diff --git a/adapter/plugins/authz/authz_policy.csv b/adapter/plugins/authz/authz_policy.csv index c062dd3e..9203e11f 100644 --- a/adapter/plugins/authz/authz_policy.csv +++ b/adapter/plugins/authz/authz_policy.csv @@ -4,4 +4,4 @@ p, bob, /dataset2/resource1, * p, bob, /dataset2/resource2, GET p, bob, /dataset2/folder1/*, POST p, dataset1_admin, /dataset1/*, * -g, cathy, dataset1_admin \ No newline at end of file +g, cathy, dataset1_admin diff --git a/adapter/plugins/authz/authz_test.go b/adapter/plugins/authz/authz_test.go index 9b4f21c2..fa5410ca 100644 --- a/adapter/plugins/authz/authz_test.go +++ b/adapter/plugins/authz/authz_test.go @@ -19,10 +19,11 @@ import ( "net/http/httptest" "testing" - beego "github.com/astaxie/beego/adapter" - "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/adapter/plugins/auth" "github.com/casbin/casbin" + + beego "github.com/beego/beego/v2/adapter" + "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/adapter/plugins/auth" ) func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, path string, method string, code int) { diff --git a/adapter/plugins/cors/cors.go b/adapter/plugins/cors/cors.go index a15d5417..6a836585 100644 --- a/adapter/plugins/cors/cors.go +++ b/adapter/plugins/cors/cors.go @@ -15,8 +15,8 @@ // Package cors provides handlers to enable CORS support. // Usage // import ( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/cors" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/cors" // ) // // func main() { @@ -36,11 +36,11 @@ package cors import ( - beego "github.com/astaxie/beego/adapter" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/filter/cors" + beego "github.com/beego/beego/v2/adapter" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/filter/cors" - "github.com/astaxie/beego/adapter/context" + "github.com/beego/beego/v2/adapter/context" ) // Options represents Access Control options. diff --git a/adapter/policy.go b/adapter/policy.go index 6f334d2d..c0b95601 100644 --- a/adapter/policy.go +++ b/adapter/policy.go @@ -15,9 +15,9 @@ package adapter import ( - "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/server/web" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web" + beecontext "github.com/beego/beego/v2/server/web/context" ) // PolicyFunc defines a policy function which is invoked before the controller handler is executed. diff --git a/adapter/router.go b/adapter/router.go index c91a09f1..17e270ca 100644 --- a/adapter/router.go +++ b/adapter/router.go @@ -18,10 +18,10 @@ import ( "net/http" "time" - beecontext "github.com/astaxie/beego/adapter/context" - "github.com/astaxie/beego/server/web/context" + beecontext "github.com/beego/beego/v2/adapter/context" + "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) // default filter execution points @@ -87,7 +87,7 @@ func NewControllerRegister() *ControllerRegister { // Add("/api",&RestController{},"get,post:ApiFunc" // Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc") func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) { - (*web.ControllerRegister)(p).Add(pattern, c, mappingMethods...) + (*web.ControllerRegister)(p).Add(pattern, c, web.SetRouterMethods(c, mappingMethods...)) } // Include only when the Runmode is dev will generate router file in the router/auto.go from the controller diff --git a/adapter/session/couchbase/sess_couchbase.go b/adapter/session/couchbase/sess_couchbase.go index b6afb612..4ce2d69d 100644 --- a/adapter/session/couchbase/sess_couchbase.go +++ b/adapter/session/couchbase/sess_couchbase.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/couchbase" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/couchbase" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -36,8 +36,8 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" - beecb "github.com/astaxie/beego/server/web/session/couchbase" + "github.com/beego/beego/v2/adapter/session" + beecb "github.com/beego/beego/v2/server/web/session/couchbase" ) // SessionStore store each session diff --git a/adapter/session/ledis/ledis_session.go b/adapter/session/ledis/ledis_session.go index 350cbdaa..c42c1787 100644 --- a/adapter/session/ledis/ledis_session.go +++ b/adapter/session/ledis/ledis_session.go @@ -5,8 +5,8 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" - beeLedis "github.com/astaxie/beego/server/web/session/ledis" + "github.com/beego/beego/v2/adapter/session" + beeLedis "github.com/beego/beego/v2/server/web/session/ledis" ) // SessionStore ledis session store diff --git a/adapter/session/memcache/sess_memcache.go b/adapter/session/memcache/sess_memcache.go index 772839cd..e81d06c6 100644 --- a/adapter/session/memcache/sess_memcache.go +++ b/adapter/session/memcache/sess_memcache.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/memcache" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/memcache" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -36,9 +36,9 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" - beemem "github.com/astaxie/beego/server/web/session/memcache" + beemem "github.com/beego/beego/v2/server/web/session/memcache" ) // SessionStore memcache session store diff --git a/adapter/session/mysql/sess_mysql.go b/adapter/session/mysql/sess_mysql.go index 5d7e1dac..d47e7496 100644 --- a/adapter/session/mysql/sess_mysql.go +++ b/adapter/session/mysql/sess_mysql.go @@ -28,8 +28,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/mysql" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/mysql" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -44,8 +44,8 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" - "github.com/astaxie/beego/server/web/session/mysql" + "github.com/beego/beego/v2/adapter/session" + "github.com/beego/beego/v2/server/web/session/mysql" // import mysql driver _ "github.com/go-sql-driver/mysql" diff --git a/adapter/session/postgres/sess_postgresql.go b/adapter/session/postgres/sess_postgresql.go index 879b2b83..a24794d6 100644 --- a/adapter/session/postgres/sess_postgresql.go +++ b/adapter/session/postgres/sess_postgresql.go @@ -38,8 +38,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/postgresql" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/postgresql" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -54,11 +54,11 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" // import postgresql Driver _ "github.com/lib/pq" - "github.com/astaxie/beego/server/web/session/postgres" + "github.com/beego/beego/v2/server/web/session/postgres" ) // SessionStore postgresql session store diff --git a/adapter/session/provider_adapter.go b/adapter/session/provider_adapter.go index 596bc6a6..3e62aa63 100644 --- a/adapter/session/provider_adapter.go +++ b/adapter/session/provider_adapter.go @@ -17,7 +17,7 @@ package session import ( "context" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) type oldToNewProviderAdapter struct { diff --git a/adapter/session/redis/sess_redis.go b/adapter/session/redis/sess_redis.go index bb8e8be4..a5fcedf6 100644 --- a/adapter/session/redis/sess_redis.go +++ b/adapter/session/redis/sess_redis.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -36,9 +36,9 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" - beeRedis "github.com/astaxie/beego/server/web/session/redis" + beeRedis "github.com/beego/beego/v2/server/web/session/redis" ) // MaxPoolSize redis max pool size diff --git a/adapter/session/redis_cluster/redis_cluster.go b/adapter/session/redis_cluster/redis_cluster.go index 1be22cd4..f4c8e4d1 100644 --- a/adapter/session/redis_cluster/redis_cluster.go +++ b/adapter/session/redis_cluster/redis_cluster.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis_cluster" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis_cluster" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -36,8 +36,8 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" - cluster "github.com/astaxie/beego/server/web/session/redis_cluster" + "github.com/beego/beego/v2/adapter/session" + cluster "github.com/beego/beego/v2/server/web/session/redis_cluster" ) // MaxPoolSize redis_cluster max pool size diff --git a/adapter/session/redis_sentinel/sess_redis_sentinel.go b/adapter/session/redis_sentinel/sess_redis_sentinel.go index 7ab9e7c5..4498e55d 100644 --- a/adapter/session/redis_sentinel/sess_redis_sentinel.go +++ b/adapter/session/redis_sentinel/sess_redis_sentinel.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis_sentinel" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis_sentinel" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -36,9 +36,9 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" - sentinel "github.com/astaxie/beego/server/web/session/redis_sentinel" + sentinel "github.com/beego/beego/v2/server/web/session/redis_sentinel" ) // DefaultPoolSize redis_sentinel default pool size diff --git a/adapter/session/redis_sentinel/sess_redis_sentinel_test.go b/adapter/session/redis_sentinel/sess_redis_sentinel_test.go index 407d32ab..0a6249ee 100644 --- a/adapter/session/redis_sentinel/sess_redis_sentinel_test.go +++ b/adapter/session/redis_sentinel/sess_redis_sentinel_test.go @@ -5,7 +5,7 @@ import ( "net/http/httptest" "testing" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" ) func TestRedisSentinel(t *testing.T) { diff --git a/adapter/session/sess_cookie.go b/adapter/session/sess_cookie.go index 3fcbd28e..ef3b6799 100644 --- a/adapter/session/sess_cookie.go +++ b/adapter/session/sess_cookie.go @@ -18,7 +18,7 @@ import ( "context" "net/http" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // CookieSessionStore Cookie SessionStore diff --git a/adapter/session/sess_file.go b/adapter/session/sess_file.go index 2ba33e6d..c201cf74 100644 --- a/adapter/session/sess_file.go +++ b/adapter/session/sess_file.go @@ -18,7 +18,7 @@ import ( "context" "net/http" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // FileSessionStore File session store diff --git a/adapter/session/sess_mem.go b/adapter/session/sess_mem.go index febed719..6a4e62c6 100644 --- a/adapter/session/sess_mem.go +++ b/adapter/session/sess_mem.go @@ -18,7 +18,7 @@ import ( "context" "net/http" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // MemSessionStore memory session store. diff --git a/adapter/session/sess_utils.go b/adapter/session/sess_utils.go index 4cfdc760..2fe229d7 100644 --- a/adapter/session/sess_utils.go +++ b/adapter/session/sess_utils.go @@ -15,7 +15,7 @@ package session import ( - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // EncodeGob encode the obj to gob diff --git a/adapter/session/session.go b/adapter/session/session.go index d8b151b7..40e947fd 100644 --- a/adapter/session/session.go +++ b/adapter/session/session.go @@ -16,7 +16,7 @@ // // Usage: // import( -// "github.com/astaxie/beego/session" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -32,7 +32,7 @@ import ( "net/http" "os" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // Store contains all data for one session process with specific id. @@ -141,7 +141,7 @@ func (manager *Manager) GC() { // SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request. func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) Store { - s := (*session.Manager)(manager).SessionRegenerateID(w, r) + s, _ := (*session.Manager)(manager).SessionRegenerateID(w, r) return &NewToOldStoreAdapter{ delegate: s, } diff --git a/adapter/session/ssdb/sess_ssdb.go b/adapter/session/ssdb/sess_ssdb.go index cd9c4a24..73ead908 100644 --- a/adapter/session/ssdb/sess_ssdb.go +++ b/adapter/session/ssdb/sess_ssdb.go @@ -4,9 +4,9 @@ import ( "context" "net/http" - "github.com/astaxie/beego/adapter/session" + "github.com/beego/beego/v2/adapter/session" - beeSsdb "github.com/astaxie/beego/server/web/session/ssdb" + beeSsdb "github.com/beego/beego/v2/server/web/session/ssdb" ) // Provider holds ssdb client and configs diff --git a/adapter/session/store_adapter.go b/adapter/session/store_adapter.go index 70ad83e2..a459e68c 100644 --- a/adapter/session/store_adapter.go +++ b/adapter/session/store_adapter.go @@ -18,7 +18,7 @@ import ( "context" "net/http" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) type NewToOldStoreAdapter struct { diff --git a/adapter/swagger/swagger.go b/adapter/swagger/swagger.go index 7a44b770..fbb00bb4 100644 --- a/adapter/swagger/swagger.go +++ b/adapter/swagger/swagger.go @@ -21,7 +21,7 @@ package swagger import ( - "github.com/astaxie/beego/server/web/swagger" + "github.com/beego/beego/v2/server/web/swagger" ) // Swagger list the resource diff --git a/adapter/template.go b/adapter/template.go index 67f5a33b..5957a0eb 100644 --- a/adapter/template.go +++ b/adapter/template.go @@ -19,7 +19,7 @@ import ( "io" "net/http" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) // ExecuteTemplate applies the template with name to the specified data object, diff --git a/adapter/templatefunc.go b/adapter/templatefunc.go index 0c805393..808539e7 100644 --- a/adapter/templatefunc.go +++ b/adapter/templatefunc.go @@ -19,7 +19,7 @@ import ( "net/url" "time" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) const ( diff --git a/adapter/testing/client.go b/adapter/testing/client.go index 5c138167..356a0f68 100644 --- a/adapter/testing/client.go +++ b/adapter/testing/client.go @@ -15,7 +15,7 @@ package testing import ( - "github.com/astaxie/beego/client/httplib/testing" + "github.com/beego/beego/v2/client/httplib/testing" ) var port = "" diff --git a/adapter/toolbox/healthcheck.go b/adapter/toolbox/healthcheck.go index 7d89c2fb..9095053f 100644 --- a/adapter/toolbox/healthcheck.go +++ b/adapter/toolbox/healthcheck.go @@ -31,19 +31,19 @@ package toolbox import ( - "github.com/astaxie/beego/core/governor" + "github.com/beego/beego/v2/core/admin" ) // AdminCheckList holds health checker map -// Deprecated using governor.AdminCheckList +// Deprecated using admin.AdminCheckList var AdminCheckList map[string]HealthChecker // HealthChecker health checker interface -type HealthChecker governor.HealthChecker +type HealthChecker admin.HealthChecker // AddHealthCheck add health checker with name string func AddHealthCheck(name string, hc HealthChecker) { - governor.AddHealthCheck(name, hc) + admin.AddHealthCheck(name, hc) AdminCheckList[name] = hc } diff --git a/adapter/toolbox/profile.go b/adapter/toolbox/profile.go index a5434360..15d7010a 100644 --- a/adapter/toolbox/profile.go +++ b/adapter/toolbox/profile.go @@ -19,7 +19,7 @@ import ( "os" "time" - "github.com/astaxie/beego/core/governor" + "github.com/beego/beego/v2/core/admin" ) var startTime = time.Now() @@ -31,20 +31,20 @@ func init() { // ProcessInput parse input command string func ProcessInput(input string, w io.Writer) { - governor.ProcessInput(input, w) + admin.ProcessInput(input, w) } // MemProf record memory profile in pprof func MemProf(w io.Writer) { - governor.MemProf(w) + admin.MemProf(w) } // GetCPUProfile start cpu profile monitor func GetCPUProfile(w io.Writer) { - governor.GetCPUProfile(w) + admin.GetCPUProfile(w) } // PrintGCSummary print gc information to io.Writer func PrintGCSummary(w io.Writer) { - governor.PrintGCSummary(w) + admin.PrintGCSummary(w) } diff --git a/adapter/toolbox/statistics.go b/adapter/toolbox/statistics.go index 7c8cd75e..47bfbbd5 100644 --- a/adapter/toolbox/statistics.go +++ b/adapter/toolbox/statistics.go @@ -17,7 +17,7 @@ package toolbox import ( "time" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) // Statistics struct diff --git a/adapter/toolbox/task.go b/adapter/toolbox/task.go index 7f1bfc45..bdd6679f 100644 --- a/adapter/toolbox/task.go +++ b/adapter/toolbox/task.go @@ -19,7 +19,7 @@ import ( "sort" "time" - "github.com/astaxie/beego/task" + "github.com/beego/beego/v2/task" ) // The bounds for each field. diff --git a/adapter/tree.go b/adapter/tree.go index 36f763ea..fe9f6933 100644 --- a/adapter/tree.go +++ b/adapter/tree.go @@ -15,10 +15,10 @@ package adapter import ( - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/server/web" + "github.com/beego/beego/v2/server/web" ) // Tree has three elements: FixRouter/wildcard/leaves diff --git a/adapter/tree_test.go b/adapter/tree_test.go deleted file mode 100644 index 2315d829..00000000 --- a/adapter/tree_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// 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 adapter - -import ( - "testing" - - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" -) - -type testinfo struct { - url string - requesturl string - params map[string]string -} - -var routers []testinfo - -func init() { - routers = make([]testinfo, 0) - routers = append(routers, testinfo{"/topic/?:auth:int", "/topic", nil}) - routers = append(routers, testinfo{"/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1/2", map[string]string{":id": "1", ":auth": "2"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1", map[string]string{":id": "1"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1/123", map[string]string{":id": "1", ":auth": "123"}}) - routers = append(routers, testinfo{"/:id", "/123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/hello/?:id", "/hello", map[string]string{":id": ""}}) - routers = append(routers, testinfo{"/", "/", nil}) - routers = append(routers, testinfo{"/customer/login", "/customer/login", nil}) - routers = append(routers, testinfo{"/customer/login", "/customer/login.json", map[string]string{":ext": "json"}}) - routers = append(routers, testinfo{"/*", "/http://customer/123/", map[string]string{":splat": "http://customer/123/"}}) - routers = append(routers, testinfo{"/*", "/customer/2009/12/11", map[string]string{":splat": "customer/2009/12/11"}}) - routers = append(routers, testinfo{"/aa/*/bb", "/aa/2009/bb", map[string]string{":splat": "2009"}}) - routers = append(routers, testinfo{"/cc/*/dd", "/cc/2009/11/dd", map[string]string{":splat": "2009/11"}}) - routers = append(routers, testinfo{"/cc/:id/*", "/cc/2009/11/dd", map[string]string{":id": "2009", ":splat": "11/dd"}}) - routers = append(routers, testinfo{"/ee/:year/*/ff", "/ee/2009/11/ff", map[string]string{":year": "2009", ":splat": "11"}}) - routers = append(routers, testinfo{"/thumbnail/:size/uploads/*", - "/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg", - map[string]string{":size": "100x100", ":splat": "items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg"}}) - routers = append(routers, testinfo{"/*.*", "/nice/api.json", map[string]string{":path": "nice/api", ":ext": "json"}}) - routers = append(routers, testinfo{"/:name/*.*", "/nice/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}}) - routers = append(routers, testinfo{"/:name/test/*.*", "/nice/test/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}}) - routers = append(routers, testinfo{"/dl/:width:int/:height:int/*.*", - "/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg", - map[string]string{":width": "48", ":height": "48", ":ext": "jpg", ":path": "05ac66d9bda00a3acf948c43e306fc9a"}}) - routers = append(routers, testinfo{"/v1/shop/:id:int", "/v1/shop/123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(a)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(b)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(c)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/:year:int/:month:int/:id/:endid", "/1111/111/aaa/aaa", map[string]string{":year": "1111", ":month": "111", ":id": "aaa", ":endid": "aaa"}}) - routers = append(routers, testinfo{"/v1/shop/:id/:name", "/v1/shop/123/nike", map[string]string{":id": "123", ":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id/account", "/v1/shop/123/account", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:name:string", "/v1/shop/nike", map[string]string{":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)", "/v1/shop//123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)_:name", "/v1/shop/123_nike", map[string]string{":id": "123", ":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id(.+)_cms.html", "/v1/shop/123_cms.html", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/cms_:id(.+)_:page(.+).html", "/v1/shop/cms_123_1.html", map[string]string{":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v/cms/aaa_:id(.+)_:page(.+).html", "/v1/2/cms/aaa_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v/cms_:id(.+)_:page(.+).html", "/v1/2/cms_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", "/v1/2_cms/ttt_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"}}) - routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"}}) -} - -func TestTreeRouters(t *testing.T) { - for _, r := range routers { - tr := NewTree() - tr.AddRouter(r.url, "astaxie") - ctx := context.NewContext() - obj := tr.Match(r.requesturl, ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal(r.url+" can't get obj, Expect ", r.requesturl) - } - if r.params != nil { - for k, v := range r.params { - if vv := ctx.Input.Param(k); vv != v { - t.Fatal("The Rule: " + r.url + "\nThe RequestURL:" + r.requesturl + "\nThe Key is " + k + ", The Value should be: " + v + ", but get: " + vv) - } else if vv == "" && v != "" { - t.Fatal(r.url + " " + r.requesturl + " get param empty:" + k) - } - } - } - } -} - -func TestStaticPath(t *testing.T) { - tr := NewTree() - tr.AddRouter("/topic/:id", "wildcard") - tr.AddRouter("/topic", "static") - ctx := context.NewContext() - obj := tr.Match("/topic", ctx) - if obj == nil || obj.(string) != "static" { - t.Fatal("/topic is a static route") - } - obj = tr.Match("/topic/1", ctx) - if obj == nil || obj.(string) != "wildcard" { - t.Fatal("/topic/1 is a wildcard route") - } -} - -func TestAddTree(t *testing.T) { - tr := NewTree() - tr.AddRouter("/shop/:id/account", "astaxie") - tr.AddRouter("/shop/:sd/ttt_:id(.+)_:page(.+).html", "astaxie") - t1 := NewTree() - t1.AddTree("/v1/zl", tr) - ctx := context.NewContext() - obj := t1.Match("/v1/zl/shop/123/account", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/v1/zl/shop/:id/account can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":id") != "123" { - t.Fatal("get :id param error") - } - ctx.Input.Reset((*beecontext.Context)(ctx)) - obj = t1.Match("/v1/zl/shop/123/ttt_1_12.html", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/v1/zl//shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":sd") != "123" || ctx.Input.Param(":id") != "1" || ctx.Input.Param(":page") != "12" { - t.Fatal("get :sd :id :page param error") - } - - t2 := NewTree() - t2.AddTree("/v1/:shopid", tr) - ctx.Input.Reset((*beecontext.Context)(ctx)) - obj = t2.Match("/v1/zl/shop/123/account", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/v1/:shopid/shop/:id/account can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":id") != "123" || ctx.Input.Param(":shopid") != "zl" { - t.Fatal("get :id :shopid param error") - } - ctx.Input.Reset((*beecontext.Context)(ctx)) - obj = t2.Match("/v1/zl/shop/123/ttt_1_12.html", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/v1/:shopid/shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get :shopid param error") - } - if ctx.Input.Param(":sd") != "123" || ctx.Input.Param(":id") != "1" || ctx.Input.Param(":page") != "12" || ctx.Input.Param(":shopid") != "zl" { - t.Fatal("get :sd :id :page :shopid param error") - } -} - -func TestAddTree2(t *testing.T) { - tr := NewTree() - tr.AddRouter("/shop/:id/account", "astaxie") - tr.AddRouter("/shop/:sd/ttt_:id(.+)_:page(.+).html", "astaxie") - t3 := NewTree() - t3.AddTree("/:version(v1|v2)/:prefix", tr) - ctx := context.NewContext() - obj := t3.Match("/v1/zl/shop/123/account", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/:version(v1|v2)/:prefix/shop/:id/account can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":id") != "123" || ctx.Input.Param(":prefix") != "zl" || ctx.Input.Param(":version") != "v1" { - t.Fatal("get :id :prefix :version param error") - } -} - -func TestAddTree3(t *testing.T) { - tr := NewTree() - tr.AddRouter("/create", "astaxie") - tr.AddRouter("/shop/:sd/account", "astaxie") - t3 := NewTree() - t3.AddTree("/table/:num", tr) - ctx := context.NewContext() - obj := t3.Match("/table/123/shop/123/account", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/table/:num/shop/:sd/account can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":num") != "123" || ctx.Input.Param(":sd") != "123" { - t.Fatal("get :num :sd param error") - } - ctx.Input.Reset((*beecontext.Context)(ctx)) - obj = t3.Match("/table/123/create", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/table/:num/create can't get obj ") - } -} - -func TestAddTree4(t *testing.T) { - tr := NewTree() - tr.AddRouter("/create", "astaxie") - tr.AddRouter("/shop/:sd/:account", "astaxie") - t4 := NewTree() - t4.AddTree("/:info:int/:num/:id", tr) - ctx := context.NewContext() - obj := t4.Match("/12/123/456/shop/123/account", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/:info:int/:num/:id/shop/:sd/:account can't get obj ") - } - if ctx.Input.ParamsLen() == 0 { - t.Fatal("get param error") - } - if ctx.Input.Param(":info") != "12" || ctx.Input.Param(":num") != "123" || - ctx.Input.Param(":id") != "456" || ctx.Input.Param(":sd") != "123" || - ctx.Input.Param(":account") != "account" { - t.Fatal("get :info :num :id :sd :account param error") - } - ctx.Input.Reset((*beecontext.Context)(ctx)) - obj = t4.Match("/12/123/456/create", ctx) - if obj == nil || obj.(string) != "astaxie" { - t.Fatal("/:info:int/:num/:id/create can't get obj ") - } -} - -// Test for issue #1595 -func TestAddTree5(t *testing.T) { - tr := NewTree() - tr.AddRouter("/v1/shop/:id", "shopdetail") - tr.AddRouter("/v1/shop/", "shophome") - ctx := context.NewContext() - obj := tr.Match("/v1/shop/", ctx) - if obj == nil || obj.(string) != "shophome" { - t.Fatal("url /v1/shop/ need match router /v1/shop/ ") - } -} diff --git a/adapter/utils/caller.go b/adapter/utils/caller.go index 419f11d6..7aec5000 100644 --- a/adapter/utils/caller.go +++ b/adapter/utils/caller.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // GetFuncName get function name diff --git a/adapter/utils/captcha/README.md b/adapter/utils/captcha/README.md index dbc2026b..74e1cf82 100644 --- a/adapter/utils/captcha/README.md +++ b/adapter/utils/captcha/README.md @@ -6,9 +6,9 @@ an example for use captcha package controllers import ( - "github.com/astaxie/beego" - "github.com/astaxie/beego/cache" - "github.com/astaxie/beego/utils/captcha" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/cache" + "github.com/beego/beego/v2/utils/captcha" ) var cpt *captcha.Captcha diff --git a/adapter/utils/captcha/captcha.go b/adapter/utils/captcha/captcha.go index 71aad0f2..4f5dd867 100644 --- a/adapter/utils/captcha/captcha.go +++ b/adapter/utils/captcha/captcha.go @@ -19,9 +19,9 @@ // package controllers // // import ( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/cache" -// "github.com/astaxie/beego/utils/captcha" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/cache" +// "github.com/beego/beego/v2/utils/captcha" // ) // // var cpt *captcha.Captcha @@ -63,11 +63,11 @@ import ( "net/http" "time" - "github.com/astaxie/beego/server/web/captcha" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/captcha" + beecontext "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/adapter/cache" - "github.com/astaxie/beego/adapter/context" + "github.com/beego/beego/v2/adapter/cache" + "github.com/beego/beego/v2/adapter/context" ) var ( diff --git a/adapter/utils/captcha/image.go b/adapter/utils/captcha/image.go index 6a1b696b..c28beb3c 100644 --- a/adapter/utils/captcha/image.go +++ b/adapter/utils/captcha/image.go @@ -17,7 +17,7 @@ package captcha import ( "io" - "github.com/astaxie/beego/server/web/captcha" + "github.com/beego/beego/v2/server/web/captcha" ) // Image struct diff --git a/adapter/utils/captcha/image_test.go b/adapter/utils/captcha/image_test.go index 5d298573..8e3b1306 100644 --- a/adapter/utils/captcha/image_test.go +++ b/adapter/utils/captcha/image_test.go @@ -17,7 +17,7 @@ package captcha import ( "testing" - "github.com/astaxie/beego/adapter/utils" + "github.com/beego/beego/v2/adapter/utils" ) const ( diff --git a/adapter/utils/debug.go b/adapter/utils/debug.go index 3f4d2759..3e4e3a27 100644 --- a/adapter/utils/debug.go +++ b/adapter/utils/debug.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // Display print the data in console diff --git a/adapter/utils/file.go b/adapter/utils/file.go index aa9ac316..e6a785a2 100644 --- a/adapter/utils/file.go +++ b/adapter/utils/file.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // SelfPath gets compiled executable file absolute path diff --git a/adapter/utils/mail.go b/adapter/utils/mail.go index 74a8f403..4ef89660 100644 --- a/adapter/utils/mail.go +++ b/adapter/utils/mail.go @@ -17,7 +17,7 @@ package utils import ( "io" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // Email is the type used for email messages diff --git a/adapter/utils/pagination/controller.go b/adapter/utils/pagination/controller.go index c82c54f9..ab3fb83d 100644 --- a/adapter/utils/pagination/controller.go +++ b/adapter/utils/pagination/controller.go @@ -15,9 +15,9 @@ package pagination import ( - "github.com/astaxie/beego/adapter/context" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/pagination" + "github.com/beego/beego/v2/adapter/context" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/pagination" ) // SetPaginator Instantiates a Paginator and assigns it to context.Input.Data("paginator"). diff --git a/adapter/utils/pagination/doc.go b/adapter/utils/pagination/doc.go index 9abc6d78..d180b093 100644 --- a/adapter/utils/pagination/doc.go +++ b/adapter/utils/pagination/doc.go @@ -8,7 +8,7 @@ In your beego.Controller: package controllers - import "github.com/astaxie/beego/utils/pagination" + import "github.com/beego/beego/v2/utils/pagination" type PostsController struct { beego.Controller diff --git a/adapter/utils/pagination/paginator.go b/adapter/utils/pagination/paginator.go index 73d9157f..cbf71da4 100644 --- a/adapter/utils/pagination/paginator.go +++ b/adapter/utils/pagination/paginator.go @@ -17,7 +17,7 @@ package pagination import ( "net/http" - "github.com/astaxie/beego/core/utils/pagination" + "github.com/beego/beego/v2/core/utils/pagination" ) // Paginator within the state of a http request. diff --git a/adapter/utils/rand.go b/adapter/utils/rand.go index 0fcca580..2c22ac76 100644 --- a/adapter/utils/rand.go +++ b/adapter/utils/rand.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // RandomCreateBytes generate random []byte by specify chars. diff --git a/adapter/utils/safemap.go b/adapter/utils/safemap.go index bb50f3cd..62bf811b 100644 --- a/adapter/utils/safemap.go +++ b/adapter/utils/safemap.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // BeeMap is a map with lock diff --git a/adapter/utils/slice.go b/adapter/utils/slice.go index 44b782b4..cdbfcca8 100644 --- a/adapter/utils/slice.go +++ b/adapter/utils/slice.go @@ -15,7 +15,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) type reducetype func(interface{}) interface{} diff --git a/adapter/utils/utils.go b/adapter/utils/utils.go index 8ba21bc4..235cc352 100644 --- a/adapter/utils/utils.go +++ b/adapter/utils/utils.go @@ -1,7 +1,7 @@ package utils import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // GetGOPATHs returns all paths in GOPATH variable. diff --git a/adapter/validation/util.go b/adapter/validation/util.go index 431ce80d..502be750 100644 --- a/adapter/validation/util.go +++ b/adapter/validation/util.go @@ -17,7 +17,7 @@ package validation import ( "reflect" - "github.com/astaxie/beego/core/validation" + "github.com/beego/beego/v2/core/validation" ) const ( diff --git a/adapter/validation/validation.go b/adapter/validation/validation.go index e90c9f5b..8226fa20 100644 --- a/adapter/validation/validation.go +++ b/adapter/validation/validation.go @@ -15,7 +15,7 @@ // Package validation for validations // // import ( -// "github.com/astaxie/beego/validation" +// "github.com/beego/beego/v2/validation" // "log" // ) // @@ -50,7 +50,7 @@ import ( "fmt" "regexp" - "github.com/astaxie/beego/core/validation" + "github.com/beego/beego/v2/core/validation" ) // ValidFormer valid interface diff --git a/adapter/validation/validators.go b/adapter/validation/validators.go index 5cd5d286..f4d7db3b 100644 --- a/adapter/validation/validators.go +++ b/adapter/validation/validators.go @@ -17,7 +17,7 @@ package validation import ( "sync" - "github.com/astaxie/beego/core/validation" + "github.com/beego/beego/v2/core/validation" ) // CanSkipFuncs will skip valid if RequiredFirst is true and the struct field's value is empty diff --git a/build_info.go b/build_info.go index 42f42c28..23f74b53 100644 --- a/build_info.go +++ b/build_info.go @@ -28,5 +28,5 @@ var ( const ( // VERSION represent beego web framework version. - VERSION = "2.0.0-alpha" + VERSION = "2.0.0" ) diff --git a/client/cache/README.md b/client/cache/README.md index b467760a..7e65cbbf 100644 --- a/client/cache/README.md +++ b/client/cache/README.md @@ -1,37 +1,34 @@ ## cache -cache is a Go cache manager. It can use many cache adapters. The repo is inspired by `database/sql` . +cache is a Go cache manager. It can use many cache adapters. The repo is inspired by `database/sql` . ## How to install? - go get github.com/astaxie/beego/cache - + go get github.com/beego/beego/v2/cache ## What adapters are supported? As of now this cache support memory, Memcache and Redis. - ## How to use it? First you must import it import ( - "github.com/astaxie/beego/cache" + "github.com/beego/beego/v2/cache" ) Then init a Cache (example with memory adapter) bm, err := cache.NewCache("memory", `{"interval":60}`) -Use it like this: - +Use it like this: + bm.Put("astaxie", 1, 10 * time.Second) bm.Get("astaxie") bm.IsExist("astaxie") bm.Delete("astaxie") - ## Memory adapter Configure memory adapter like this: @@ -40,7 +37,6 @@ Configure memory adapter like this: interval means the gc time. The cache will check at each time interval, whether item has expired. - ## Memcache adapter Memcache adapter use the [gomemcache](http://github.com/bradfitz/gomemcache) client. @@ -49,7 +45,6 @@ Configure like this: {"conn":"127.0.0.1:11211"} - ## Redis adapter Redis adapter use the [redigo](http://github.com/gomodule/redigo) client. diff --git a/client/cache/cache.go b/client/cache/cache.go index ddf246ab..e73a1c1a 100644 --- a/client/cache/cache.go +++ b/client/cache/cache.go @@ -16,7 +16,7 @@ // Usage: // // import( -// "github.com/astaxie/beego/cache" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("memory", `{"interval":60}`) diff --git a/client/cache/cache_test.go b/client/cache/cache_test.go index 6066b72d..c02bba69 100644 --- a/client/cache/cache_test.go +++ b/client/cache/cache_test.go @@ -16,6 +16,7 @@ package cache import ( "context" + "math" "os" "sync" "testing" @@ -46,11 +47,11 @@ func TestCacheIncr(t *testing.T) { } func TestCache(t *testing.T) { - bm, err := NewCache("memory", `{"interval":20}`) + bm, err := NewCache("memory", `{"interval":1}`) if err != nil { t.Error("init err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 5 * time.Second if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } @@ -62,7 +63,7 @@ func TestCache(t *testing.T) { t.Error("get err") } - time.Sleep(30 * time.Second) + time.Sleep(7 * time.Second) if res, _ := bm.IsExist(context.Background(), "astaxie"); res { t.Error("check err") @@ -72,21 +73,13 @@ func TestCache(t *testing.T) { t.Error("set Error", err) } - if err = bm.Incr(context.Background(), "astaxie"); err != nil { - t.Error("Incr Error", err) - } + // test different integer type for incr & decr + testMultiTypeIncrDecr(t, bm, timeoutDuration) - if v, _ := bm.Get(context.Background(), "astaxie"); v.(int) != 2 { - t.Error("get err") - } + // test overflow of incr&decr + testIncrOverFlow(t, bm, timeoutDuration) + testDecrOverFlow(t, bm, timeoutDuration) - if err = bm.Decr(context.Background(), "astaxie"); err != nil { - t.Error("Decr Error", err) - } - - if v, _ := bm.Get(context.Background(), "astaxie"); v.(int) != 1 { - t.Error("get err") - } bm.Delete(context.Background(), "astaxie") if res, _ := bm.IsExist(context.Background(), "astaxie"); res { t.Error("delete err") @@ -120,6 +113,20 @@ func TestCache(t *testing.T) { if vv[1].(string) != "author1" { t.Error("GetMulti ERROR") } + + vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) + if len(vv) != 2 { + t.Error("GetMulti ERROR") + } + if vv[0] != nil { + t.Error("GetMulti ERROR") + } + if vv[1].(string) != "author1" { + t.Error("GetMulti ERROR") + } + if err != nil && err.Error() != "key [astaxie0] error: the key isn't exist" { + t.Error("GetMulti ERROR") + } } func TestFileCache(t *testing.T) { @@ -139,21 +146,13 @@ func TestFileCache(t *testing.T) { t.Error("get err") } - if err = bm.Incr(context.Background(), "astaxie"); err != nil { - t.Error("Incr Error", err) - } + // test different integer type for incr & decr + testMultiTypeIncrDecr(t, bm, timeoutDuration) - if v, _ := bm.Get(context.Background(), "astaxie"); v.(int) != 2 { - t.Error("get err") - } + // test overflow of incr&decr + testIncrOverFlow(t, bm, timeoutDuration) + testDecrOverFlow(t, bm, timeoutDuration) - if err = bm.Decr(context.Background(), "astaxie"); err != nil { - t.Error("Decr Error", err) - } - - if v, _ := bm.Get(context.Background(), "astaxie"); v.(int) != 1 { - t.Error("get err") - } bm.Delete(context.Background(), "astaxie") if res, _ := bm.IsExist(context.Background(), "astaxie"); res { t.Error("delete err") @@ -189,5 +188,99 @@ func TestFileCache(t *testing.T) { t.Error("GetMulti ERROR") } + vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) + if len(vv) != 2 { + t.Error("GetMulti ERROR") + } + if vv[0] != nil { + t.Error("GetMulti ERROR") + } + if vv[1].(string) != "author1" { + t.Error("GetMulti ERROR") + } + if err == nil { + t.Error("GetMulti ERROR") + } + os.RemoveAll("cache") } + +func testMultiTypeIncrDecr(t *testing.T, c Cache, timeout time.Duration) { + testIncrDecr(t, c, 1, 2, timeout) + testIncrDecr(t, c, int32(1), int32(2), timeout) + testIncrDecr(t, c, int64(1), int64(2), timeout) + testIncrDecr(t, c, uint(1), uint(2), timeout) + testIncrDecr(t, c, uint32(1), uint32(2), timeout) + testIncrDecr(t, c, uint64(1), uint64(2), timeout) +} + +func testIncrDecr(t *testing.T, c Cache, beforeIncr interface{}, afterIncr interface{}, timeout time.Duration) { + var err error + ctx := context.Background() + key := "incDecKey" + if err = c.Put(ctx, key, beforeIncr, timeout); err != nil { + t.Error("Get Error", err) + } + + if err = c.Incr(ctx, key); err != nil { + t.Error("Incr Error", err) + } + + if v, _ := c.Get(ctx, key); v != afterIncr { + t.Error("Get Error") + } + + if err = c.Decr(ctx, key); err != nil { + t.Error("Decr Error", err) + } + + if v, _ := c.Get(ctx, key); v != beforeIncr { + t.Error("Get Error") + } + + if err := c.Delete(ctx, key); err != nil { + t.Error("Delete Error") + } +} + +func testIncrOverFlow(t *testing.T, c Cache, timeout time.Duration) { + var err error + ctx := context.Background() + key := "incKey" + + // int64 + if err = c.Put(ctx, key, int64(math.MaxInt64), timeout); err != nil { + t.Error("Put Error: ", err.Error()) + return + } + defer func() { + if err = c.Delete(ctx, key); err != nil { + t.Errorf("Delete error: %s", err.Error()) + } + }() + if err = c.Incr(ctx, key); err == nil { + t.Error("Incr error") + return + } +} + +func testDecrOverFlow(t *testing.T, c Cache, timeout time.Duration) { + var err error + ctx := context.Background() + key := "decKey" + + // int64 + if err = c.Put(ctx, key, int64(math.MinInt64), timeout); err != nil { + t.Error("Put Error: ", err.Error()) + return + } + defer func() { + if err = c.Delete(ctx, key); err != nil { + t.Errorf("Delete error: %s", err.Error()) + } + }() + if err = c.Decr(ctx, key); err == nil { + t.Error("Decr error") + return + } +} diff --git a/client/cache/calc_utils.go b/client/cache/calc_utils.go new file mode 100644 index 00000000..91d0974b --- /dev/null +++ b/client/cache/calc_utils.go @@ -0,0 +1,83 @@ +package cache + +import ( + "fmt" + "math" +) + +func incr(originVal interface{}) (interface{}, error) { + switch val := originVal.(type) { + case int: + tmp := val + 1 + if val > 0 && tmp < 0 { + return nil, fmt.Errorf("increment would overflow") + } + return tmp, nil + case int32: + if val == math.MaxInt32 { + return nil, fmt.Errorf("increment would overflow") + } + return val + 1, nil + case int64: + if val == math.MaxInt64 { + return nil, fmt.Errorf("increment would overflow") + } + return val + 1, nil + case uint: + tmp := val + 1 + if tmp < val { + return nil, fmt.Errorf("increment would overflow") + } + return tmp, nil + case uint32: + if val == math.MaxUint32 { + return nil, fmt.Errorf("increment would overflow") + } + return val + 1, nil + case uint64: + if val == math.MaxUint64 { + return nil, fmt.Errorf("increment would overflow") + } + return val + 1, nil + default: + return nil, fmt.Errorf("item val is not (u)int (u)int32 (u)int64") + } +} + +func decr(originVal interface{}) (interface{}, error) { + switch val := originVal.(type) { + case int: + tmp := val - 1 + if val < 0 && tmp > 0 { + return nil, fmt.Errorf("decrement would overflow") + } + return tmp, nil + case int32: + if val == math.MinInt32 { + return nil, fmt.Errorf("decrement would overflow") + } + return val - 1, nil + case int64: + if val == math.MinInt64 { + return nil, fmt.Errorf("decrement would overflow") + } + return val - 1, nil + case uint: + if val == 0 { + return nil, fmt.Errorf("decrement would overflow") + } + return val - 1, nil + case uint32: + if val == 0 { + return nil, fmt.Errorf("increment would overflow") + } + return val - 1, nil + case uint64: + if val == 0 { + return nil, fmt.Errorf("increment would overflow") + } + return val - 1, nil + default: + return nil, fmt.Errorf("item val is not (u)int (u)int32 (u)int64") + } +} \ No newline at end of file diff --git a/client/cache/calc_utils_test.go b/client/cache/calc_utils_test.go new file mode 100644 index 00000000..b98e71de --- /dev/null +++ b/client/cache/calc_utils_test.go @@ -0,0 +1,241 @@ +package cache + +import ( + "math" + "strconv" + "testing" +) + +func TestIncr(t *testing.T) { + // int + var originVal interface{} = int(1) + var updateVal interface{} = int(2) + val, err := incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(int(1 << (strconv.IntSize - 1) - 1)) + if err == nil { + t.Error("incr failed") + return + } + + // int32 + originVal = int32(1) + updateVal = int32(2) + val, err = incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(int32(math.MaxInt32)) + if err == nil { + t.Error("incr failed") + return + } + + // int64 + originVal = int64(1) + updateVal = int64(2) + val, err = incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(int64(math.MaxInt64)) + if err == nil { + t.Error("incr failed") + return + } + + // uint + originVal = uint(1) + updateVal = uint(2) + val, err = incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(uint(1 << (strconv.IntSize) - 1)) + if err == nil { + t.Error("incr failed") + return + } + + // uint32 + originVal = uint32(1) + updateVal = uint32(2) + val, err = incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(uint32(math.MaxUint32)) + if err == nil { + t.Error("incr failed") + return + } + + // uint64 + originVal = uint64(1) + updateVal = uint64(2) + val, err = incr(originVal) + if err != nil { + t.Errorf("incr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("incr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = incr(uint64(math.MaxUint64)) + if err == nil { + t.Error("incr failed") + return + } + + // other type + _, err = incr("string") + if err == nil { + t.Error("incr failed") + return + } +} + +func TestDecr(t *testing.T) { + // int + var originVal interface{} = int(2) + var updateVal interface{} = int(1) + val, err := decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(int(-1 << (strconv.IntSize - 1))) + if err == nil { + t.Error("decr failed") + return + } + + // int32 + originVal = int32(2) + updateVal = int32(1) + val, err = decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(int32(math.MinInt32)) + if err == nil { + t.Error("decr failed") + return + } + + // int64 + originVal = int64(2) + updateVal = int64(1) + val, err = decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(int64(math.MinInt64)) + if err == nil { + t.Error("decr failed") + return + } + + // uint + originVal = uint(2) + updateVal = uint(1) + val, err = decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(uint(0)) + if err == nil { + t.Error("decr failed") + return + } + + // uint32 + originVal = uint32(2) + updateVal = uint32(1) + val, err = decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(uint32(0)) + if err == nil { + t.Error("decr failed") + return + } + + // uint64 + originVal = uint64(2) + updateVal = uint64(1) + val, err = decr(originVal) + if err != nil { + t.Errorf("decr failed, err: %s", err.Error()) + return + } + if val != updateVal { + t.Errorf("decr failed, expect %v, but %v actually", updateVal, val) + return + } + _, err = decr(uint64(0)) + if err == nil { + t.Error("decr failed") + return + } + + // other type + _, err = decr("string") + if err == nil { + t.Error("decr failed") + return + } +} \ No newline at end of file diff --git a/client/cache/file.go b/client/cache/file.go index dc818258..87e14b6c 100644 --- a/client/cache/file.go +++ b/client/cache/file.go @@ -26,8 +26,8 @@ import ( "io/ioutil" "os" "path/filepath" - "reflect" "strconv" + "strings" "time" "github.com/pkg/errors" @@ -144,17 +144,22 @@ func (fc *FileCache) Get(ctx context.Context, key string) (interface{}, error) { // GetMulti gets values from file cache. // if nonexistent or expired return an empty string. func (fc *FileCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) { - var rc []interface{} - for _, key := range keys { - val, err := fc.Get(context.Background(), key) - if err != nil { - rc = append(rc, err) - } else { - rc = append(rc, val) - } + rc := make([]interface{}, len(keys)) + keysErr := make([]string, 0) + for i, ki := range keys { + val, err := fc.Get(context.Background(), ki) + if err != nil { + keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, err.Error())) + continue + } + rc[i] = val } - return rc, nil + + if len(keysErr) == 0 { + return rc, nil + } + return rc, errors.New(strings.Join(keysErr, "; ")) } // Put value into file cache. @@ -189,28 +194,32 @@ func (fc *FileCache) Delete(ctx context.Context, key string) error { // Incr increases cached int value. // fc value is saved forever unless deleted. func (fc *FileCache) Incr(ctx context.Context, key string) error { - data, _ := fc.Get(context.Background(), key) - var incr int - if reflect.TypeOf(data).Name() != "int" { - incr = 0 - } else { - incr = data.(int) + 1 + data, err := fc.Get(context.Background(), key) + if err != nil { + return err } - fc.Put(context.Background(), key, incr, time.Duration(fc.EmbedExpiry)) - return nil + + val, err := incr(data) + if err != nil { + return err + } + + return fc.Put(context.Background(), key, val, time.Duration(fc.EmbedExpiry)) } // Decr decreases cached int value. func (fc *FileCache) Decr(ctx context.Context, key string) error { - data, _ := fc.Get(context.Background(), key) - var decr int - if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 { - decr = 0 - } else { - decr = data.(int) - 1 + data, err := fc.Get(context.Background(), key) + if err != nil { + return err } - fc.Put(context.Background(), key, decr, time.Duration(fc.EmbedExpiry)) - return nil + + val, err := decr(data) + if err != nil { + return err + } + + return fc.Put(context.Background(), key, val, time.Duration(fc.EmbedExpiry)) } // IsExist checks if value exists. diff --git a/client/cache/memcache/memcache.go b/client/cache/memcache/memcache.go index f3774571..527d08ca 100644 --- a/client/cache/memcache/memcache.go +++ b/client/cache/memcache/memcache.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/cache/memcache" -// "github.com/astaxie/beego/cache" +// _ "github.com/beego/beego/v2/cache/memcache" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`) @@ -33,12 +33,13 @@ import ( "context" "encoding/json" "errors" + "fmt" "strings" "time" "github.com/bradfitz/gomemcache/memcache" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) // Cache Memcache adapter. @@ -68,19 +69,31 @@ func (rc *Cache) Get(ctx context.Context, key string) (interface{}, error) { // GetMulti gets a value from a key in memcache. func (rc *Cache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) { - var rv []interface{} + rv := make([]interface{}, len(keys)) if rc.conn == nil { if err := rc.connectInit(); err != nil { return rv, err } } + mv, err := rc.conn.GetMulti(keys) - if err == nil { - for _, v := range mv { - rv = append(rv, v.Value) - } + if err != nil { + return rv, err } - return rv, err + + keysErr := make([]string, 0) + for i, ki := range keys { + if _, ok := mv[ki]; !ok { + keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "the key isn't exist")) + continue + } + rv[i] = mv[ki].Value + } + + if len(keysErr) == 0 { + return rv, nil + } + return rv, fmt.Errorf(strings.Join(keysErr, "; ")) } // Put puts a value into memcache. diff --git a/client/cache/memcache/memcache_test.go b/client/cache/memcache/memcache_test.go index bc8936a7..083e661c 100644 --- a/client/cache/memcache/memcache_test.go +++ b/client/cache/memcache/memcache_test.go @@ -24,11 +24,10 @@ import ( _ "github.com/bradfitz/gomemcache/memcache" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) func TestMemcacheCache(t *testing.T) { - addr := os.Getenv("MEMCACHE_ADDR") if addr == "" { addr = "127.0.0.1:11211" @@ -114,6 +113,20 @@ func TestMemcacheCache(t *testing.T) { t.Error("GetMulti ERROR") } + vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) + if len(vv) != 2 { + t.Error("GetMulti ERROR") + } + if vv[0] != nil { + t.Error("GetMulti ERROR") + } + if string(vv[1].([]byte)) != "author1" { + t.Error("GetMulti ERROR") + } + if err != nil && err.Error() == "key [astaxie0] error: key isn't exist" { + t.Error("GetMulti ERROR") + } + // test clear all if err = bm.ClearAll(context.Background()); err != nil { t.Error("clear all err") diff --git a/client/cache/memory.go b/client/cache/memory.go index 6f87ec08..850326ad 100644 --- a/client/cache/memory.go +++ b/client/cache/memory.go @@ -18,6 +18,8 @@ import ( "context" "encoding/json" "errors" + "fmt" + "strings" "sync" "time" ) @@ -68,22 +70,28 @@ func (bc *MemoryCache) Get(ctx context.Context, key string) (interface{}, error) } return itm.val, nil } - return nil, nil + return nil, errors.New("the key isn't exist") } // GetMulti gets caches from memory. // If non-existent or expired, return nil. func (bc *MemoryCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) { - var rc []interface{} - for _, name := range keys { - val, err := bc.Get(context.Background(), name) + rc := make([]interface{}, len(keys)) + keysErr := make([]string, 0) + + for i, ki := range keys { + val, err := bc.Get(context.Background(), ki) if err != nil { - rc = append(rc, err) - } else { - rc = append(rc, val) + keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, err.Error())) + continue } + rc[i] = val } - return rc, nil + + if len(keysErr) == 0 { + return rc, nil + } + return rc, errors.New(strings.Join(keysErr, "; ")) } // Put puts cache into memory. @@ -122,22 +130,12 @@ func (bc *MemoryCache) Incr(ctx context.Context, key string) error { if !ok { return errors.New("key not exist") } - switch val := itm.val.(type) { - case int: - itm.val = val + 1 - case int32: - itm.val = val + 1 - case int64: - itm.val = val + 1 - case uint: - itm.val = val + 1 - case uint32: - itm.val = val + 1 - case uint64: - itm.val = val + 1 - default: - return errors.New("item val is not (u)int (u)int32 (u)int64") + + val, err := incr(itm.val) + if err != nil { + return err } + itm.val = val return nil } @@ -149,34 +147,12 @@ func (bc *MemoryCache) Decr(ctx context.Context, key string) error { if !ok { return errors.New("key not exist") } - switch val := itm.val.(type) { - case int: - itm.val = val - 1 - case int64: - itm.val = val - 1 - case int32: - itm.val = val - 1 - case uint: - if val > 0 { - itm.val = val - 1 - } else { - return errors.New("item val is less than 0") - } - case uint32: - if val > 0 { - itm.val = val - 1 - } else { - return errors.New("item val is less than 0") - } - case uint64: - if val > 0 { - itm.val = val - 1 - } else { - return errors.New("item val is less than 0") - } - default: - return errors.New("item val is not int int64 int32") + + val, err := decr(itm.val) + if err != nil { + return err } + itm.val = val return nil } diff --git a/client/cache/redis/redis.go b/client/cache/redis/redis.go index 34059835..dcf0cd5a 100644 --- a/client/cache/redis/redis.go +++ b/client/cache/redis/redis.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/cache/redis" -// "github.com/astaxie/beego/cache" +// _ "github.com/beego/beego/v2/cache/redis" +// "github.com/beego/beego/v2/cache" // ) // // bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) @@ -40,7 +40,7 @@ import ( "github.com/gomodule/redigo/redis" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) var ( diff --git a/client/cache/redis/redis_test.go b/client/cache/redis/redis_test.go index f82b2c40..3344bc34 100644 --- a/client/cache/redis/redis_test.go +++ b/client/cache/redis/redis_test.go @@ -24,7 +24,7 @@ import ( "github.com/gomodule/redigo/redis" "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) func TestRedisCache(t *testing.T) { @@ -113,6 +113,14 @@ func TestRedisCache(t *testing.T) { t.Error("GetMulti ERROR") } + vv, _ = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) + if vv[0] != nil { + t.Error("GetMulti ERROR") + } + if v, _ := redis.String(vv[1], nil); v != "author1" { + t.Error("GetMulti ERROR") + } + // test clear all if err = bm.ClearAll(context.Background()); err != nil { t.Error("clear all err") diff --git a/client/cache/ssdb/ssdb.go b/client/cache/ssdb/ssdb.go index 1acee861..93fa9feb 100644 --- a/client/cache/ssdb/ssdb.go +++ b/client/cache/ssdb/ssdb.go @@ -4,13 +4,14 @@ import ( "context" "encoding/json" "errors" + "fmt" "strconv" "strings" "time" "github.com/ssdb/gossdb/ssdb" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) // Cache SSDB adapter @@ -19,7 +20,7 @@ type Cache struct { conninfo []string } -//NewSsdbCache creates new ssdb adapter. +// NewSsdbCache creates new ssdb adapter. func NewSsdbCache() cache.Cache { return &Cache{} } @@ -28,36 +29,50 @@ func NewSsdbCache() cache.Cache { func (rc *Cache) Get(ctx context.Context, key string) (interface{}, error) { if rc.conn == nil { if err := rc.connectInit(); err != nil { - return nil, nil + return nil, err } } value, err := rc.conn.Get(key) if err == nil { return value, nil } - return nil, nil + return nil, err } // GetMulti gets one or keys values from ssdb. func (rc *Cache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) { size := len(keys) - var values []interface{} + values := make([]interface{}, size) if rc.conn == nil { if err := rc.connectInit(); err != nil { return values, err } } + res, err := rc.conn.Do("multi_get", keys) + if err != nil { + return values, err + } + resSize := len(res) - if err == nil { - for i := 1; i < resSize; i += 2 { - values = append(values, res[i+1]) + keyIdx := make(map[string]int) + for i := 1; i < resSize; i += 2 { + keyIdx[res[i]] = i + } + + keysErr := make([]string, 0) + for i, ki := range keys { + if _, ok := keyIdx[ki]; !ok { + keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "the key isn't exist")) + continue } - return values, nil + values[i] = res[keyIdx[ki]+1] } - for i := 0; i < size; i++ { - values = append(values, err) + + if len(keysErr) != 0 { + return values, fmt.Errorf(strings.Join(keysErr, "; ")) } + return values, nil } diff --git a/client/cache/ssdb/ssdb_test.go b/client/cache/ssdb/ssdb_test.go index cebaa975..8ac1efd6 100644 --- a/client/cache/ssdb/ssdb_test.go +++ b/client/cache/ssdb/ssdb_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/astaxie/beego/client/cache" + "github.com/beego/beego/v2/client/cache" ) func TestSsdbcacheCache(t *testing.T) { @@ -106,6 +106,20 @@ func TestSsdbcacheCache(t *testing.T) { t.Error("getmulti error") } + vv, err = ssdb.GetMulti(context.Background(), []string{"ssdb", "ssdb11"}) + if len(vv) != 2 { + t.Error("getmulti error") + } + if vv[0].(string) != "ssdb" { + t.Error("getmulti error") + } + if vv[1] != nil { + t.Error("getmulti error") + } + if err != nil && err.Error() != "key [ssdb11] error: the key isn't exist" { + t.Error("getmulti error") + } + // test clear all done if err = ssdb.ClearAll(context.Background()); err != nil { t.Error("clear all err") diff --git a/client/httplib/README.md b/client/httplib/README.md index 97df8e6b..90a6c505 100644 --- a/client/httplib/README.md +++ b/client/httplib/README.md @@ -1,20 +1,23 @@ # httplib + httplib is an libs help you to curl remote url. # How to use? ## GET + you can use Get to crawl data. - import "github.com/astaxie/beego/httplib" + import "github.com/beego/beego/v2/httplib" str, err := httplib.Get("http://beego.me/").String() if err != nil { // error } fmt.Println(str) - + ## POST + POST data to remote url req := httplib.Post("http://beego.me/") @@ -40,13 +43,12 @@ Example: // POST httplib.Post("http://beego.me/").SetTimeout(100 * time.Second, 30 * time.Second) - ## Debug If you want to debug the request info, set the debug on httplib.Get("http://beego.me/").Debug(true) - + ## Set HTTP Basic Auth str, err := Get("http://beego.me/").SetBasicAuth("user", "passwd").String() @@ -54,21 +56,21 @@ If you want to debug the request info, set the debug on // error } fmt.Println(str) - + ## Set HTTPS If request url is https, You can set the client support TSL: httplib.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) - -More info about the `tls.Config` please visit http://golang.org/pkg/crypto/tls/#Config + +More info about the `tls.Config` please visit http://golang.org/pkg/crypto/tls/#Config ## Set HTTP Version some servers need to specify the protocol version of HTTP httplib.Get("http://beego.me/").SetProtocolVersion("HTTP/1.1") - + ## Set Cookie some http request need setcookie. So set it like this: @@ -91,7 +93,6 @@ httplib support mutil file upload, use `req.PostFile()` } fmt.Println(str) - See godoc for further documentation and examples. -* [godoc.org/github.com/astaxie/beego/httplib](https://godoc.org/github.com/astaxie/beego/httplib) +* [godoc.org/github.com/beego/beego/v2/httplib](https://godoc.org/github.com/beego/beego/v2/httplib) diff --git a/client/httplib/filter/opentracing/filter.go b/client/httplib/filter/opentracing/filter.go index 765a82a9..a46effc8 100644 --- a/client/httplib/filter/opentracing/filter.go +++ b/client/httplib/filter/opentracing/filter.go @@ -18,13 +18,17 @@ import ( "context" "net/http" - "github.com/astaxie/beego/client/httplib" logKit "github.com/go-kit/kit/log" opentracingKit "github.com/go-kit/kit/tracing/opentracing" "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go/log" + + "github.com/beego/beego/v2/client/httplib" ) type FilterChainBuilder struct { + // TagURL true will tag span with url + TagURL bool // CustomSpanFunc users are able to custom their span CustomSpanFunc func(span opentracing.Span, ctx context.Context, req *httplib.BeegoHTTPRequest, resp *http.Response, err error) @@ -49,13 +53,19 @@ func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filt } span.SetTag("http.method", method) span.SetTag("peer.hostname", req.GetRequest().URL.Host) - span.SetTag("http.url", req.GetRequest().URL.String()) + span.SetTag("http.scheme", req.GetRequest().URL.Scheme) span.SetTag("span.kind", "client") span.SetTag("component", "beego") + + if builder.TagURL { + span.SetTag("http.url", req.GetRequest().URL.String()) + } + span.LogFields(log.String("http.url", req.GetRequest().URL.String())) + if err != nil { span.SetTag("error", true) - span.SetTag("message", err.Error()) + span.LogFields(log.String("message", err.Error())) } else if resp != nil && !(resp.StatusCode < 300 && resp.StatusCode >= 200) { span.SetTag("error", true) } diff --git a/client/httplib/filter/opentracing/filter_test.go b/client/httplib/filter/opentracing/filter_test.go index 7281f93f..e1ae48c5 100644 --- a/client/httplib/filter/opentracing/filter_test.go +++ b/client/httplib/filter/opentracing/filter_test.go @@ -23,7 +23,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/client/httplib" + "github.com/beego/beego/v2/client/httplib" ) func TestFilterChainBuilder_FilterChain(t *testing.T) { @@ -33,7 +33,9 @@ func TestFilterChainBuilder_FilterChain(t *testing.T) { StatusCode: 404, }, errors.New("hello") } - builder := &FilterChainBuilder{} + builder := &FilterChainBuilder{ + TagURL: true, + } filter := builder.FilterChain(next) req := httplib.Get("https://github.com/notifications?query=repo%3Aastaxie%2Fbeego") resp, err := filter(context.Background(), req) diff --git a/client/httplib/filter/prometheus/filter.go b/client/httplib/filter/prometheus/filter.go index ce88b70e..3d5acf12 100644 --- a/client/httplib/filter/prometheus/filter.go +++ b/client/httplib/filter/prometheus/filter.go @@ -22,7 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/astaxie/beego/client/httplib" + "github.com/beego/beego/v2/client/httplib" ) type FilterChainBuilder struct { @@ -43,7 +43,7 @@ func (builder *FilterChainBuilder) FilterChain(next httplib.Filter) httplib.Filt "appname": builder.AppName, }, Help: "The statics info for remote http requests", - }, []string{"proto", "scheme", "method", "host", "path", "status", "duration", "isError"}) + }, []string{"proto", "scheme", "method", "host", "path", "status", "isError"}) return func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) { startTime := time.Now() @@ -73,5 +73,5 @@ func (builder *FilterChainBuilder) report(startTime time.Time, endTime time.Time dur := int(endTime.Sub(startTime) / time.Millisecond) builder.summaryVec.WithLabelValues(proto, scheme, method, host, path, - strconv.Itoa(status), strconv.Itoa(dur), strconv.FormatBool(err == nil)) + strconv.Itoa(status), strconv.FormatBool(err != nil)).Observe(float64(dur)) } diff --git a/client/httplib/filter/prometheus/filter_test.go b/client/httplib/filter/prometheus/filter_test.go index 46edc3d2..1e7935d0 100644 --- a/client/httplib/filter/prometheus/filter_test.go +++ b/client/httplib/filter/prometheus/filter_test.go @@ -22,7 +22,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/client/httplib" + "github.com/beego/beego/v2/client/httplib" ) func TestFilterChainBuilder_FilterChain(t *testing.T) { diff --git a/client/httplib/http_response.go b/client/httplib/http_response.go new file mode 100644 index 00000000..89930cb1 --- /dev/null +++ b/client/httplib/http_response.go @@ -0,0 +1,39 @@ +// Copyright 2020 beego +// +// 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 httplib + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" +) + +// NewHttpResponseWithJsonBody will try to convert the data to json format +// usually you only use this when you want to mock http Response +func NewHttpResponseWithJsonBody(data interface{}) *http.Response { + var body []byte + if str, ok := data.(string); ok { + body = []byte(str) + } else if bts, ok := data.([]byte); ok { + body = bts + } else { + body, _ = json.Marshal(data) + } + return &http.Response{ + ContentLength: int64(len(body)), + Body: ioutil.NopCloser(bytes.NewReader(body)), + } +} diff --git a/client/httplib/http_response_test.go b/client/httplib/http_response_test.go new file mode 100644 index 00000000..90db3fca --- /dev/null +++ b/client/httplib/http_response_test.go @@ -0,0 +1,36 @@ +// Copyright 2020 beego +// +// 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 httplib + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + + +func TestNewHttpResponseWithJsonBody(t *testing.T) { + // string + resp := NewHttpResponseWithJsonBody("{}") + assert.Equal(t, int64(2), resp.ContentLength) + + resp = NewHttpResponseWithJsonBody([]byte("{}")) + assert.Equal(t, int64(2), resp.ContentLength) + + resp = NewHttpResponseWithJsonBody(&user{ + Name: "Tom", + }) + assert.True(t, resp.ContentLength > 0) +} diff --git a/client/httplib/httplib.go b/client/httplib/httplib.go index f8ab80a1..f89c6fa2 100644 --- a/client/httplib/httplib.go +++ b/client/httplib/httplib.go @@ -15,7 +15,7 @@ // Package httplib is used as http.Client // Usage: // -// import "github.com/astaxie/beego/httplib" +// import "github.com/beego/beego/v2/httplib" // // b := httplib.Post("http://beego.me/") // b.Param("username","astaxie") @@ -44,48 +44,22 @@ import ( "mime/multipart" "net" "net/http" - "net/http/cookiejar" "net/http/httputil" "net/url" "os" "path" "strings" - "sync" "time" "gopkg.in/yaml.v2" ) -var defaultSetting = BeegoHTTPSettings{ - UserAgent: "beegoServer", - ConnectTimeout: 60 * time.Second, - ReadWriteTimeout: 60 * time.Second, - Gzip: true, - DumpBody: true, -} - -var defaultCookieJar http.CookieJar -var settingMutex sync.Mutex // it will be the last filter and execute request.Do var doRequestFilter = func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) { return req.doRequest(ctx) } -// createDefaultCookie creates a global cookiejar to store cookies. -func createDefaultCookie() { - settingMutex.Lock() - defer settingMutex.Unlock() - defaultCookieJar, _ = cookiejar.New(nil) -} - -// SetDefaultSetting overwrites default settings -func SetDefaultSetting(setting BeegoHTTPSettings) { - settingMutex.Lock() - defer settingMutex.Unlock() - defaultSetting = setting -} - // NewBeegoRequest returns *BeegoHttpRequest with specific method func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest { var resp http.Response @@ -136,23 +110,7 @@ func Head(url string) *BeegoHTTPRequest { return NewBeegoRequest(url, "HEAD") } -// BeegoHTTPSettings is the http.Client setting -type BeegoHTTPSettings struct { - ShowDebug bool - UserAgent string - ConnectTimeout time.Duration - ReadWriteTimeout time.Duration - TLSClientConfig *tls.Config - Proxy func(*http.Request) (*url.URL, error) - Transport http.RoundTripper - CheckRedirect func(req *http.Request, via []*http.Request) error - EnableCookie bool - Gzip bool - DumpBody bool - Retries int // if set to -1 means will retry forever - RetryDelay time.Duration - FilterChains []FilterChain -} + // BeegoHTTPRequest provides more useful methods than http.Request for requesting a url. type BeegoHTTPRequest struct { @@ -338,10 +296,16 @@ func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest { case string: bf := bytes.NewBufferString(t) b.req.Body = ioutil.NopCloser(bf) + b.req.GetBody = func() (io.ReadCloser, error) { + return ioutil.NopCloser(bf), nil + } b.req.ContentLength = int64(len(t)) case []byte: bf := bytes.NewBuffer(t) b.req.Body = ioutil.NopCloser(bf) + b.req.GetBody = func() (io.ReadCloser, error) { + return ioutil.NopCloser(bf), nil + } b.req.ContentLength = int64(len(t)) } return b @@ -355,6 +319,9 @@ func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) { return b, err } b.req.Body = ioutil.NopCloser(bytes.NewReader(byts)) + b.req.GetBody = func() (io.ReadCloser, error) { + return ioutil.NopCloser(bytes.NewReader(byts)), nil + } b.req.ContentLength = int64(len(byts)) b.req.Header.Set("Content-Type", "application/xml") } @@ -553,7 +520,7 @@ func (b *BeegoHTTPRequest) doRequest(ctx context.Context) (resp *http.Response, // retries default value is 0, it will run once. // retries equal to -1, it will run forever until success // retries is setted, it will retries fixed times. - // Sleeps for a 400ms inbetween calls to reduce spam + // Sleeps for a 400ms between calls to reduce spam for i := 0; b.setting.Retries == -1 || i <= b.setting.Retries; i++ { resp, err = client.Do(b.req) if err == nil { diff --git a/client/httplib/httplib_test.go b/client/httplib/httplib_test.go index f6be8571..1763b1b5 100644 --- a/client/httplib/httplib_test.go +++ b/client/httplib/httplib_test.go @@ -15,6 +15,7 @@ package httplib import ( + "context" "errors" "io/ioutil" "net" @@ -23,6 +24,8 @@ import ( "strings" "testing" "time" + + "github.com/stretchr/testify/assert" ) func TestResponse(t *testing.T) { @@ -98,7 +101,7 @@ func TestSimplePost(t *testing.T) { } } -//func TestPostFile(t *testing.T) { +// func TestPostFile(t *testing.T) { // v := "smallfish" // req := Post("http://httpbin.org/post") // req.Debug(true) @@ -115,7 +118,7 @@ func TestSimplePost(t *testing.T) { // if n == -1 { // t.Fatal(v + " not found in post") // } -//} +// } func TestSimplePut(t *testing.T) { str, err := Put("http://httpbin.org/put").String() @@ -284,3 +287,94 @@ func TestHeader(t *testing.T) { } t.Log(str) } + +// TestAddFilter make sure that AddFilters only work for the specific request +func TestAddFilter(t *testing.T) { + req := Get("http://beego.me") + req.AddFilters(func(next Filter) Filter { + return func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) { + return next(ctx, req) + } + }) + + r := Get("http://beego.me") + assert.Equal(t, 1, len(req.setting.FilterChains)-len(r.setting.FilterChains)) +} + +func TestHead(t *testing.T) { + req := Head("http://beego.me") + assert.NotNil(t, req) + assert.Equal(t, "HEAD", req.req.Method) +} + +func TestDelete(t *testing.T) { + req := Delete("http://beego.me") + assert.NotNil(t, req) + assert.Equal(t, "DELETE", req.req.Method) +} + +func TestPost(t *testing.T) { + req := Post("http://beego.me") + assert.NotNil(t, req) + assert.Equal(t, "POST", req.req.Method) +} + +func TestNewBeegoRequest(t *testing.T) { + req := NewBeegoRequest("http://beego.me", "GET") + assert.NotNil(t, req) + assert.Equal(t, "GET", req.req.Method) +} + +func TestPut(t *testing.T) { + req := Put("http://beego.me") + assert.NotNil(t, req) + assert.Equal(t, "PUT", req.req.Method) +} + +func TestBeegoHTTPRequest_Header(t *testing.T) { + req := Post("http://beego.me") + key, value := "test-header", "test-header-value" + req.Header(key, value) + assert.Equal(t, value, req.req.Header.Get(key)) +} + +func TestBeegoHTTPRequest_SetHost(t *testing.T) { + req := Post("http://beego.me") + host := "test-hose" + req.SetHost(host) + assert.Equal(t, host, req.req.Host) +} + +func TestBeegoHTTPRequest_Param(t *testing.T) { + req := Post("http://beego.me") + key, value := "test-param", "test-param-value" + req.Param(key, value) + assert.Equal(t, value, req.params[key][0]) + + value1 := "test-param-value-1" + req.Param(key, value1) + assert.Equal(t, value1, req.params[key][1]) +} + +func TestBeegoHTTPRequest_Body(t *testing.T) { + req := Post("http://beego.me") + body := `hello, world` + req.Body([]byte(body)) + assert.Equal(t, int64(len(body)), req.req.ContentLength) + assert.NotNil(t, req.req.GetBody) +} + + +type user struct { + Name string `xml:"name"` +} +func TestBeegoHTTPRequest_XMLBody(t *testing.T) { + req := Post("http://beego.me") + body := &user{ + Name: "Tom", + } + _, err := req.XMLBody(body) + assert.True(t, req.req.ContentLength > 0) + assert.Nil(t, err) + assert.NotNil(t, req.req.GetBody) +} \ No newline at end of file diff --git a/client/httplib/mock/mock.go b/client/httplib/mock/mock.go new file mode 100644 index 00000000..7640e454 --- /dev/null +++ b/client/httplib/mock/mock.go @@ -0,0 +1,80 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "context" + "net/http" + + "github.com/beego/beego/v2/client/httplib" + "github.com/beego/beego/v2/core/logs" +) + +const mockCtxKey = "beego-httplib-mock" + +func init() { + InitMockSetting() +} + +type Stub interface { + Mock(cond RequestCondition, resp *http.Response, err error) + Clear() + MockByPath(path string, resp *http.Response, err error) +} + +var mockFilter = &MockResponseFilter{} + +func InitMockSetting() { + httplib.AddDefaultFilter(mockFilter.FilterChain) +} + +func StartMock() Stub { + return mockFilter +} + +func CtxWithMock(ctx context.Context, mock... *Mock) context.Context { + return context.WithValue(ctx, mockCtxKey, mock) +} + +func mockFromCtx(ctx context.Context) []*Mock { + ms := ctx.Value(mockCtxKey) + if ms != nil { + if res, ok := ms.([]*Mock); ok { + return res + } + logs.Error("mockCtxKey found in context, but value is not type []*Mock") + } + return nil +} + +type Mock struct { + cond RequestCondition + resp *http.Response + err error +} + +func NewMockByPath(path string, resp *http.Response, err error) *Mock { + return NewMock(NewSimpleCondition(path), resp, err) +} + +func NewMock(con RequestCondition, resp *http.Response, err error) *Mock { + return &Mock{ + cond: con, + resp: resp, + err: err, + } +} + + diff --git a/client/httplib/mock/mock_condition.go b/client/httplib/mock/mock_condition.go new file mode 100644 index 00000000..639b45a3 --- /dev/null +++ b/client/httplib/mock/mock_condition.go @@ -0,0 +1,177 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "context" + "encoding/json" + "net/textproto" + "regexp" + + "github.com/beego/beego/v2/client/httplib" +) + +type RequestCondition interface { + Match(ctx context.Context, req *httplib.BeegoHTTPRequest) bool +} + +// reqCondition create condition +// - path: same path +// - pathReg: request path match pathReg +// - method: same method +// - Query parameters (key, value) +// - header (key, value) +// - Body json format, contains specific (key, value). +type SimpleCondition struct { + pathReg string + path string + method string + query map[string]string + header map[string]string + body map[string]interface{} +} + +func NewSimpleCondition(path string, opts ...simpleConditionOption) *SimpleCondition { + sc := &SimpleCondition{ + path: path, + query: make(map[string]string), + header: make(map[string]string), + body: map[string]interface{}{}, + } + for _, o := range opts { + o(sc) + } + return sc +} + +func (sc *SimpleCondition) Match(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + res := true + if len(sc.path) > 0 { + res = sc.matchPath(ctx, req) + } else if len(sc.pathReg) > 0 { + res = sc.matchPathReg(ctx, req) + } else { + return false + } + return res && + sc.matchMethod(ctx, req) && + sc.matchQuery(ctx, req) && + sc.matchHeader(ctx, req) && + sc.matchBodyFields(ctx, req) +} + +func (sc *SimpleCondition) matchPath(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + path := req.GetRequest().URL.Path + return path == sc.path +} + +func (sc *SimpleCondition) matchPathReg(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + path := req.GetRequest().URL.Path + if b, err := regexp.Match(sc.pathReg, []byte(path)); err == nil { + return b + } + return false +} + +func (sc *SimpleCondition) matchQuery(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + qs := req.GetRequest().URL.Query() + for k, v := range sc.query { + if uv, ok := qs[k]; !ok || uv[0] != v { + return false + } + } + return true +} + +func (sc *SimpleCondition) matchHeader(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + headers := req.GetRequest().Header + for k, v := range sc.header { + if uv, ok := headers[k]; !ok || uv[0] != v { + return false + } + } + return true +} + +func (sc *SimpleCondition) matchBodyFields(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + if len(sc.body) == 0 { + return true + } + getBody := req.GetRequest().GetBody + body, err := getBody() + if err != nil { + return false + } + bytes := make([]byte, req.GetRequest().ContentLength) + _, err = body.Read(bytes) + if err != nil { + return false + } + + + m := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &m) + + if err != nil { + return false + } + + for k, v := range sc.body { + if uv, ok := m[k]; !ok || uv != v { + return false + } + } + return true +} + +func (sc *SimpleCondition) matchMethod(ctx context.Context, req *httplib.BeegoHTTPRequest) bool { + if len(sc.method) > 0 { + return sc.method == req.GetRequest().Method + } + return true +} + +type simpleConditionOption func(sc *SimpleCondition) + +func WithPathReg(pathReg string) simpleConditionOption { + return func(sc *SimpleCondition) { + sc.pathReg = pathReg + } +} + +func WithQuery(key, value string) simpleConditionOption { + return func(sc *SimpleCondition) { + sc.query[key] = value + } +} + +func WithHeader(key, value string) simpleConditionOption { + return func(sc *SimpleCondition) { + sc.header[textproto.CanonicalMIMEHeaderKey(key)] = value + } +} + +func WithJsonBodyFields(field string, value interface{}) simpleConditionOption { + return func(sc *SimpleCondition) { + sc.body[field] = value + } +} + +func WithMethod(method string) simpleConditionOption { + return func(sc *SimpleCondition) { + sc.method = method + } +} diff --git a/client/httplib/mock/mock_condition_test.go b/client/httplib/mock/mock_condition_test.go new file mode 100644 index 00000000..4fc6d377 --- /dev/null +++ b/client/httplib/mock/mock_condition_test.go @@ -0,0 +1,124 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/beego/beego/v2/client/httplib" +) + +func init() { + +} + +func TestSimpleCondition_MatchPath(t *testing.T) { + sc := NewSimpleCondition("/abc/s") + res := sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s")) + assert.True(t, res) +} + +func TestSimpleCondition_MatchQuery(t *testing.T) { + k, v := "my-key", "my-value" + sc := NewSimpleCondition("/abc/s") + res := sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s?my-key=my-value")) + assert.True(t, res) + + sc = NewSimpleCondition("/abc/s", WithQuery(k, v)) + res = sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s?my-key=my-value")) + assert.True(t, res) + + res = sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s?my-key=my-valuesss")) + assert.False(t, res) + + res = sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s?my-key-a=my-value")) + assert.False(t, res) + + res = sc.Match(context.Background(), httplib.Get("http://localhost:8080/abc/s?my-key=my-value&abc=hello")) + assert.True(t, res) +} + +func TestSimpleCondition_MatchHeader(t *testing.T) { + k, v := "my-header", "my-header-value" + sc := NewSimpleCondition("/abc/s") + req := httplib.Get("http://localhost:8080/abc/s") + assert.True(t, sc.Match(context.Background(), req)) + + req = httplib.Get("http://localhost:8080/abc/s") + req.Header(k, v) + assert.True(t, sc.Match(context.Background(), req)) + + sc = NewSimpleCondition("/abc/s", WithHeader(k, v)) + req.Header(k, v) + assert.True(t, sc.Match(context.Background(), req)) + + req.Header(k, "invalid") + assert.False(t, sc.Match(context.Background(), req)) +} + +func TestSimpleCondition_MatchBodyField(t *testing.T) { + + sc := NewSimpleCondition("/abc/s") + req := httplib.Post("http://localhost:8080/abc/s") + + assert.True(t, sc.Match(context.Background(), req)) + + req.Body(`{ + "body-field": 123 +}`) + assert.True(t, sc.Match(context.Background(), req)) + + k := "body-field" + v := float64(123) + sc = NewSimpleCondition("/abc/s", WithJsonBodyFields(k, v)) + assert.True(t, sc.Match(context.Background(), req)) + + sc = NewSimpleCondition("/abc/s", WithJsonBodyFields(k, v)) + req.Body(`{ + "body-field": abc +}`) + assert.False(t, sc.Match(context.Background(), req)) + + sc = NewSimpleCondition("/abc/s", WithJsonBodyFields("body-field", "abc")) + req.Body(`{ + "body-field": "abc" +}`) + assert.True(t, sc.Match(context.Background(), req)) +} + +func TestSimpleCondition_Match(t *testing.T) { + sc := NewSimpleCondition("/abc/s") + req := httplib.Post("http://localhost:8080/abc/s") + + assert.True(t, sc.Match(context.Background(), req)) + + sc = NewSimpleCondition("/abc/s", WithMethod("POST")) + assert.True(t, sc.Match(context.Background(), req)) + + sc = NewSimpleCondition("/abc/s", WithMethod("GET")) + assert.False(t, sc.Match(context.Background(), req)) +} + +func TestSimpleCondition_MatchPathReg(t *testing.T) { + sc := NewSimpleCondition("", WithPathReg(`\/abc\/.*`)) + req := httplib.Post("http://localhost:8080/abc/s") + assert.True(t, sc.Match(context.Background(), req)) + + req = httplib.Post("http://localhost:8080/abcd/s") + assert.False(t, sc.Match(context.Background(), req)) +} diff --git a/client/httplib/mock/mock_filter.go b/client/httplib/mock/mock_filter.go new file mode 100644 index 00000000..225d65f3 --- /dev/null +++ b/client/httplib/mock/mock_filter.go @@ -0,0 +1,61 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "context" + "net/http" + + "github.com/beego/beego/v2/client/httplib" +) + +// MockResponse will return mock response if find any suitable mock data +// if you want to test your code using httplib, you need this. +type MockResponseFilter struct { + ms []*Mock +} + +func NewMockResponseFilter() *MockResponseFilter { + return &MockResponseFilter{ + ms: make([]*Mock, 0, 1), + } +} + +func (m *MockResponseFilter) FilterChain(next httplib.Filter) httplib.Filter { + return func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) { + ms := mockFromCtx(ctx) + ms = append(ms, m.ms...) + for _, mock := range ms { + if mock.cond.Match(ctx, req) { + return mock.resp, mock.err + } + } + return next(ctx, req) + } +} + +func (m *MockResponseFilter) MockByPath(path string, resp *http.Response, err error) { + m.Mock(NewSimpleCondition(path), resp, err) +} + +func (m *MockResponseFilter) Clear() { + m.ms = make([]*Mock, 0, 1) +} + +// Mock add mock data +// If the cond.Match(...) = true, the resp and err will be returned +func (m *MockResponseFilter) Mock(cond RequestCondition, resp *http.Response, err error) { + m.ms = append(m.ms, NewMock(cond, resp, err)) +} diff --git a/client/httplib/mock/mock_filter_test.go b/client/httplib/mock/mock_filter_test.go new file mode 100644 index 00000000..b27e772e --- /dev/null +++ b/client/httplib/mock/mock_filter_test.go @@ -0,0 +1,63 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/beego/beego/v2/client/httplib" +) + +func TestMockResponseFilter_FilterChain(t *testing.T) { + req := httplib.Get("http://localhost:8080/abc/s") + ft := NewMockResponseFilter() + + expectedResp := httplib.NewHttpResponseWithJsonBody(`{}`) + expectedErr := errors.New("expected error") + ft.Mock(NewSimpleCondition("/abc/s"), expectedResp, expectedErr) + + req.AddFilters(ft.FilterChain) + + resp, err := req.DoRequest() + assert.Equal(t, expectedErr, err) + assert.Equal(t, expectedResp, resp) + + req = httplib.Get("http://localhost:8080/abcd/s") + req.AddFilters(ft.FilterChain) + + resp, err = req.DoRequest() + assert.NotEqual(t, expectedErr, err) + assert.NotEqual(t, expectedResp, resp) + + req = httplib.Get("http://localhost:8080/abc/s") + req.AddFilters(ft.FilterChain) + expectedResp1 := httplib.NewHttpResponseWithJsonBody(map[string]string{}) + expectedErr1 := errors.New("expected error") + ft.Mock(NewSimpleCondition("/abc/abs/bbc"), expectedResp1, expectedErr1) + + resp, err = req.DoRequest() + assert.Equal(t, expectedErr, err) + assert.Equal(t, expectedResp, resp) + + req = httplib.Get("http://localhost:8080/abc/abs/bbc") + req.AddFilters(ft.FilterChain) + ft.Mock(NewSimpleCondition("/abc/abs/bbc"), expectedResp1, expectedErr1) + resp, err = req.DoRequest() + assert.Equal(t, expectedErr1, err) + assert.Equal(t, expectedResp1, resp) +} diff --git a/client/httplib/mock/mock_test.go b/client/httplib/mock/mock_test.go new file mode 100644 index 00000000..e73e8a6a --- /dev/null +++ b/client/httplib/mock/mock_test.go @@ -0,0 +1,77 @@ +// Copyright 2020 beego +// +// 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 mock + +import ( + "context" + "errors" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/beego/beego/v2/client/httplib" +) + +func TestStartMock(t *testing.T) { + + // httplib.defaultSetting.FilterChains = []httplib.FilterChain{mockFilter.FilterChain} + + stub := StartMock() + // defer stub.Clear() + + expectedResp := httplib.NewHttpResponseWithJsonBody([]byte(`{}`)) + expectedErr := errors.New("expected err") + + stub.Mock(NewSimpleCondition("/abc"), expectedResp, expectedErr) + + resp, err := OriginalCodeUsingHttplib() + + assert.Equal(t, expectedErr, err) + assert.Equal(t, expectedResp, resp) + +} + +// TestStartMock_Isolation Test StartMock that +// mock only work for this request +func TestStartMock_Isolation(t *testing.T) { + // httplib.defaultSetting.FilterChains = []httplib.FilterChain{mockFilter.FilterChain} + // setup global stub + stub := StartMock() + globalMockResp := httplib.NewHttpResponseWithJsonBody([]byte(`{}`)) + globalMockErr := errors.New("expected err") + stub.Mock(NewSimpleCondition("/abc"), globalMockResp, globalMockErr) + + expectedResp := httplib.NewHttpResponseWithJsonBody(struct { + A string `json:"a"` + }{ + A: "aaa", + }) + expectedErr := errors.New("expected err aa") + m := NewMockByPath("/abc", expectedResp, expectedErr) + ctx := CtxWithMock(context.Background(), m) + + resp, err := OriginnalCodeUsingHttplibPassCtx(ctx) + assert.Equal(t, expectedErr, err) + assert.Equal(t, expectedResp, resp) +} + +func OriginnalCodeUsingHttplibPassCtx(ctx context.Context) (*http.Response, error) { + return httplib.Get("http://localhost:7777/abc").DoRequestWithCtx(ctx) +} + +func OriginalCodeUsingHttplib() (*http.Response, error){ + return httplib.Get("http://localhost:7777/abc").DoRequest() +} diff --git a/client/httplib/setting.go b/client/httplib/setting.go new file mode 100644 index 00000000..c8d049e0 --- /dev/null +++ b/client/httplib/setting.go @@ -0,0 +1,81 @@ +// Copyright 2020 beego +// +// 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 httplib + +import ( + "crypto/tls" + "net/http" + "net/http/cookiejar" + "net/url" + "sync" + "time" +) + +// BeegoHTTPSettings is the http.Client setting +type BeegoHTTPSettings struct { + ShowDebug bool + UserAgent string + ConnectTimeout time.Duration + ReadWriteTimeout time.Duration + TLSClientConfig *tls.Config + Proxy func(*http.Request) (*url.URL, error) + Transport http.RoundTripper + CheckRedirect func(req *http.Request, via []*http.Request) error + EnableCookie bool + Gzip bool + DumpBody bool + Retries int // if set to -1 means will retry forever + RetryDelay time.Duration + FilterChains []FilterChain +} + +// createDefaultCookie creates a global cookiejar to store cookies. +func createDefaultCookie() { + settingMutex.Lock() + defer settingMutex.Unlock() + defaultCookieJar, _ = cookiejar.New(nil) +} + +// SetDefaultSetting overwrites default settings +// Keep in mind that when you invoke the SetDefaultSetting +// some methods invoked before SetDefaultSetting +func SetDefaultSetting(setting BeegoHTTPSettings) { + settingMutex.Lock() + defer settingMutex.Unlock() + defaultSetting = setting +} + +var defaultSetting = BeegoHTTPSettings{ + UserAgent: "beegoServer", + ConnectTimeout: 60 * time.Second, + ReadWriteTimeout: 60 * time.Second, + Gzip: true, + DumpBody: true, + FilterChains: make([]FilterChain, 0, 4), +} + +var defaultCookieJar http.CookieJar +var settingMutex sync.Mutex + +// AddDefaultFilter add a new filter into defaultSetting +// Be careful about using this method if you invoke SetDefaultSetting somewhere +func AddDefaultFilter(fc FilterChain) { + settingMutex.Lock() + defer settingMutex.Unlock() + if defaultSetting.FilterChains == nil { + defaultSetting.FilterChains = make([]FilterChain, 0, 4) + } + defaultSetting.FilterChains = append(defaultSetting.FilterChains, fc) +} \ No newline at end of file diff --git a/client/httplib/testing/client.go b/client/httplib/testing/client.go index 34e49f2d..517e0722 100644 --- a/client/httplib/testing/client.go +++ b/client/httplib/testing/client.go @@ -15,7 +15,7 @@ package testing import ( - "github.com/astaxie/beego/client/httplib" + "github.com/beego/beego/v2/client/httplib" ) var port = "" diff --git a/client/orm/README.md b/client/orm/README.md index 6e808d2a..58669e1f 100644 --- a/client/orm/README.md +++ b/client/orm/README.md @@ -1,6 +1,6 @@ # beego orm -[![Build Status](https://drone.io/github.com/astaxie/beego/status.png)](https://drone.io/github.com/astaxie/beego/latest) +[![Build Status](https://drone.io/github.com/beego/beego/v2/status.png)](https://drone.io/github.com/beego/beego/v2/latest) A powerful orm framework for go. @@ -27,7 +27,7 @@ more features please read the docs **Install:** - go get github.com/astaxie/beego/orm + go get github.com/beego/beego/v2/orm ## Changelog @@ -45,7 +45,7 @@ package main import ( "fmt" - "github.com/astaxie/beego/orm" + "github.com/beego/beego/v2/orm" _ "github.com/go-sql-driver/mysql" // import your used driver ) diff --git a/client/orm/db.go b/client/orm/db.go index b103d218..4080f292 100644 --- a/client/orm/db.go +++ b/client/orm/db.go @@ -22,7 +22,7 @@ import ( "strings" "time" - "github.com/astaxie/beego/client/orm/hints" + "github.com/beego/beego/v2/client/orm/hints" ) const ( @@ -524,7 +524,7 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName) } - //Get on the key-value pairs + // Get on the key-value pairs for _, v := range args { kv := strings.Split(v, "=") if len(kv) == 2 { @@ -559,7 +559,7 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a updates[i] = v + "=" + valueStr case DRPostgres: if conflitValue != nil { - //postgres ON CONFLICT DO UPDATE SET can`t use colu=colu+values + // postgres ON CONFLICT DO UPDATE SET can`t use colu=colu+values updates[i] = fmt.Sprintf("%s=(select %s from %s where %s = ? )", v, valueStr, mi.table, args0) updateValues = append(updateValues, conflitValue) } else { @@ -584,7 +584,7 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a if isMulti { qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks } - //conflitValue maybe is a int,can`t use fmt.Sprintf + // conflitValue maybe is a int,can`t use fmt.Sprintf query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s) %s "+qupdates, Q, mi.table, Q, Q, columns, Q, qmarks, iouStr) d.ins.ReplaceMarks(&query) diff --git a/client/orm/db_mysql.go b/client/orm/db_mysql.go index f674ab2b..ee68baf7 100644 --- a/client/orm/db_mysql.go +++ b/client/orm/db_mysql.go @@ -111,7 +111,7 @@ func (d *dbBaseMysql) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Val iouStr = "ON DUPLICATE KEY UPDATE" - //Get on the key-value pairs + // Get on the key-value pairs for _, v := range args { kv := strings.Split(v, "=") if len(kv) == 2 { @@ -155,7 +155,7 @@ func (d *dbBaseMysql) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Val if isMulti { qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks } - //conflitValue maybe is a int,can`t use fmt.Sprintf + // conflitValue maybe is a int,can`t use fmt.Sprintf query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s) %s "+qupdates, Q, mi.table, Q, Q, columns, Q, qmarks, iouStr) d.ins.ReplaceMarks(&query) diff --git a/client/orm/db_oracle.go b/client/orm/db_oracle.go index cb0d5052..1de440b6 100644 --- a/client/orm/db_oracle.go +++ b/client/orm/db_oracle.go @@ -18,7 +18,7 @@ import ( "fmt" "strings" - "github.com/astaxie/beego/client/orm/hints" + "github.com/beego/beego/v2/client/orm/hints" ) // oracle operators. @@ -77,7 +77,7 @@ func (d *dbBaseOracle) DbTypes() map[string]string { return oracleTypes } -//ShowTablesQuery show all the tables in database +// ShowTablesQuery show all the tables in database func (d *dbBaseOracle) ShowTablesQuery() string { return "SELECT TABLE_NAME FROM USER_TABLES" } diff --git a/client/orm/db_sqlite.go b/client/orm/db_sqlite.go index 961f2535..aff713a5 100644 --- a/client/orm/db_sqlite.go +++ b/client/orm/db_sqlite.go @@ -21,7 +21,7 @@ import ( "strings" "time" - "github.com/astaxie/beego/client/orm/hints" + "github.com/beego/beego/v2/client/orm/hints" ) // sqlite operators. diff --git a/client/orm/do_nothing_orm.go b/client/orm/do_nothing_orm.go index fc5b2159..c6da420d 100644 --- a/client/orm/do_nothing_orm.go +++ b/client/orm/do_nothing_orm.go @@ -18,7 +18,7 @@ import ( "context" "database/sql" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // DoNothingOrm won't do anything, usually you use this to custom your mock Ormer implementation diff --git a/client/orm/filter/bean/default_value_filter.go b/client/orm/filter/bean/default_value_filter.go index 3dac5c74..b71903b3 100644 --- a/client/orm/filter/bean/default_value_filter.go +++ b/client/orm/filter/bean/default_value_filter.go @@ -19,10 +19,10 @@ import ( "reflect" "strings" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - "github.com/astaxie/beego/client/orm" - "github.com/astaxie/beego/core/bean" + "github.com/beego/beego/v2/client/orm" + "github.com/beego/beego/v2/core/bean" ) // DefaultValueFilterChainBuilder only works for InsertXXX method, diff --git a/client/orm/filter/bean/default_value_filter_test.go b/client/orm/filter/bean/default_value_filter_test.go index 2a6ed1f4..871d5539 100644 --- a/client/orm/filter/bean/default_value_filter_test.go +++ b/client/orm/filter/bean/default_value_filter_test.go @@ -19,7 +19,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) func TestDefaultValueFilterChainBuilder_FilterChain(t *testing.T) { diff --git a/client/orm/filter/opentracing/filter.go b/client/orm/filter/opentracing/filter.go index 7f9658b4..75852c63 100644 --- a/client/orm/filter/opentracing/filter.go +++ b/client/orm/filter/opentracing/filter.go @@ -20,7 +20,7 @@ import ( "github.com/opentracing/opentracing-go" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // FilterChainBuilder provides an extension point diff --git a/client/orm/filter/opentracing/filter_test.go b/client/orm/filter/opentracing/filter_test.go index 428dacda..d6ee1fd8 100644 --- a/client/orm/filter/opentracing/filter_test.go +++ b/client/orm/filter/opentracing/filter_test.go @@ -21,7 +21,7 @@ import ( "github.com/opentracing/opentracing-go" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) func TestFilterChainBuilder_FilterChain(t *testing.T) { diff --git a/client/orm/filter/prometheus/filter.go b/client/orm/filter/prometheus/filter.go index e74e946a..db60876e 100644 --- a/client/orm/filter/prometheus/filter.go +++ b/client/orm/filter/prometheus/filter.go @@ -22,7 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) // FilterChainBuilder is an extension point, @@ -50,7 +50,7 @@ func (builder *FilterChainBuilder) FilterChain(next orm.Filter) orm.Filter { "appname": builder.AppName, }, Help: "The statics info for orm operation", - }, []string{"method", "name", "duration", "insideTx", "txName"}) + }, []string{"method", "name", "insideTx", "txName"}) return func(ctx context.Context, inv *orm.Invocation) []interface{} { startTime := time.Now() @@ -74,12 +74,12 @@ func (builder *FilterChainBuilder) report(ctx context.Context, inv *orm.Invocati builder.reportTxn(ctx, inv) return } - builder.summaryVec.WithLabelValues(inv.Method, inv.GetTableName(), strconv.Itoa(int(dur)), - strconv.FormatBool(inv.InsideTx), inv.TxName) + builder.summaryVec.WithLabelValues(inv.Method, inv.GetTableName(), + strconv.FormatBool(inv.InsideTx), inv.TxName).Observe(float64(dur)) } func (builder *FilterChainBuilder) reportTxn(ctx context.Context, inv *orm.Invocation) { dur := time.Now().Sub(inv.TxStartTime) / time.Millisecond - builder.summaryVec.WithLabelValues(inv.Method, inv.TxName, strconv.Itoa(int(dur)), - strconv.FormatBool(inv.InsideTx), inv.TxName) + builder.summaryVec.WithLabelValues(inv.Method, inv.TxName, + strconv.FormatBool(inv.InsideTx), inv.TxName).Observe(float64(dur)) } diff --git a/client/orm/filter/prometheus/filter_test.go b/client/orm/filter/prometheus/filter_test.go index 72b16038..92316557 100644 --- a/client/orm/filter/prometheus/filter_test.go +++ b/client/orm/filter/prometheus/filter_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/client/orm" + "github.com/beego/beego/v2/client/orm" ) func TestFilterChainBuilder_FilterChain1(t *testing.T) { diff --git a/client/orm/filter_orm_decorator.go b/client/orm/filter_orm_decorator.go index 9f837cba..a60390a1 100644 --- a/client/orm/filter_orm_decorator.go +++ b/client/orm/filter_orm_decorator.go @@ -20,7 +20,7 @@ import ( "reflect" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) const ( diff --git a/client/orm/filter_orm_decorator_test.go b/client/orm/filter_orm_decorator_test.go index 671ca001..9e223358 100644 --- a/client/orm/filter_orm_decorator_test.go +++ b/client/orm/filter_orm_decorator_test.go @@ -21,7 +21,7 @@ import ( "sync" "testing" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" "github.com/stretchr/testify/assert" ) @@ -222,7 +222,7 @@ func TestFilterOrmDecorator_InsertMulti(t *testing.T) { } }) - bulk := []*FilterTestEntity{&FilterTestEntity{}, &FilterTestEntity{}} + bulk := []*FilterTestEntity{{}, {}} i, err := od.InsertMulti(2, bulk) assert.NotNil(t, err) assert.Equal(t, "insert multi error", err.Error()) diff --git a/client/orm/hints/db_hints.go b/client/orm/hints/db_hints.go index 7bfe8eb0..6578a595 100644 --- a/client/orm/hints/db_hints.go +++ b/client/orm/hints/db_hints.go @@ -15,11 +15,11 @@ package hints import ( - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) const ( - //query level + // query level KeyForceIndex = iota KeyUseIndex KeyIgnoreIndex diff --git a/client/orm/migration/ddl.go b/client/orm/migration/ddl.go index a396d39a..ec6dc2e7 100644 --- a/client/orm/migration/ddl.go +++ b/client/orm/migration/ddl.go @@ -17,7 +17,7 @@ package migration import ( "fmt" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // Index struct defines the structure of Index Columns diff --git a/client/orm/migration/migration.go b/client/orm/migration/migration.go index aeea12c6..86d6f590 100644 --- a/client/orm/migration/migration.go +++ b/client/orm/migration/migration.go @@ -33,8 +33,8 @@ import ( "strings" "time" - "github.com/astaxie/beego/client/orm" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/client/orm" + "github.com/beego/beego/v2/core/logs" ) // const the data format for the bee generate migration datatype @@ -52,7 +52,7 @@ type Migrationer interface { GetCreated() int64 } -//Migration defines the migrations by either SQL or DDL +// Migration defines the migrations by either SQL or DDL type Migration struct { sqls []string Created string @@ -104,7 +104,7 @@ func (m *Migration) Down() { m.sqls = append(m.sqls, m.GetSQL()) } -//Migrate adds the SQL to the execution list +// Migrate adds the SQL to the execution list func (m *Migration) Migrate(migrationType string) { m.ModifyType = migrationType m.sqls = append(m.sqls, m.GetSQL()) diff --git a/client/orm/models.go b/client/orm/models.go index 19941d2e..64dfab09 100644 --- a/client/orm/models.go +++ b/client/orm/models.go @@ -45,7 +45,7 @@ type _modelCache struct { done bool } -//NewModelCacheHandler generator of _modelCache +// NewModelCacheHandler generator of _modelCache func NewModelCacheHandler() *_modelCache { return &_modelCache{ cache: make(map[string]*modelInfo), @@ -113,7 +113,7 @@ func (mc *_modelCache) clean() { mc.done = false } -//bootstrap bootstrap for models +// bootstrap bootstrap for models func (mc *_modelCache) bootstrap() { mc.Lock() defer mc.Unlock() @@ -407,7 +407,7 @@ func (mc *_modelCache) register(prefixOrSuffixStr string, prefixOrSuffix bool, m return } -//getDbDropSQL get database scheme drop sql queries +// getDbDropSQL get database scheme drop sql queries func (mc *_modelCache) getDbDropSQL(al *alias) (queries []string, err error) { if len(mc.cache) == 0 { err = errors.New("no Model found, need register your model") @@ -422,7 +422,7 @@ func (mc *_modelCache) getDbDropSQL(al *alias) (queries []string, err error) { return queries, nil } -//getDbCreateSQL get database scheme creation sql queries +// getDbCreateSQL get database scheme creation sql queries func (mc *_modelCache) getDbCreateSQL(al *alias) (queries []string, tableIndexes map[string][]dbIndex, err error) { if len(mc.cache) == 0 { err = errors.New("no Model found, need register your model") @@ -467,9 +467,9 @@ func (mc *_modelCache) getDbCreateSQL(al *alias) (queries []string, tableIndexes column += " " + "NOT NULL" } - //if fi.initial.String() != "" { + // if fi.initial.String() != "" { // column += " DEFAULT " + fi.initial.String() - //} + // } // Append attribute DEFAULT column += getColumnDefault(fi) diff --git a/client/orm/models_info_f.go b/client/orm/models_info_f.go index 7152fada..c7ad4801 100644 --- a/client/orm/models_info_f.go +++ b/client/orm/models_info_f.go @@ -194,7 +194,7 @@ checkType: } fieldType = f.FieldType() if fieldType&IsRelField > 0 { - err = fmt.Errorf("unsupport type custom field, please refer to https://github.com/astaxie/beego/blob/master/orm/models_fields.go#L24-L42") + err = fmt.Errorf("unsupport type custom field, please refer to https://github.com/beego/beego/v2/blob/master/orm/models_fields.go#L24-L42") goto end } default: diff --git a/client/orm/models_info_m.go b/client/orm/models_info_m.go index c450239c..c9a979af 100644 --- a/client/orm/models_info_m.go +++ b/client/orm/models_info_m.go @@ -74,7 +74,7 @@ func addModelFields(mi *modelInfo, ind reflect.Value, mName string, index []int) } else if err != nil { break } - //record current field index + // record current field index fi.fieldIndex = append(fi.fieldIndex, index...) fi.fieldIndex = append(fi.fieldIndex, i) fi.mi = mi diff --git a/client/orm/models_test.go b/client/orm/models_test.go index d5aa2fa0..e3f74c0b 100644 --- a/client/orm/models_test.go +++ b/client/orm/models_test.go @@ -318,7 +318,7 @@ type Post struct { Created time.Time `orm:"auto_now_add"` Updated time.Time `orm:"auto_now"` UpdatedPrecision time.Time `orm:"auto_now;type(datetime);precision(4)"` - Tags []*Tag `orm:"rel(m2m);rel_through(github.com/astaxie/beego/client/orm.PostTags)"` + Tags []*Tag `orm:"rel(m2m);rel_through(github.com/beego/beego/v2/client/orm.PostTags)"` } func (u *Post) TableIndex() [][]string { @@ -376,7 +376,7 @@ type Group struct { type Permission struct { ID int `orm:"column(id)"` Name string - Groups []*Group `orm:"rel(m2m);rel_through(github.com/astaxie/beego/client/orm.GroupPermissions)"` + Groups []*Group `orm:"rel(m2m);rel_through(github.com/beego/beego/v2/client/orm.GroupPermissions)"` } type GroupPermissions struct { @@ -485,7 +485,7 @@ var ( usage: - go get -u github.com/astaxie/beego/client/orm + go get -u github.com/beego/beego/v2/client/orm go get -u github.com/go-sql-driver/mysql go get -u github.com/mattn/go-sqlite3 go get -u github.com/lib/pq @@ -495,25 +495,25 @@ var ( mysql -u root -e 'create database orm_test;' export ORM_DRIVER=mysql export ORM_SOURCE="root:@/orm_test?charset=utf8" - go test -v github.com/astaxie/beego/client/orm + go test -v github.com/beego/beego/v2/client/orm #### Sqlite3 export ORM_DRIVER=sqlite3 export ORM_SOURCE='file:memory_test?mode=memory' - go test -v github.com/astaxie/beego/client/orm + go test -v github.com/beego/beego/v2/client/orm #### PostgreSQL psql -c 'create database orm_test;' -U postgres export ORM_DRIVER=postgres export ORM_SOURCE="user=postgres dbname=orm_test sslmode=disable" - go test -v github.com/astaxie/beego/client/orm + go test -v github.com/beego/beego/v2/client/orm #### TiDB export ORM_DRIVER=tidb export ORM_SOURCE='memory://test/test' - go test -v github.com/astaxie/beego/pgk/orm + go test -v github.com/beego/beego/v2/pgk/orm ` ) diff --git a/client/orm/orm.go b/client/orm/orm.go index a228c626..f4422648 100644 --- a/client/orm/orm.go +++ b/client/orm/orm.go @@ -21,7 +21,7 @@ // // import ( // "fmt" -// "github.com/astaxie/beego/client/orm" +// "github.com/beego/beego/v2/client/orm" // _ "github.com/go-sql-driver/mysql" // import your used driver // ) // @@ -63,10 +63,10 @@ import ( "reflect" "time" - "github.com/astaxie/beego/client/orm/hints" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/client/orm/hints" + "github.com/beego/beego/v2/core/utils" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // DebugQueries define the debug diff --git a/client/orm/orm_conds.go b/client/orm/orm_conds.go index fbf62c5a..99828f3c 100644 --- a/client/orm/orm_conds.go +++ b/client/orm/orm_conds.go @@ -77,10 +77,13 @@ func (c Condition) AndNot(expr string, args ...interface{}) *Condition { // AndCond combine a condition to current condition func (c *Condition) AndCond(cond *Condition) *Condition { - c = c.clone() + if c == cond { panic(fmt.Errorf(" cannot use self as sub cond")) } + + c = c.clone() + if cond != nil { c.params = append(c.params, condValue{cond: cond, isCond: true}) } @@ -150,5 +153,8 @@ func (c *Condition) IsEmpty() bool { // clone clone a condition func (c Condition) clone() *Condition { + params := make([]condValue, len(c.params)) + copy(params, c.params) + c.params = params return &c } diff --git a/client/orm/orm_log.go b/client/orm/orm_log.go index d8df7e36..61addeb5 100644 --- a/client/orm/orm_log.go +++ b/client/orm/orm_log.go @@ -29,7 +29,7 @@ type Log struct { *log.Logger } -//costomer log func +// costomer log func var LogFunc func(query map[string]interface{}) // NewLog set io.Writer to create a Logger. diff --git a/client/orm/orm_queryset.go b/client/orm/orm_queryset.go index 45900487..9f7a3c1e 100644 --- a/client/orm/orm_queryset.go +++ b/client/orm/orm_queryset.go @@ -17,8 +17,8 @@ package orm import ( "context" "fmt" - "github.com/astaxie/beego/client/orm/hints" - "github.com/astaxie/beego/client/orm/clauses/order_clause" + "github.com/astaxie/beego/v2/client/orm/hints" + "github.com/astaxie/beego/v2/client/orm/clauses/order_clause" ) type colValue struct { diff --git a/client/orm/orm_raw.go b/client/orm/orm_raw.go index e11e97fa..af9c00cc 100644 --- a/client/orm/orm_raw.go +++ b/client/orm/orm_raw.go @@ -181,6 +181,12 @@ func (o *rawSet) setFieldValue(ind reflect.Value, value interface{}) { if err == nil { ind.Set(reflect.ValueOf(t)) } + } else if len(str) >= 8 { + str = str[:8] + t, err := time.ParseInLocation(formatTime, str, DefaultTimeLoc) + if err == nil { + ind.Set(reflect.ValueOf(t)) + } } } case sql.NullString, sql.NullInt64, sql.NullFloat64, sql.NullBool: diff --git a/client/orm/orm_test.go b/client/orm/orm_test.go index 2f3f9d55..1dd3bc8d 100644 --- a/client/orm/orm_test.go +++ b/client/orm/orm_test.go @@ -32,7 +32,7 @@ import ( "testing" "time" - "github.com/astaxie/beego/client/orm/hints" + "github.com/beego/beego/v2/client/orm/hints" "github.com/stretchr/testify/assert" ) @@ -1780,6 +1780,10 @@ func TestRawQueryRow(t *testing.T) { throwFail(t, AssertIs(id, 1)) break case "time": + v = v.(time.Time).In(DefaultTimeLoc) + value := dataValues[col].(time.Time).In(DefaultTimeLoc) + assert.True(t, v.(time.Time).Sub(value) <= time.Second) + break case "date": case "datetime": v = v.(time.Time).In(DefaultTimeLoc) @@ -1807,12 +1811,12 @@ func TestRawQueryRow(t *testing.T) { throwFail(t, AssertIs(*status, 3)) throwFail(t, AssertIs(pid, nil)) - type Embeded struct { + type Embedded struct { Email string } type queryRowNoModelTest struct { Id int - EmbedField Embeded + EmbedField Embedded } cols = []string{ @@ -2702,3 +2706,48 @@ func TestPSQueryBuilder(t *testing.T) { throwFailNow(t, AssertIs(l[0].UserName, "astaxie")) throwFailNow(t, AssertIs(l[0].Age, 30)) } + +func TestCondition(t *testing.T) { + // test Condition whether to include yourself + cond := NewCondition() + cond = cond.AndCond(cond.Or("ID", 1)) + cond = cond.AndCond(cond.Or("ID", 2)) + cond = cond.AndCond(cond.Or("ID", 3)) + cond = cond.AndCond(cond.Or("ID", 4)) + + cycleFlag := false + var hasCycle func(*Condition) + hasCycle = func(c *Condition) { + if nil == c || cycleFlag { + return + } + condPointMap := make(map[string]bool) + condPointMap[fmt.Sprintf("%p", c)] = true + for _, p := range c.params { + if p.isCond { + adr := fmt.Sprintf("%p", p.cond) + if condPointMap[adr] { + // self as sub cond was cycle + cycleFlag = true + break + } + condPointMap[adr] = true + + } + } + if cycleFlag { + return + } + for _, p := range c.params { + if p.isCond { + // check next cond + hasCycle(p.cond) + } + } + return + } + hasCycle(cond) + // cycleFlag was true,meaning use self as sub cond + throwFail(t, AssertIs(!cycleFlag, true)) + return +} diff --git a/client/orm/types.go b/client/orm/types.go index 5da40830..37aa9f3f 100644 --- a/client/orm/types.go +++ b/client/orm/types.go @@ -21,7 +21,7 @@ import ( "reflect" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // TableNaming is usually used by model @@ -96,13 +96,13 @@ type Fielder interface { } type TxBeginner interface { - //self control transaction + // self control transaction Begin() (TxOrmer, error) BeginWithCtx(ctx context.Context) (TxOrmer, error) BeginWithOpts(opts *sql.TxOptions) (TxOrmer, error) BeginWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions) (TxOrmer, error) - //closure control transaction + // closure control transaction DoTx(task func(ctx context.Context, txOrm TxOrmer) error) error DoTxWithCtx(ctx context.Context, task func(ctx context.Context, txOrm TxOrmer) error) error DoTxWithOpts(opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error @@ -114,7 +114,7 @@ type TxCommitter interface { Rollback() error } -//Data Manipulation Language +// Data Manipulation Language type DML interface { // insert model data to database // for example: diff --git a/client/orm/utils.go b/client/orm/utils.go index 3ff76772..d6c0a8e8 100644 --- a/client/orm/utils.go +++ b/client/orm/utils.go @@ -49,12 +49,12 @@ func (f *StrTo) Set(v string) { // Clear string func (f *StrTo) Clear() { - *f = StrTo(0x1E) + *f = StrTo(rune(0x1E)) } // Exist check string exist func (f StrTo) Exist() bool { - return string(f) != string(0x1E) + return string(f) != string(rune(0x1E)) } // Bool string to bool diff --git a/core/governor/command.go b/core/admin/command.go similarity index 99% rename from core/governor/command.go rename to core/admin/command.go index 75df5815..f65d2750 100644 --- a/core/governor/command.go +++ b/core/admin/command.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package governor +package admin import ( "github.com/pkg/errors" diff --git a/core/governor/healthcheck.go b/core/admin/healthcheck.go similarity index 96% rename from core/governor/healthcheck.go rename to core/admin/healthcheck.go index a91f09fa..79738d1d 100644 --- a/core/governor/healthcheck.go +++ b/core/admin/healthcheck.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package governor healthcheck +// Package admin healthcheck // // type DatabaseCheck struct { // } @@ -28,7 +28,7 @@ // AddHealthCheck("database",&DatabaseCheck{}) // // more docs: http://beego.me/docs/module/toolbox.md -package governor +package admin // AdminCheckList holds health checker map var AdminCheckList map[string]HealthChecker diff --git a/core/governor/profile.go b/core/admin/profile.go similarity index 98% rename from core/governor/profile.go rename to core/admin/profile.go index 17f1f375..5b3fdb21 100644 --- a/core/governor/profile.go +++ b/core/admin/profile.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package governor +package admin import ( "fmt" @@ -26,7 +26,7 @@ import ( "strconv" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) var startTime = time.Now() diff --git a/core/governor/profile_test.go b/core/admin/profile_test.go similarity index 98% rename from core/governor/profile_test.go rename to core/admin/profile_test.go index 530b0637..139c4b99 100644 --- a/core/governor/profile_test.go +++ b/core/admin/profile_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package governor +package admin import ( "os" diff --git a/core/bean/tag_auto_wire_bean_factory.go b/core/bean/tag_auto_wire_bean_factory.go index b88a42ff..821eed26 100644 --- a/core/bean/tag_auto_wire_bean_factory.go +++ b/core/bean/tag_auto_wire_bean_factory.go @@ -22,7 +22,7 @@ import ( "github.com/pkg/errors" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) const DefaultValueTagKey = "default" diff --git a/core/config/config.go b/core/config/config.go index a4a24fff..d0add317 100644 --- a/core/config/config.go +++ b/core/config/config.go @@ -14,7 +14,7 @@ // Package config is used to parse config. // Usage: -// import "github.com/astaxie/beego/config" +// import "github.com/beego/beego/v2/config" // Examples. // // cnf, err := config.NewConfig("ini", "config.conf") diff --git a/core/config/env/env.go b/core/config/env/env.go index d3903d74..fbf06c5d 100644 --- a/core/config/env/env.go +++ b/core/config/env/env.go @@ -21,7 +21,7 @@ import ( "os" "strings" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) var env *utils.BeeMap diff --git a/core/config/etcd/config.go b/core/config/etcd/config.go index 6c3d33d4..acc43f35 100644 --- a/core/config/etcd/config.go +++ b/core/config/etcd/config.go @@ -26,8 +26,8 @@ import ( "github.com/pkg/errors" "google.golang.org/grpc" - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/core/logs" ) type EtcdConfiger struct { diff --git a/core/config/global.go b/core/config/global.go index c5c59ba7..d0b74253 100644 --- a/core/config/global.go +++ b/core/config/global.go @@ -14,26 +14,13 @@ package config -import ( - "github.com/astaxie/beego/core/logs" -) - // We use this to simply application's development // for most users, they only need to use those methods var globalInstance Configer -func init() { - // Ignore this error - err := InitGlobalInstance("ini", "config/app.conf") - if err != nil { - logs.Warn("init global config instance failed. If you donot use this, just ignore it. ", err) - } - -} - // InitGlobalInstance will ini the global instance // If you want to use specific implementation, don't forget to import it. -// e.g. _ import "github.com/astaxie/beego/core/config/etcd" +// e.g. _ import "github.com/beego/beego/v2/core/config/etcd" // err := InitGlobalInstance("etcd", "someconfig") func InitGlobalInstance(name string, cfg string) error { var err error diff --git a/core/config/ini.go b/core/config/ini.go index 93dd774a..f2877ce8 100644 --- a/core/config/ini.go +++ b/core/config/ini.go @@ -29,6 +29,8 @@ import ( "sync" "github.com/mitchellh/mapstructure" + + "github.com/beego/beego/v2/core/logs" ) var ( @@ -97,7 +99,7 @@ func (ini *IniConfig) parseData(dir string, data []byte) (*IniConfigContainer, e break } - //It might be a good idea to throw a error on all unknonw errors? + // It might be a good idea to throw a error on all unknonw errors? if _, ok := err.(*os.PathError); ok { return nil, err } @@ -516,4 +518,11 @@ func (c *IniConfigContainer) Unmarshaler(prefix string, obj interface{}, opt ... func init() { Register("ini", &IniConfig{}) + + err := InitGlobalInstance("ini", "conf/app.conf") + if err != nil { + logs.Warn("init global config instance failed. If you donot use this, just ignore it. ", err) + } } + +// Ignore this error diff --git a/core/config/ini_test.go b/core/config/ini_test.go index 7daa0a6e..b7a03aa2 100644 --- a/core/config/ini_test.go +++ b/core/config/ini_test.go @@ -146,7 +146,7 @@ httpport = 8080 # enable db [dbinfo] # db type name -# suport mysql,sqlserver +# support mysql,sqlserver name = mysql ` @@ -162,7 +162,7 @@ httpport=8080 # enable db [dbinfo] # db type name -# suport mysql,sqlserver +# support mysql,sqlserver name=mysql ` ) diff --git a/core/config/json/json.go b/core/config/json/json.go index 672d2787..c1a29cad 100644 --- a/core/config/json/json.go +++ b/core/config/json/json.go @@ -26,8 +26,8 @@ import ( "github.com/mitchellh/mapstructure" - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/core/logs" ) // JSONConfig is a json config parser and implements Config interface. diff --git a/core/config/json/json_test.go b/core/config/json/json_test.go index 386cfdf1..8f5b2c83 100644 --- a/core/config/json/json_test.go +++ b/core/config/json/json_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) func TestJsonStartsWithArray(t *testing.T) { diff --git a/core/config/toml/toml.go b/core/config/toml/toml.go index 96e1a200..9261cd27 100644 --- a/core/config/toml/toml.go +++ b/core/config/toml/toml.go @@ -21,7 +21,7 @@ import ( "github.com/pelletier/go-toml" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) const keySeparator = "." diff --git a/core/config/toml/toml_test.go b/core/config/toml/toml_test.go index 20726f0d..2867f4be 100644 --- a/core/config/toml/toml_test.go +++ b/core/config/toml/toml_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) func TestConfig_Parse(t *testing.T) { diff --git a/core/config/xml/xml.go b/core/config/xml/xml.go index 70f0c23c..059ada5c 100644 --- a/core/config/xml/xml.go +++ b/core/config/xml/xml.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/config/xml" -// "github.com/astaxie/beego/config" +// _ "github.com/beego/beego/v2/config/xml" +// "github.com/beego/beego/v2/config" // ) // // cnf, err := config.NewConfig("xml", "config.xml") @@ -41,8 +41,8 @@ import ( "github.com/mitchellh/mapstructure" - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/core/logs" "github.com/beego/x2j" ) diff --git a/core/config/xml/xml_test.go b/core/config/xml/xml_test.go index c6cf970d..37c5fe7f 100644 --- a/core/config/xml/xml_test.go +++ b/core/config/xml/xml_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) func TestXML(t *testing.T) { diff --git a/core/config/yaml/yaml.go b/core/config/yaml/yaml.go index 71daabee..778a4eb1 100644 --- a/core/config/yaml/yaml.go +++ b/core/config/yaml/yaml.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/config/yaml" -// "github.com/astaxie/beego/config" +// _ "github.com/beego/beego/v2/config/yaml" +// "github.com/beego/beego/v2/config" // ) // // cnf, err := config.NewConfig("yaml", "config.yaml") @@ -43,8 +43,8 @@ import ( "github.com/beego/goyaml2" "gopkg.in/yaml.v2" - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/core/logs" ) // Config is a yaml config parser and implements Config interface. diff --git a/core/config/yaml/yaml_test.go b/core/config/yaml/yaml_test.go index d18317db..cf889613 100644 --- a/core/config/yaml/yaml_test.go +++ b/core/config/yaml/yaml_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/config" + "github.com/beego/beego/v2/core/config" ) func TestYaml(t *testing.T) { diff --git a/core/logs/README.md b/core/logs/README.md index c05bcc04..c7c82110 100644 --- a/core/logs/README.md +++ b/core/logs/README.md @@ -1,24 +1,22 @@ ## logs -logs is a Go logs manager. It can use many logs adapters. The repo is inspired by `database/sql` . +logs is a Go logs manager. It can use many logs adapters. The repo is inspired by `database/sql` . ## How to install? - go get github.com/astaxie/beego/logs - + go get github.com/beego/beego/v2/logs ## What adapters are supported? As of now this logs support console, file,smtp and conn. - ## How to use it? First you must import it ```golang import ( - "github.com/astaxie/beego/logs" + "github.com/beego/beego/v2/logs" ) ``` diff --git a/core/logs/alils/alils.go b/core/logs/alils/alils.go index 484d31e4..7a3e4ddf 100644 --- a/core/logs/alils/alils.go +++ b/core/logs/alils/alils.go @@ -9,7 +9,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pkg/errors" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) const ( diff --git a/core/logs/console_test.go b/core/logs/console_test.go index e345ba40..02bff3ec 100644 --- a/core/logs/console_test.go +++ b/core/logs/console_test.go @@ -58,7 +58,7 @@ func TestConsoleAsync(t *testing.T) { log := NewLogger(100) log.SetLogger("console") log.Async() - //log.Close() + // log.Close() testConsoleCalls(log) for len(log.msgChan) != 0 { time.Sleep(1 * time.Millisecond) diff --git a/core/logs/es/es.go b/core/logs/es/es.go index 6175f253..2e592ffd 100644 --- a/core/logs/es/es.go +++ b/core/logs/es/es.go @@ -12,7 +12,7 @@ import ( "github.com/elastic/go-elasticsearch/v6" "github.com/elastic/go-elasticsearch/v6/esapi" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // NewES returns a LoggerInterface @@ -29,7 +29,7 @@ func NewES() logs.Logger { // please import this package // usually means that you can import this package in your main package // for example, anonymous: -// import _ "github.com/astaxie/beego/logs/es" +// import _ "github.com/beego/beego/v2/logs/es" type esLogger struct { *elasticsearch.Client DSN string `json:"dsn"` diff --git a/core/logs/es/index.go b/core/logs/es/index.go index 0dafef4c..7a31eff1 100644 --- a/core/logs/es/index.go +++ b/core/logs/es/index.go @@ -17,7 +17,7 @@ package es import ( "fmt" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // IndexNaming generate the index name diff --git a/core/logs/es/index_test.go b/core/logs/es/index_test.go index 03e7a911..ce30763a 100644 --- a/core/logs/es/index_test.go +++ b/core/logs/es/index_test.go @@ -20,7 +20,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) func TestDefaultIndexNaming_IndexName(t *testing.T) { diff --git a/core/logs/file_test.go b/core/logs/file_test.go index 6612ebe6..e9a8922b 100644 --- a/core/logs/file_test.go +++ b/core/logs/file_test.go @@ -164,7 +164,7 @@ func TestFileDailyRotate_05(t *testing.T) { testFileDailyRotate(t, fn1, fn2) os.Remove(fn) } -func TestFileDailyRotate_06(t *testing.T) { //test file mode +func TestFileDailyRotate_06(t *testing.T) { // test file mode log := NewLogger(10000) log.SetLogger("file", `{"filename":"test3.log","maxlines":4}`) log.Debug("debug") @@ -237,7 +237,7 @@ func TestFileHourlyRotate_05(t *testing.T) { os.Remove(fn) } -func TestFileHourlyRotate_06(t *testing.T) { //test file mode +func TestFileHourlyRotate_06(t *testing.T) { // test file mode log := NewLogger(10000) log.SetLogger("file", `{"filename":"test3.log", "hourly":true, "maxlines":4}`) log.Debug("debug") diff --git a/core/logs/formatter.go b/core/logs/formatter.go index 67500b2b..80b30fa0 100644 --- a/core/logs/formatter.go +++ b/core/logs/formatter.go @@ -69,8 +69,8 @@ func (p *PatternLogFormatter) ToString(lm *LogMsg) string { 'm': lm.Msg, 'n': strconv.Itoa(lm.LineNumber), 'l': strconv.Itoa(lm.Level), - 't': levelPrefix[lm.Level-1], - 'T': levelNames[lm.Level-1], + 't': levelPrefix[lm.Level], + 'T': levelNames[lm.Level], 'F': lm.FilePath, } _, m['f'] = path.Split(lm.FilePath) diff --git a/core/logs/formatter_test.go b/core/logs/formatter_test.go index a97765ac..a1853d72 100644 --- a/core/logs/formatter_test.go +++ b/core/logs/formatter_test.go @@ -88,7 +88,7 @@ func TestPatternLogFormatter(t *testing.T) { } got := tes.ToString(lm) want := lm.FilePath + ":" + strconv.Itoa(lm.LineNumber) + "|" + - when.Format(tes.WhenFormat) + levelPrefix[lm.Level-1] + ">> " + lm.Msg + when.Format(tes.WhenFormat) + levelPrefix[lm.Level] + ">> " + lm.Msg if got != want { t.Errorf("want %s, got %s", want, got) } diff --git a/core/logs/log.go b/core/logs/log.go index b05abd3b..ef9aa7f3 100644 --- a/core/logs/log.go +++ b/core/logs/log.go @@ -15,7 +15,7 @@ // Package logs provide a general log interface // Usage: // -// import "github.com/astaxie/beego/logs" +// import "github.com/beego/beego/v2/logs" // // log := NewLogger(10000) // log.SetLogger("console", "") @@ -687,7 +687,7 @@ func EnableFuncCallDepth(b bool) { // SetLogFuncCall set the CallDepth, default is 4 func SetLogFuncCall(b bool) { beeLogger.EnableFuncCallDepth(b) - beeLogger.SetLogFuncCallDepth(4) + beeLogger.SetLogFuncCallDepth(3) } // SetLogFuncCallDepth set log funcCallDepth @@ -764,9 +764,7 @@ func formatLog(f interface{}, v ...interface{}) string { if len(v) == 0 { return msg } - if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") { - // format string - } else { + if !strings.Contains(msg, "%") { // do not contain format char msg += strings.Repeat(" %v", len(v)) } diff --git a/core/logs/logger.go b/core/logs/logger.go index d8b334d4..77e68ea2 100644 --- a/core/logs/logger.go +++ b/core/logs/logger.go @@ -60,7 +60,7 @@ func formatTimeHeader(when time.Time) ([]byte, int, int) { y, mo, d := when.Date() h, mi, s := when.Clock() ns := when.Nanosecond() / 1000000 - //len("2006/01/02 15:04:05.123 ")==24 + // len("2006/01/02 15:04:05.123 ")==24 var buf [24]byte buf[0] = y1[y/1000%10] @@ -126,12 +126,12 @@ func initColor() { cyan = w32Cyan } colorMap = map[string]string{ - //by color + // by color "green": green, "white": white, "yellow": yellow, "red": red, - //by method + // by method "GET": blue, "POST": cyan, "PUT": yellow, diff --git a/core/logs/slack.go b/core/logs/slack.go index b6e2f170..ce892a1b 100644 --- a/core/logs/slack.go +++ b/core/logs/slack.go @@ -1,10 +1,10 @@ package logs import ( + "bytes" "encoding/json" "fmt" "net/http" - "net/url" "github.com/pkg/errors" ) @@ -25,8 +25,8 @@ func newSLACKWriter() Logger { } func (s *SLACKWriter) Format(lm *LogMsg) string { - text := fmt.Sprintf("{\"text\": \"%s %s\"}", lm.When.Format("2006-01-02 15:04:05"), lm.OldStyleFormat()) - return text + // text := fmt.Sprintf("{\"text\": \"%s\"}", msg) + return lm.When.Format("2006-01-02 15:04:05") + " " + lm.OldStyleFormat() } func (s *SLACKWriter) SetFormatter(f LogFormatter) { @@ -55,10 +55,12 @@ func (s *SLACKWriter) WriteMsg(lm *LogMsg) error { return nil } msg := s.Format(lm) - form := url.Values{} - form.Add("payload", msg) + m := make(map[string]string, 1) + m["text"] = msg - resp, err := http.PostForm(s.WebhookURL, form) + body, _ := json.Marshal(m) + // resp, err := http.PostForm(s.WebhookURL, form) + resp, err := http.Post(s.WebhookURL, "application/json", bytes.NewReader(body)) if err != nil { return err } diff --git a/core/logs/slack_test.go b/core/logs/slack_test.go new file mode 100644 index 00000000..31f5cf97 --- /dev/null +++ b/core/logs/slack_test.go @@ -0,0 +1,44 @@ +// 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 logs + +// func TestSLACKWriter_WriteMsg(t *testing.T) { +// sc := ` +// { +// "webhookurl":"", +// "level":7 +// } +// ` +// l := newSLACKWriter() +// err := l.Init(sc) +// if err != nil { +// Debug(err) +// } +// +// err = l.WriteMsg(&LogMsg{ +// Level: 7, +// Msg: `{ "abs"`, +// When: time.Now(), +// FilePath: "main.go", +// LineNumber: 100, +// enableFullFilePath: true, +// enableFuncCallDepth: true, +// }) +// +// if err != nil { +// Debug(err) +// } +// +// } diff --git a/core/utils/kv.go b/core/utils/kv.go index f4e6c4d4..7fc5cee9 100644 --- a/core/utils/kv.go +++ b/core/utils/kv.go @@ -50,7 +50,7 @@ type SimpleKVs struct { var _ KVs = new(SimpleKVs) -// GetValueOr returns the value for a given key, if non-existant +// GetValueOr returns the value for a given key, if non-existent // it returns defValue func (kvs *SimpleKVs) GetValueOr(key interface{}, defValue interface{}) interface{} { v, ok := kvs.kvs[key] diff --git a/core/utils/mail.go b/core/utils/mail.go index 80a366ca..e685c449 100644 --- a/core/utils/mail.go +++ b/core/utils/mail.go @@ -188,10 +188,10 @@ func (e *Email) Attach(r io.Reader, filename string, args ...string) (a *Attachm err = errors.New("Must specify the file type and number of parameters can not exceed at least two") return } - c := args[0] //Content-Type + c := args[0] // Content-Type id := "" if len(args) > 1 { - id = args[1] //Content-ID + id = args[1] // Content-ID } var buffer bytes.Buffer if _, err = io.Copy(&buffer, r); err != nil { diff --git a/core/utils/pagination/doc.go b/core/utils/pagination/doc.go index b9c604b9..c2df00aa 100644 --- a/core/utils/pagination/doc.go +++ b/core/utils/pagination/doc.go @@ -8,7 +8,7 @@ In your beego.Controller: package controllers - import "github.com/astaxie/beego/core/utils/pagination" + import "github.com/beego/beego/v2/core/utils/pagination" type PostsController struct { beego.Controller diff --git a/core/validation/README.md b/core/validation/README.md index 43373e47..46d7c935 100644 --- a/core/validation/README.md +++ b/core/validation/README.md @@ -7,18 +7,18 @@ validation is a form validation for a data validation and error collecting using Install: - go get github.com/astaxie/beego/validation + go get github.com/beego/beego/v2/validation Test: - go test github.com/astaxie/beego/validation + go test github.com/beego/beego/v2/validation ## Example Direct Use: import ( - "github.com/astaxie/beego/validation" + "github.com/beego/beego/v2/validation" "log" ) @@ -49,7 +49,7 @@ Direct Use: Struct Tag Use: import ( - "github.com/astaxie/beego/validation" + "github.com/beego/beego/v2/validation" ) // validation function follow with "valid" tag @@ -81,7 +81,7 @@ Struct Tag Use: Use custom function: import ( - "github.com/astaxie/beego/validation" + "github.com/beego/beego/v2/validation" ) type user struct { @@ -141,7 +141,6 @@ Struct Tag Functions: Phone ZipCode - ## LICENSE BSD License http://creativecommons.org/licenses/BSD/ diff --git a/core/validation/validation.go b/core/validation/validation.go index 134e750e..eb3a1042 100644 --- a/core/validation/validation.go +++ b/core/validation/validation.go @@ -15,7 +15,7 @@ // Package validation for validations // // import ( -// "github.com/astaxie/beego/validation" +// "github.com/beego/beego/v2/validation" // "log" // ) // @@ -423,7 +423,7 @@ func (v *Validation) Valid(obj interface{}) (b bool, err error) { // Step2: If pass on step1, then reflect obj's fields // Step3: Do the Recursively validation to all struct or struct pointer fields func (v *Validation) RecursiveValid(objc interface{}) (bool, error) { - //Step 1: validate obj itself firstly + // Step 1: validate obj itself firstly // fails if objc is not struct pass, err := v.Valid(objc) if err != nil || !pass { diff --git a/core/validation/validators.go b/core/validation/validators.go index ec422d86..c4ea1f51 100644 --- a/core/validation/validators.go +++ b/core/validation/validators.go @@ -23,7 +23,7 @@ import ( "time" "unicode/utf8" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // CanSkipFuncs will skip valid if RequiredFirst is true and the struct field's value is empty diff --git a/go.mod b/go.mod index 7527aa47..89baa406 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,5 @@ -module github.com/astaxie/beego +//module github.com/beego/beego/v2 +module github.com/beego/beego/v2 require ( github.com/Knetic/govaluate v3.0.0+incompatible // indirect @@ -11,9 +12,9 @@ require ( github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf // indirect github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect - github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d - github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808 // indirect - github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a // indirect + github.com/couchbase/go-couchbase v0.0.0-20201216133707-c04035124b17 + github.com/couchbase/gomemcached v0.1.2-0.20201215185628-3bc3f73e68cb // indirect + github.com/couchbase/goutils v0.0.0-20201030094643-5e82bb967e67 // indirect github.com/elastic/go-elasticsearch/v6 v6.8.5 github.com/elazarl/go-bindata-assetfs v1.0.0 github.com/go-kit/kit v0.9.0 @@ -43,10 +44,9 @@ require ( go.etcd.io/etcd v3.3.25+incompatible // indirect go.uber.org/zap v1.15.0 // indirect golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 - golang.org/x/net v0.0.0-20200822124328-c89045814202 // indirect - golang.org/x/sys v0.0.0-20200824131525-c12d262b63d8 // indirect + golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 // indirect golang.org/x/text v0.3.3 // indirect - golang.org/x/tools v0.0.0-20200117065230-39095c1d176c + golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 google.golang.org/grpc v1.26.0 gopkg.in/yaml.v2 v2.2.8 honnef.co/go/tools v0.0.1-2020.1.5 // indirect diff --git a/go.sum b/go.sum index 994d1ec4..17ecab27 100644 --- a/go.sum +++ b/go.sum @@ -24,6 +24,7 @@ github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwt github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= @@ -39,10 +40,20 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f h1:lBNOc5arjvs8E5mO2tbp github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d h1:OMrhQqj1QCyDT2sxHCDjE+k8aMdn2ngTCGG7g4wrdLo= github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/go-couchbase v0.0.0-20201216133707-c04035124b17 h1:1ZELwRDUvpBpmgKSIUP6VMW1jIehzD0sCdWxRyejegw= +github.com/couchbase/go-couchbase v0.0.0-20201216133707-c04035124b17/go.mod h1:+/bddYDxXsf9qt0xpDUtRR47A2GjaXmGGAqQ/k3GJ8A= github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808 h1:8s2l8TVUwMXl6tZMe3+hPCRJ25nQXiA3d1x622JtOqc= github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/gomemcached v0.1.0 h1:whUde87n8CScx8ckMp2En5liqAlcuG3aKy/BQeBPu84= +github.com/couchbase/gomemcached v0.1.0/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/gomemcached v0.1.1 h1:xCS8ZglJDhrlQg3jmK7Rn1V8f7bPjXABLC05CgLQauc= +github.com/couchbase/gomemcached v0.1.1/go.mod h1:mxliKQxOv84gQ0bJWbI+w9Wxdpt9HjDvgW9MjCym5Vo= +github.com/couchbase/gomemcached v0.1.2-0.20201215185628-3bc3f73e68cb h1:ZCFku0K/3Xvl7rXkGGM+ioT76Rxko8V9wDEWa0GFp14= +github.com/couchbase/gomemcached v0.1.2-0.20201215185628-3bc3f73e68cb/go.mod h1:mxliKQxOv84gQ0bJWbI+w9Wxdpt9HjDvgW9MjCym5Vo= github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a h1:Y5XsLCEhtEI8qbD9RP3Qlv5FXdTDHxZM9UPUnMRgBp8= github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/couchbase/goutils v0.0.0-20201030094643-5e82bb967e67 h1:NCqJ6fwen6YP0WlV/IyibaT0kPt3JEI1rA62V/UPKT4= +github.com/couchbase/goutils v0.0.0-20201030094643-5e82bb967e67/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76 h1:Lgdd/Qp96Qj8jqLpq2cI1I1X7BJnu06efS+XkhRoLUQ= github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -209,6 +220,7 @@ github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnD github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b h1:0Ve0/CCjiAiyKddUMUn3RwIGlq2iTW4GuVzyoKBYO/8= github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= go.etcd.io/etcd v0.5.0-alpha.5 h1:VOolFSo3XgsmnYDLozjvZ6JL6AAwIDu1Yx1y+4EYLDo= go.etcd.io/etcd v3.3.25+incompatible h1:V1RzkZJj9LqsJRy+TUBgpWSbZXITLB819lstuTFoZOY= @@ -231,7 +243,10 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= @@ -252,6 +267,8 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrS golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -259,6 +276,7 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/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-20201020160332-67f06af15bc9/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-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -274,6 +292,8 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200824131525-c12d262b63d8 h1:AvbQYmiaaaza3cW3QXRyPo5kYgpFIzOAfeAAN7m3qQ4= golang.org/x/sys v0.0.0-20200824131525-c12d262b63d8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= @@ -293,8 +313,11 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200117065230-39095c1d176c h1:FodBYPZKH5tAN2O60HlglMwXGAeV/4k+NKbli79M/2c= golang.org/x/tools v0.0.0-20200117065230-39095c1d176c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200815165600-90abf76919f3 h1:0aScV/0rLmANzEYIhjCOi2pTvDyhZNduBUMD2q3iqs4= golang.org/x/tools v0.0.0-20200815165600-90abf76919f3/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 h1:1Bs6RVeBFtLZ8Yi1Hk07DiOqzvwLD/4hln4iahvFlag= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= 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 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= diff --git a/server/web/LICENSE b/server/web/LICENSE index 5dbd4243..26050108 100644 --- a/server/web/LICENSE +++ b/server/web/LICENSE @@ -10,4 +10,4 @@ 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. \ No newline at end of file +limitations under the License. diff --git a/server/web/admin.go b/server/web/admin.go index 1b06f486..d640c1be 100644 --- a/server/web/admin.go +++ b/server/web/admin.go @@ -20,7 +20,7 @@ import ( "reflect" "time" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" ) // BeeAdminApp is the default adminApp used by admin module. @@ -112,13 +112,13 @@ func registerAdmin() error { HttpServer: NewHttpServerWithCfg(BConfig), } // keep in mind that all data should be html escaped to avoid XSS attack - beeAdminApp.Router("/", c, "get:AdminIndex") - beeAdminApp.Router("/qps", c, "get:QpsIndex") - beeAdminApp.Router("/prof", c, "get:ProfIndex") - beeAdminApp.Router("/healthcheck", c, "get:Healthcheck") - beeAdminApp.Router("/task", c, "get:TaskStatus") - beeAdminApp.Router("/listconf", c, "get:ListConf") - beeAdminApp.Router("/metrics", c, "get:PrometheusMetrics") + beeAdminApp.Router("/", c, SetRouterMethods(c, "get:AdminIndex")) + beeAdminApp.Router("/qps", c, SetRouterMethods(c, "get:QpsIndex")) + beeAdminApp.Router("/prof", c, SetRouterMethods(c, "get:ProfIndex")) + beeAdminApp.Router("/healthcheck", c, SetRouterMethods(c, "get:Healthcheck")) + beeAdminApp.Router("/task", c, SetRouterMethods(c, "get:TaskStatus")) + beeAdminApp.Router("/listconf", c, SetRouterMethods(c, "get:ListConf")) + beeAdminApp.Router("/metrics", c, SetRouterMethods(c, "get:PrometheusMetrics")) go beeAdminApp.Run() } diff --git a/server/web/admin_controller.go b/server/web/admin_controller.go index 2998c8d4..8ac0ccd4 100644 --- a/server/web/admin_controller.go +++ b/server/web/admin_controller.go @@ -24,7 +24,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/astaxie/beego/core/governor" + "github.com/beego/beego/v2/core/admin" ) type adminController struct { @@ -51,7 +51,7 @@ func (a *adminController) ProfIndex() { data = make(map[interface{}]interface{}) result bytes.Buffer ) - governor.ProcessInput(command, &result) + admin.ProcessInput(command, &result) data["Content"] = template.HTMLEscapeString(result.String()) if format == "json" && command == "gc summary" { @@ -88,7 +88,7 @@ func (a *adminController) TaskStatus() { req.ParseForm() taskname := req.Form.Get("taskname") if taskname != "" { - cmd := governor.GetCommand("task", "run") + cmd := admin.GetCommand("task", "run") res := cmd.Execute(taskname) if res.IsSuccess() { @@ -103,7 +103,7 @@ func (a *adminController) TaskStatus() { // List Tasks content := make(M) - resultList := governor.GetCommand("task", "list").Execute().Content.([][]string) + resultList := admin.GetCommand("task", "list").Execute().Content.([][]string) var fields = []string{ "Task Name", "Task Spec", @@ -141,7 +141,7 @@ func heathCheck(rw http.ResponseWriter, r *http.Request) { } ) - for name, h := range governor.AdminCheckList { + for name, h := range admin.AdminCheckList { if err := h.Check(); err != nil { result = []string{ "error", @@ -250,7 +250,7 @@ func (a *adminController) ListConf() { filterTypeData := BeeApp.reportFilter() filterTypes := make([]string, 0, len(filterTypeData)) - for k, _ := range filterTypeData { + for k := range filterTypeData { filterTypes = append(filterTypes, k) } diff --git a/server/web/admin_test.go b/server/web/admin_test.go index 5ef57323..04da4fab 100644 --- a/server/web/admin_test.go +++ b/server/web/admin_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/core/governor" + "github.com/beego/beego/v2/core/admin" ) type SampleDatabaseCheck struct { @@ -126,8 +126,8 @@ func TestWriteJSON(t *testing.T) { func TestHealthCheckHandlerDefault(t *testing.T) { endpointPath := "/healthcheck" - governor.AddHealthCheck("database", &SampleDatabaseCheck{}) - governor.AddHealthCheck("cache", &SampleCacheCheck{}) + admin.AddHealthCheck("database", &SampleDatabaseCheck{}) + admin.AddHealthCheck("cache", &SampleCacheCheck{}) req, err := http.NewRequest("GET", endpointPath, nil) if err != nil { @@ -152,12 +152,12 @@ func TestHealthCheckHandlerDefault(t *testing.T) { func TestBuildHealthCheckResponseList(t *testing.T) { healthCheckResults := [][]string{ - []string{ + { "error", "Database", - "Error occured whie starting the db", + "Error occurred whie starting the db", }, - []string{ + { "success", "Cache", "Cache started successfully", @@ -187,8 +187,8 @@ func TestBuildHealthCheckResponseList(t *testing.T) { func TestHealthCheckHandlerReturnsJSON(t *testing.T) { - governor.AddHealthCheck("database", &SampleDatabaseCheck{}) - governor.AddHealthCheck("cache", &SampleCacheCheck{}) + admin.AddHealthCheck("database", &SampleDatabaseCheck{}) + admin.AddHealthCheck("cache", &SampleCacheCheck{}) req, err := http.NewRequest("GET", "/healthcheck?json=true", nil) if err != nil { diff --git a/server/web/adminui.go b/server/web/adminui.go index de8c9455..54d67354 100644 --- a/server/web/adminui.go +++ b/server/web/adminui.go @@ -21,7 +21,7 @@ var indexTpl = ` For detail usage please check our document:

-Toolbox +Toolbox

Live Monitor diff --git a/server/web/captcha/README.md b/server/web/captcha/README.md index dbc2026b..74e1cf82 100644 --- a/server/web/captcha/README.md +++ b/server/web/captcha/README.md @@ -6,9 +6,9 @@ an example for use captcha package controllers import ( - "github.com/astaxie/beego" - "github.com/astaxie/beego/cache" - "github.com/astaxie/beego/utils/captcha" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/cache" + "github.com/beego/beego/v2/utils/captcha" ) var cpt *captcha.Captcha diff --git a/server/web/captcha/captcha.go b/server/web/captcha/captcha.go index 8ce832f7..d052af13 100644 --- a/server/web/captcha/captcha.go +++ b/server/web/captcha/captcha.go @@ -19,9 +19,9 @@ // package controllers // // import ( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/cache" -// "github.com/astaxie/beego/utils/captcha" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/cache" +// "github.com/beego/beego/v2/utils/captcha" // ) // // var cpt *captcha.Captcha @@ -67,11 +67,11 @@ import ( "strings" "time" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - "github.com/astaxie/beego/core/utils" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/utils" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) var ( diff --git a/server/web/captcha/image_test.go b/server/web/captcha/image_test.go index 4b4518a1..53e89575 100644 --- a/server/web/captcha/image_test.go +++ b/server/web/captcha/image_test.go @@ -17,7 +17,7 @@ package captcha import ( "testing" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) type byteCounter struct { diff --git a/server/web/config.go b/server/web/config.go index 10138e63..bc411fb2 100644 --- a/server/web/config.go +++ b/server/web/config.go @@ -17,19 +17,20 @@ package web import ( "crypto/tls" "fmt" + "net/http" "os" "path/filepath" "reflect" "runtime" "strings" - "github.com/astaxie/beego" - "github.com/astaxie/beego/core/config" - "github.com/astaxie/beego/core/logs" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/core/config" + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/server/web/session" - "github.com/astaxie/beego/core/utils" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/utils" + "github.com/beego/beego/v2/server/web/context" ) // Config is the main struct for BConfig @@ -116,6 +117,7 @@ type SessionConfig struct { SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers SessionNameInHTTPHeader string SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params + SessionCookieSameSite http.SameSite } // LogConfig holds Log related config @@ -274,6 +276,7 @@ func newBConfig() *Config { SessionEnableSidInHTTPHeader: false, // enable store/get the sessionId into/from http headers SessionNameInHTTPHeader: "Beegosessionid", SessionEnableSidInURLQuery: false, // enable get the sessionId from Url Query params + SessionCookieSameSite: http.SameSiteDefaultMode, }, }, Log: LogConfig{ diff --git a/server/web/config_test.go b/server/web/config_test.go index 0129ebb4..9f8f7a80 100644 --- a/server/web/config_test.go +++ b/server/web/config_test.go @@ -19,7 +19,7 @@ import ( "reflect" "testing" - beeJson "github.com/astaxie/beego/core/config/json" + beeJson "github.com/beego/beego/v2/core/config/json" ) func TestDefaults(t *testing.T) { diff --git a/server/web/context/acceptencoder.go b/server/web/context/acceptencoder.go index 8ed6a853..312e50de 100644 --- a/server/web/context/acceptencoder.go +++ b/server/web/context/acceptencoder.go @@ -65,7 +65,7 @@ type nopResetWriter struct { } func (n nopResetWriter) Reset(w io.Writer) { - //do nothing + // do nothing } type acceptEncoder struct { diff --git a/server/web/context/context.go b/server/web/context/context.go index 53ed3d01..6070c996 100644 --- a/server/web/context/context.go +++ b/server/web/context/context.go @@ -15,7 +15,7 @@ // Package context provide the context utils // Usage: // -// import "github.com/astaxie/beego/context" +// import "github.com/beego/beego/v2/context" // // ctx := context.Context{Request:req,ResponseWriter:rw} // @@ -35,7 +35,7 @@ import ( "strings" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // Commonly used mime-types @@ -149,7 +149,8 @@ func (ctx *Context) XSRFToken(key string, expire int64) string { token, ok := ctx.GetSecureCookie(key, "_xsrf") if !ok { token = string(utils.RandomCreateBytes(32)) - ctx.SetSecureCookie(key, "_xsrf", token, expire, "", "", true, true) + // TODO make it configurable + ctx.SetSecureCookie(key, "_xsrf", token, expire, "", "") } ctx._xsrfToken = token } @@ -221,7 +222,7 @@ func (r *Response) Write(p []byte) (int, error) { // and sets `Started` to true. func (r *Response) WriteHeader(code int) { if r.Status > 0 { - //prevent multiple response.WriteHeader calls + // prevent multiple response.WriteHeader calls return } r.Status = code diff --git a/server/web/context/input.go b/server/web/context/input.go index 504838a3..241ef8bc 100644 --- a/server/web/context/input.go +++ b/server/web/context/input.go @@ -29,7 +29,7 @@ import ( "strings" "sync" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) // Regexes for checking the accept headers diff --git a/server/web/context/output.go b/server/web/context/output.go index a6e83681..aba5e560 100644 --- a/server/web/context/output.go +++ b/server/web/context/output.go @@ -261,15 +261,15 @@ func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error { } // ServeFormatted serves YAML, XML or JSON, depending on the value of the Accept header -func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) { +func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) error { accept := output.Context.Input.Header("Accept") switch accept { case ApplicationYAML: - output.YAML(data) + return output.YAML(data) case ApplicationXML, TextXML: - output.XML(data, hasIndent) + return output.XML(data, hasIndent) default: - output.JSON(data, hasIndent, len(hasEncode) > 0 && hasEncode[0]) + return output.JSON(data, hasIndent, len(hasEncode) > 0 && hasEncode[0]) } } @@ -288,7 +288,7 @@ func (output *BeegoOutput) Download(file string, filename ...string) { } else { fName = filepath.Base(file) } - //https://tools.ietf.org/html/rfc6266#section-4.3 + // https://tools.ietf.org/html/rfc6266#section-4.3 fn := url.PathEscape(fName) if fName == fn { fn = "filename=" + fn diff --git a/server/web/context/param/conv.go b/server/web/context/param/conv.go index fe3388b6..eecb6acb 100644 --- a/server/web/context/param/conv.go +++ b/server/web/context/param/conv.go @@ -4,8 +4,8 @@ import ( "fmt" "reflect" - "github.com/astaxie/beego/core/logs" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/logs" + beecontext "github.com/beego/beego/v2/server/web/context" ) // ConvertParams converts http method params to values that will be passed to the method controller as arguments diff --git a/server/web/context/param/methodparams.go b/server/web/context/param/methodparams.go index b5ccbdd0..22ff0e43 100644 --- a/server/web/context/param/methodparams.go +++ b/server/web/context/param/methodparams.go @@ -5,7 +5,7 @@ import ( "strings" ) -//MethodParam keeps param information to be auto passed to controller methods +// MethodParam keeps param information to be auto passed to controller methods type MethodParam struct { name string in paramType diff --git a/server/web/context/param/parsers.go b/server/web/context/param/parsers.go index 421aecf0..fb4099f5 100644 --- a/server/web/context/param/parsers.go +++ b/server/web/context/param/parsers.go @@ -18,7 +18,7 @@ func getParser(param *MethodParam, t reflect.Type) paramParser { reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return intParser{} case reflect.Slice: - if t.Elem().Kind() == reflect.Uint8 { //treat []byte as string + if t.Elem().Kind() == reflect.Uint8 { // treat []byte as string return stringParser{} } if param.in == body { diff --git a/server/web/context/param/parsers_test.go b/server/web/context/param/parsers_test.go index 81a821f1..7d4c9661 100644 --- a/server/web/context/param/parsers_test.go +++ b/server/web/context/param/parsers_test.go @@ -14,40 +14,40 @@ type testDefinition struct { func Test_Parsers(t *testing.T) { - //ints + // ints checkParser(testDefinition{"1", 1, intParser{}}, t) checkParser(testDefinition{"-1", int64(-1), intParser{}}, t) checkParser(testDefinition{"1", uint64(1), intParser{}}, t) - //floats + // floats checkParser(testDefinition{"1.0", float32(1.0), floatParser{}}, t) checkParser(testDefinition{"-1.0", float64(-1.0), floatParser{}}, t) - //strings + // strings checkParser(testDefinition{"AB", "AB", stringParser{}}, t) checkParser(testDefinition{"AB", []byte{65, 66}, stringParser{}}, t) - //bools + // bools checkParser(testDefinition{"true", true, boolParser{}}, t) checkParser(testDefinition{"0", false, boolParser{}}, t) - //timeParser + // timeParser checkParser(testDefinition{"2017-05-30T13:54:53Z", time.Date(2017, 5, 30, 13, 54, 53, 0, time.UTC), timeParser{}}, t) checkParser(testDefinition{"2017-05-30", time.Date(2017, 5, 30, 0, 0, 0, 0, time.UTC), timeParser{}}, t) - //json + // json checkParser(testDefinition{`{"X": 5, "Y":"Z"}`, struct { X int Y string }{5, "Z"}, jsonParser{}}, t) - //slice in query is parsed as comma delimited + // slice in query is parsed as comma delimited checkParser(testDefinition{`1,2`, []int{1, 2}, sliceParser(intParser{})}, t) - //slice in body is parsed as json + // slice in body is parsed as json checkParser(testDefinition{`["a","b"]`, []string{"a", "b"}, jsonParser{}}, t, MethodParam{in: body}) - //pointers + // pointers var someInt = 1 checkParser(testDefinition{`1`, &someInt, ptrParser(intParser{})}, t) diff --git a/server/web/context/response.go b/server/web/context/response.go index 7bd9a7e8..86b2c0b8 100644 --- a/server/web/context/response.go +++ b/server/web/context/response.go @@ -6,10 +6,10 @@ import ( ) const ( - //BadRequest indicates HTTP error 400 + // BadRequest indicates HTTP error 400 BadRequest StatusCode = http.StatusBadRequest - //NotFound indicates HTTP error 404 + // NotFound indicates HTTP error 404 NotFound StatusCode = http.StatusNotFound ) diff --git a/server/web/controller.go b/server/web/controller.go index 3a1b9837..5983cfbd 100644 --- a/server/web/controller.go +++ b/server/web/controller.go @@ -16,6 +16,7 @@ package web import ( "bytes" + context2 "context" "errors" "fmt" "html/template" @@ -28,10 +29,10 @@ import ( "strconv" "strings" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" - "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/context/param" + "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/context/param" ) var ( @@ -250,13 +251,16 @@ func (c *Controller) Render() error { // RenderString returns the rendered template string. Do not send out response. func (c *Controller) RenderString() (string, error) { b, e := c.RenderBytes() + if e != nil { + return "", e + } return string(b), e } // RenderBytes returns the bytes of rendered template string. Do not send out response. func (c *Controller) RenderBytes() ([]byte, error) { buf, err := c.renderTemplate() - //if the controller has set layout, then first get the tplName's content set the content to the layout + // if the controller has set layout, then first get the tplName's content set the content to the layout if err == nil && c.Layout != "" { c.Data["LayoutContent"] = template.HTML(buf.String()) @@ -276,7 +280,7 @@ func (c *Controller) RenderBytes() ([]byte, error) { } buf.Reset() - ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data) + err = ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data) } return buf.Bytes(), err } @@ -373,50 +377,57 @@ func (c *Controller) URLFor(endpoint string, values ...interface{}) string { } // ServeJSON sends a json response with encoding charset. -func (c *Controller) ServeJSON(encoding ...bool) { +func (c *Controller) ServeJSON(encoding ...bool) error { var ( hasIndent = BConfig.RunMode != PROD hasEncoding = len(encoding) > 0 && encoding[0] ) - c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding) + return c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding) } // ServeJSONP sends a jsonp response. -func (c *Controller) ServeJSONP() { +func (c *Controller) ServeJSONP() error { hasIndent := BConfig.RunMode != PROD - c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent) + return c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent) } // ServeXML sends xml response. -func (c *Controller) ServeXML() { +func (c *Controller) ServeXML() error { hasIndent := BConfig.RunMode != PROD - c.Ctx.Output.XML(c.Data["xml"], hasIndent) + return c.Ctx.Output.XML(c.Data["xml"], hasIndent) } // ServeYAML sends yaml response. -func (c *Controller) ServeYAML() { - c.Ctx.Output.YAML(c.Data["yaml"]) +func (c *Controller) ServeYAML() error { + return c.Ctx.Output.YAML(c.Data["yaml"]) } // ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header -func (c *Controller) ServeFormatted(encoding ...bool) { +func (c *Controller) ServeFormatted(encoding ...bool) error { hasIndent := BConfig.RunMode != PROD hasEncoding := len(encoding) > 0 && encoding[0] - c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding) + return c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding) } // Input returns the input data map from POST or PUT request body and query string. -func (c *Controller) Input() url.Values { +func (c *Controller) Input() (url.Values, error) { if c.Ctx.Request.Form == nil { - c.Ctx.Request.ParseForm() + err := c.Ctx.Request.ParseForm() + if err != nil { + return nil, err + } } - return c.Ctx.Request.Form + return c.Ctx.Request.Form, nil } // ParseForm maps input data map to obj struct. func (c *Controller) ParseForm(obj interface{}) error { - return ParseForm(c.Input(), obj) + form, err := c.Input() + if err != nil { + return err + } + return ParseForm(form, obj) } // GetString returns the input value by key string or the default value while it's present and input is blank @@ -438,7 +449,7 @@ func (c *Controller) GetStrings(key string, def ...[]string) []string { defv = def[0] } - if f := c.Input(); f == nil { + if f, err := c.Input(); f == nil || err != nil { return defv } else if vs := f[key]; len(vs) > 0 { return vs @@ -618,11 +629,11 @@ func (c *Controller) StartSession() session.Store { } // SetSession puts value into session. -func (c *Controller) SetSession(name interface{}, value interface{}) { +func (c *Controller) SetSession(name interface{}, value interface{}) error { if c.CruSession == nil { c.StartSession() } - c.CruSession.Set(nil, name, value) + return c.CruSession.Set(context2.Background(), name, value) } // GetSession gets value from session. @@ -630,32 +641,38 @@ func (c *Controller) GetSession(name interface{}) interface{} { if c.CruSession == nil { c.StartSession() } - return c.CruSession.Get(nil, name) + return c.CruSession.Get(context2.Background(), name) } // DelSession removes value from session. -func (c *Controller) DelSession(name interface{}) { +func (c *Controller) DelSession(name interface{}) error { if c.CruSession == nil { c.StartSession() } - c.CruSession.Delete(nil, name) + return c.CruSession.Delete(context2.Background(), name) } // SessionRegenerateID regenerates session id for this session. // the session data have no changes. -func (c *Controller) SessionRegenerateID() { +func (c *Controller) SessionRegenerateID() error { if c.CruSession != nil { - c.CruSession.SessionRelease(nil, c.Ctx.ResponseWriter) + c.CruSession.SessionRelease(context2.Background(), c.Ctx.ResponseWriter) } - c.CruSession = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request) + var err error + c.CruSession, err = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request) c.Ctx.Input.CruSession = c.CruSession + return err } // DestroySession cleans session data and session cookie. -func (c *Controller) DestroySession() { - c.Ctx.Input.CruSession.Flush(nil) +func (c *Controller) DestroySession() error { + err := c.Ctx.Input.CruSession.Flush(nil) + if err != nil { + return err + } c.Ctx.Input.CruSession = nil GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request) + return nil } // IsAjax returns this request is ajax or not. diff --git a/server/web/controller_test.go b/server/web/controller_test.go index 0b711e0d..4f8b6d1c 100644 --- a/server/web/controller_test.go +++ b/server/web/controller_test.go @@ -21,9 +21,7 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/assert" - - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) func TestGetInt(t *testing.T) { @@ -46,7 +44,7 @@ func TestGetInt8(t *testing.T) { if val != 40 { t.Errorf("TestGetInt8 expect 40,get %T,%v", val, val) } - //Output: int8 + // Output: int8 } func TestGetInt16(t *testing.T) { @@ -127,10 +125,9 @@ func TestGetUint64(t *testing.T) { } func TestAdditionalViewPaths(t *testing.T) { - wkdir, err := os.Getwd() - assert.Nil(t, err) - dir1 := filepath.Join(wkdir, "_beeTmp", "TestAdditionalViewPaths") - dir2 := filepath.Join(wkdir, "_beeTmp2", "TestAdditionalViewPaths") + tmpDir := os.TempDir() + dir1 := filepath.Join(tmpDir, "_beeTmp", "TestAdditionalViewPaths") + dir2 := filepath.Join(tmpDir, "_beeTmp2", "TestAdditionalViewPaths") defer os.RemoveAll(dir1) defer os.RemoveAll(dir2) diff --git a/server/web/doc.go b/server/web/doc.go index a32bc576..48c21342 100644 --- a/server/web/doc.go +++ b/server/web/doc.go @@ -6,7 +6,7 @@ It is used for rapid development of RESTful APIs, web apps and backend services beego is inspired by Tornado, Sinatra and Flask with the added benefit of some Go-specific features such as interfaces and struct embedding. package main - import "github.com/astaxie/beego" + import "github.com/beego/beego/v2" func main() { beego.Run() diff --git a/server/web/error.go b/server/web/error.go index b5ef1d2d..85ae5c8c 100644 --- a/server/web/error.go +++ b/server/web/error.go @@ -23,10 +23,10 @@ import ( "strconv" "strings" - "github.com/astaxie/beego" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/core/utils" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) const ( @@ -444,13 +444,13 @@ func exception(errCode string, ctx *context.Context) { return } } - //if 50x error has been removed from errorMap + // if 50x error has been removed from errorMap ctx.ResponseWriter.WriteHeader(atoi(errCode)) ctx.WriteString(errCode) } func executeError(err *errorInfo, ctx *context.Context, code int) { - //make sure to log the error in the access log + // make sure to log the error in the access log LogAccess(ctx, nil, code) if err.errorType == errorTypeHandler { @@ -460,16 +460,16 @@ func executeError(err *errorInfo, ctx *context.Context, code int) { } if err.errorType == errorTypeController { ctx.Output.SetStatus(code) - //Invoke the request handler + // Invoke the request handler vc := reflect.New(err.controllerType) execController, ok := vc.Interface().(ControllerInterface) if !ok { panic("controller is not ControllerInterface") } - //call the controller init function + // call the controller init function execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface()) - //call prepare function + // call prepare function execController.Prepare() execController.URLMapping() @@ -477,7 +477,7 @@ func executeError(err *errorInfo, ctx *context.Context, code int) { method := vc.MethodByName(err.method) method.Call([]reflect.Value{}) - //render template + // render template if BConfig.WebConfig.AutoRender { if err := execController.Render(); err != nil { panic(err) diff --git a/server/web/filter.go b/server/web/filter.go index 967de8c9..0baa269f 100644 --- a/server/web/filter.go +++ b/server/web/filter.go @@ -17,7 +17,7 @@ package web import ( "strings" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // FilterChain is different from pure FilterFunc diff --git a/server/web/filter/apiauth/apiauth.go b/server/web/filter/apiauth/apiauth.go index 58153f1d..9e6c30dc 100644 --- a/server/web/filter/apiauth/apiauth.go +++ b/server/web/filter/apiauth/apiauth.go @@ -16,8 +16,8 @@ // // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/apiauth" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/apiauth" // ) // // func main(){ @@ -65,8 +65,8 @@ import ( "sort" "time" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) // AppIDToAppSecret gets appsecret through appid diff --git a/server/web/filter/auth/basic.go b/server/web/filter/auth/basic.go index ee6af6c3..5a01f260 100644 --- a/server/web/filter/auth/basic.go +++ b/server/web/filter/auth/basic.go @@ -15,8 +15,8 @@ // Package auth provides handlers to enable basic auth support. // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/auth" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/auth" // ) // // func main(){ @@ -40,8 +40,8 @@ import ( "net/http" "strings" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) var defaultRealm = "Authorization Required" diff --git a/server/web/filter/authz/authz.go b/server/web/filter/authz/authz.go index 857c52f2..8009c976 100644 --- a/server/web/filter/authz/authz.go +++ b/server/web/filter/authz/authz.go @@ -15,8 +15,8 @@ // Package authz provides handlers to enable ACL, RBAC, ABAC authorization support. // Simple Usage: // import( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/authz" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/authz" // "github.com/casbin/casbin" // ) // @@ -44,8 +44,8 @@ import ( "github.com/casbin/casbin" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) // NewAuthorizer returns the authorizer. diff --git a/server/web/filter/authz/authz_model.conf b/server/web/filter/authz/authz_model.conf index d1b3dbd7..fd2f08df 100644 --- a/server/web/filter/authz/authz_model.conf +++ b/server/web/filter/authz/authz_model.conf @@ -11,4 +11,4 @@ g = _, _ e = some(where (p.eft == allow)) [matchers] -m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") \ No newline at end of file +m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") diff --git a/server/web/filter/authz/authz_policy.csv b/server/web/filter/authz/authz_policy.csv index c062dd3e..9203e11f 100644 --- a/server/web/filter/authz/authz_policy.csv +++ b/server/web/filter/authz/authz_policy.csv @@ -4,4 +4,4 @@ p, bob, /dataset2/resource1, * p, bob, /dataset2/resource2, GET p, bob, /dataset2/folder1/*, POST p, dataset1_admin, /dataset1/*, * -g, cathy, dataset1_admin \ No newline at end of file +g, cathy, dataset1_admin diff --git a/server/web/filter/authz/authz_test.go b/server/web/filter/authz/authz_test.go index c0d0dde5..37153954 100644 --- a/server/web/filter/authz/authz_test.go +++ b/server/web/filter/authz/authz_test.go @@ -21,9 +21,9 @@ import ( "github.com/casbin/casbin" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/filter/auth" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/filter/auth" ) func testRequest(t *testing.T, handler *web.ControllerRegister, user string, path string, method string, code int) { diff --git a/server/web/filter/cors/cors.go b/server/web/filter/cors/cors.go index 3a6905ea..0eb9aa30 100644 --- a/server/web/filter/cors/cors.go +++ b/server/web/filter/cors/cors.go @@ -15,8 +15,8 @@ // Package cors provides handlers to enable CORS support. // Usage // import ( -// "github.com/astaxie/beego" -// "github.com/astaxie/beego/plugins/cors" +// "github.com/beego/beego/v2" +// "github.com/beego/beego/v2/plugins/cors" // ) // // func main() { @@ -42,8 +42,8 @@ import ( "strings" "time" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) const ( diff --git a/server/web/filter/cors/cors_test.go b/server/web/filter/cors/cors_test.go index 7649de25..e907a202 100644 --- a/server/web/filter/cors/cors_test.go +++ b/server/web/filter/cors/cors_test.go @@ -21,8 +21,8 @@ import ( "testing" "time" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) // HTTPHeaderGuardRecorder is httptest.ResponseRecorder with own http.Header diff --git a/server/web/filter/opentracing/filter.go b/server/web/filter/opentracing/filter.go index c2defa18..641136fc 100644 --- a/server/web/filter/opentracing/filter.go +++ b/server/web/filter/opentracing/filter.go @@ -17,11 +17,12 @@ package opentracing import ( "context" - "github.com/astaxie/beego/server/web" - beegoCtx "github.com/astaxie/beego/server/web/context" logKit "github.com/go-kit/kit/log" opentracingKit "github.com/go-kit/kit/tracing/opentracing" "github.com/opentracing/opentracing-go" + + "github.com/beego/beego/v2/server/web" + beegoCtx "github.com/beego/beego/v2/server/web/context" ) // FilterChainBuilder provides an extension point that we can support more configurations if necessary diff --git a/server/web/filter/opentracing/filter_test.go b/server/web/filter/opentracing/filter_test.go index d7222c37..d92c98a1 100644 --- a/server/web/filter/opentracing/filter_test.go +++ b/server/web/filter/opentracing/filter_test.go @@ -22,7 +22,7 @@ import ( "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) func TestFilterChainBuilder_FilterChain(t *testing.T) { diff --git a/server/web/filter/prometheus/filter.go b/server/web/filter/prometheus/filter.go index 7daabd5a..59a673ac 100644 --- a/server/web/filter/prometheus/filter.go +++ b/server/web/filter/prometheus/filter.go @@ -21,9 +21,9 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/astaxie/beego" - "github.com/astaxie/beego/server/web" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2" + "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context" ) // FilterChainBuilder is an extension point, @@ -43,7 +43,7 @@ func (builder *FilterChainBuilder) FilterChain(next web.FilterFunc) web.FilterFu "appname": web.BConfig.AppName, }, Help: "The statics info for http request", - }, []string{"pattern", "method", "status", "duration"}) + }, []string{"pattern", "method", "status"}) prometheus.MustRegister(summaryVec) @@ -83,5 +83,5 @@ func report(dur time.Duration, ctx *context.Context, vec *prometheus.SummaryVec) status := ctx.Output.Status ptn := ctx.Input.GetData("RouterPattern").(string) ms := dur / time.Millisecond - vec.WithLabelValues(ptn, ctx.Input.Method(), strconv.Itoa(status), strconv.Itoa(int(ms))).Observe(float64(ms)) + vec.WithLabelValues(ptn, ctx.Input.Method(), strconv.Itoa(status)).Observe(float64(ms)) } diff --git a/server/web/filter/prometheus/filter_test.go b/server/web/filter/prometheus/filter_test.go index cb133a64..f00f20e7 100644 --- a/server/web/filter/prometheus/filter_test.go +++ b/server/web/filter/prometheus/filter_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) func TestFilterChain(t *testing.T) { diff --git a/server/web/filter_chain_test.go b/server/web/filter_chain_test.go index e175ab29..2a428b78 100644 --- a/server/web/filter_chain_test.go +++ b/server/web/filter_chain_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) func TestControllerRegister_InsertFilterChain(t *testing.T) { diff --git a/server/web/filter_test.go b/server/web/filter_test.go index 11f575d6..8765243c 100644 --- a/server/web/filter_test.go +++ b/server/web/filter_test.go @@ -19,7 +19,7 @@ import ( "net/http/httptest" "testing" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) var FilterUser = func(ctx *context.Context) { diff --git a/server/web/flash.go b/server/web/flash.go index 55f6435d..4b6567ac 100644 --- a/server/web/flash.go +++ b/server/web/flash.go @@ -102,7 +102,7 @@ func ReadFromRequest(c *Controller) *FlashData { } } } - //read one time then delete it + // read one time then delete it c.Ctx.SetCookie(BConfig.WebConfig.FlashName, "", -1, "/") } c.Data["flash"] = flash.Data diff --git a/server/web/flash_test.go b/server/web/flash_test.go index 2deef54e..c1ca9554 100644 --- a/server/web/flash_test.go +++ b/server/web/flash_test.go @@ -40,7 +40,7 @@ func TestFlashHeader(t *testing.T) { // setup the handler handler := NewControllerRegister() - handler.Add("/", &TestFlashController{}, "get:TestWriteFlash") + handler.Add("/", &TestFlashController{}, SetRouterMethods(&TestFlashController{}, "get:TestWriteFlash")) handler.ServeHTTP(w, r) // get the Set-Cookie value diff --git a/server/web/grace/grace.go b/server/web/grace/grace.go index fb0cb7bb..0adc8654 100644 --- a/server/web/grace/grace.go +++ b/server/web/grace/grace.go @@ -22,7 +22,7 @@ // "net/http" // "os" // -// "github.com/astaxie/beego/grace" +// "github.com/beego/beego/v2/grace" // ) // // func handler(w http.ResponseWriter, r *http.Request) { @@ -138,7 +138,7 @@ func NewServer(addr string, handler http.Handler) (srv *Server) { }, state: StateInit, Network: "tcp", - terminalChan: make(chan error), //no cache channel + terminalChan: make(chan error), // no cache channel } srv.Server = &http.Server{ Addr: addr, diff --git a/server/web/hooks.go b/server/web/hooks.go index 58e2c0f3..ae32b9f8 100644 --- a/server/web/hooks.go +++ b/server/web/hooks.go @@ -6,9 +6,9 @@ import ( "net/http" "path/filepath" - "github.com/astaxie/beego/core/logs" - "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/session" ) // register MIME type with content type @@ -61,6 +61,7 @@ func registerSession() error { conf.EnableSidInHTTPHeader = BConfig.WebConfig.Session.SessionEnableSidInHTTPHeader conf.SessionNameInHTTPHeader = BConfig.WebConfig.Session.SessionNameInHTTPHeader conf.EnableSidInURLQuery = BConfig.WebConfig.Session.SessionEnableSidInURLQuery + conf.CookieSameSite = BConfig.WebConfig.Session.SessionCookieSameSite } else { if err = json.Unmarshal([]byte(sessionConfig), conf); err != nil { return err diff --git a/server/web/namespace.go b/server/web/namespace.go index 58afb6c7..3598a222 100644 --- a/server/web/namespace.go +++ b/server/web/namespace.go @@ -18,7 +18,7 @@ import ( "net/http" "strings" - beecontext "github.com/astaxie/beego/server/web/context" + beecontext "github.com/beego/beego/v2/server/web/context" ) type namespaceCond func(*beecontext.Context) bool @@ -97,91 +97,91 @@ func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace { } // Router same as beego.Rourer -// refer: https://godoc.org/github.com/astaxie/beego#Router +// refer: https://godoc.org/github.com/beego/beego/v2#Router func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace { - n.handlers.Add(rootpath, c, mappingMethods...) + n.handlers.Add(rootpath, c, SetRouterMethods(c, mappingMethods...)) return n } // AutoRouter same as beego.AutoRouter -// refer: https://godoc.org/github.com/astaxie/beego#AutoRouter +// refer: https://godoc.org/github.com/beego/beego/v2#AutoRouter func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace { n.handlers.AddAuto(c) return n } // AutoPrefix same as beego.AutoPrefix -// refer: https://godoc.org/github.com/astaxie/beego#AutoPrefix +// refer: https://godoc.org/github.com/beego/beego/v2#AutoPrefix func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace { n.handlers.AddAutoPrefix(prefix, c) return n } // Get same as beego.Get -// refer: https://godoc.org/github.com/astaxie/beego#Get +// refer: https://godoc.org/github.com/beego/beego/v2#Get func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace { n.handlers.Get(rootpath, f) return n } // Post same as beego.Post -// refer: https://godoc.org/github.com/astaxie/beego#Post +// refer: https://godoc.org/github.com/beego/beego/v2#Post func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace { n.handlers.Post(rootpath, f) return n } // Delete same as beego.Delete -// refer: https://godoc.org/github.com/astaxie/beego#Delete +// refer: https://godoc.org/github.com/beego/beego/v2#Delete func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace { n.handlers.Delete(rootpath, f) return n } // Put same as beego.Put -// refer: https://godoc.org/github.com/astaxie/beego#Put +// refer: https://godoc.org/github.com/beego/beego/v2#Put func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace { n.handlers.Put(rootpath, f) return n } // Head same as beego.Head -// refer: https://godoc.org/github.com/astaxie/beego#Head +// refer: https://godoc.org/github.com/beego/beego/v2#Head func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace { n.handlers.Head(rootpath, f) return n } // Options same as beego.Options -// refer: https://godoc.org/github.com/astaxie/beego#Options +// refer: https://godoc.org/github.com/beego/beego/v2#Options func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace { n.handlers.Options(rootpath, f) return n } // Patch same as beego.Patch -// refer: https://godoc.org/github.com/astaxie/beego#Patch +// refer: https://godoc.org/github.com/beego/beego/v2#Patch func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace { n.handlers.Patch(rootpath, f) return n } // Any same as beego.Any -// refer: https://godoc.org/github.com/astaxie/beego#Any +// refer: https://godoc.org/github.com/beego/beego/v2#Any func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace { n.handlers.Any(rootpath, f) return n } // Handler same as beego.Handler -// refer: https://godoc.org/github.com/astaxie/beego#Handler +// refer: https://godoc.org/github.com/beego/beego/v2#Handler func (n *Namespace) Handler(rootpath string, h http.Handler) *Namespace { n.handlers.Handler(rootpath, h) return n } // Include add include class -// refer: https://godoc.org/github.com/astaxie/beego#Include +// refer: https://godoc.org/github.com/beego/beego/v2#Include func (n *Namespace) Include(cList ...ControllerInterface) *Namespace { n.handlers.Include(cList...) return n @@ -189,8 +189,8 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace { // Namespace add nest Namespace // usage: -//ns := beego.NewNamespace(“/v1”). -//Namespace( +// ns := beego.NewNamespace(“/v1”). +// Namespace( // beego.NewNamespace("/shop"). // Get("/:id", func(ctx *context.Context) { // ctx.Output.Body([]byte("shopinfo")) @@ -203,7 +203,7 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace { // Get("/:id", func(ctx *context.Context) { // ctx.Output.Body([]byte("crminfo")) // }), -//) +// ) func (n *Namespace) Namespace(ns ...*Namespace) *Namespace { for _, ni := range ns { for k, v := range ni.handlers.routers { diff --git a/server/web/namespace_test.go b/server/web/namespace_test.go index a6f87bba..05042c96 100644 --- a/server/web/namespace_test.go +++ b/server/web/namespace_test.go @@ -20,7 +20,7 @@ import ( "strconv" "testing" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) func TestNamespaceGet(t *testing.T) { diff --git a/server/web/pagination/controller.go b/server/web/pagination/controller.go index f6b2f73d..d1299768 100644 --- a/server/web/pagination/controller.go +++ b/server/web/pagination/controller.go @@ -15,8 +15,8 @@ package pagination import ( - "github.com/astaxie/beego/core/utils/pagination" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/utils/pagination" + "github.com/beego/beego/v2/server/web/context" ) // SetPaginator Instantiates a Paginator and assigns it to context.Input.Data("paginator"). diff --git a/server/web/parser.go b/server/web/parser.go index 820c8b10..6d87207c 100644 --- a/server/web/parser.go +++ b/server/web/parser.go @@ -30,17 +30,17 @@ import ( "golang.org/x/tools/go/packages" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - "github.com/astaxie/beego/core/utils" - "github.com/astaxie/beego/server/web/context/param" + "github.com/beego/beego/v2/core/utils" + "github.com/beego/beego/v2/server/web/context/param" ) var globalRouterTemplate = `package {{.routersDir}} import ( - "github.com/astaxie/beego" - "github.com/astaxie/beego/server/web/context/param"{{.globalimport}} + beego "github.com/beego/beego/v2/server/web" + "github.com/beego/beego/v2/server/web/context/param"{{.globalimport}} ) func init() { @@ -50,7 +50,6 @@ func init() { var ( lastupdateFilename = "lastupdate.tmp" - commentFilename string pkgLastupdate map[string]int64 genInfoList map[string][]ControllerComments @@ -71,16 +70,13 @@ var ( } ) -const commentPrefix = "commentsRouter_" +const commentFilename = "commentsRouter.go" func init() { pkgLastupdate = make(map[string]int64) } func parserPkg(pkgRealpath string) error { - rep := strings.NewReplacer("\\", "_", "/", "_", ".", "_") - commentFilename, _ = filepath.Rel(AppPath, pkgRealpath) - commentFilename = commentPrefix + rep.Replace(commentFilename) + ".go" if !compareFile(pkgRealpath) { logs.Info(pkgRealpath + " no changed") return nil @@ -102,7 +98,10 @@ func parserPkg(pkgRealpath string) error { if specDecl.Recv != nil { exp, ok := specDecl.Recv.List[0].Type.(*ast.StarExpr) // Check that the type is correct first beforing throwing to parser if ok { - parserComments(specDecl, fmt.Sprint(exp.X), pkg.PkgPath) + err = parserComments(specDecl, fmt.Sprint(exp.X), pkg.PkgPath) + if err != nil { + return err + } } } } @@ -500,7 +499,8 @@ func genRouterCode(pkgRealpath string) { beego.GlobalControllerRouter["` + k + `"] = append(beego.GlobalControllerRouter["` + k + `"], beego.ControllerComments{ Method: "` + strings.TrimSpace(c.Method) + `", - ` + `Router: "` + c.Router + `"` + `, + + ` + "Router: `" + c.Router + "`" + `, AllowHTTPMethods: ` + allmethod + `, MethodParams: ` + methodParams + `, Filters: ` + filters + `, @@ -584,17 +584,6 @@ func getpathTime(pkgRealpath string) (lastupdate int64, err error) { func getRouterDir(pkgRealpath string) string { dir := filepath.Dir(pkgRealpath) - for { - routersDir := AppConfig.DefaultString("routersdir", "routers") - d := filepath.Join(dir, routersDir) - if utils.FileExists(d) { - return d - } - - if r, _ := filepath.Rel(dir, AppPath); r == "." { - return d - } - // Parent dir. - dir = filepath.Dir(dir) - } + routersDir := AppConfig.DefaultString("routersdir", "routers") + return filepath.Join(dir, routersDir) } diff --git a/server/web/parser_test.go b/server/web/parser_test.go new file mode 100644 index 00000000..1f34d8d8 --- /dev/null +++ b/server/web/parser_test.go @@ -0,0 +1,34 @@ +// Copyright 2020 beego +// +// 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 web + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_getRouterDir(t *testing.T) { + pkg := filepath.Dir(os.TempDir()) + + res := getRouterDir(pkg) + assert.Equal(t, filepath.Join(pkg, "routers"), res) + AppConfig.Set("routersdir", "cus_routers") + res = getRouterDir(pkg) + assert.Equal(t, filepath.Join(pkg, "cus_routers"), res) + +} diff --git a/server/web/policy.go b/server/web/policy.go index 14673422..1b810520 100644 --- a/server/web/policy.go +++ b/server/web/policy.go @@ -17,7 +17,7 @@ package web import ( "strings" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) // PolicyFunc defines a policy function which is invoked before the controller handler is executed. diff --git a/server/web/router.go b/server/web/router.go index 7bb89d82..ba85ad6e 100644 --- a/server/web/router.go +++ b/server/web/router.go @@ -25,11 +25,11 @@ import ( "sync" "time" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - "github.com/astaxie/beego/core/utils" - beecontext "github.com/astaxie/beego/server/web/context" - "github.com/astaxie/beego/server/web/context/param" + "github.com/beego/beego/v2/core/utils" + beecontext "github.com/beego/beego/v2/server/web/context" + "github.com/beego/beego/v2/server/web/context/param" ) // default filter execution points @@ -118,12 +118,27 @@ type ControllerInfo struct { routerType int initialize func() ControllerInterface methodParams []*param.MethodParam + sessionOn bool } +type ControllerOptions func(*ControllerInfo) + func (c *ControllerInfo) GetPattern() string { return c.pattern } +func SetRouterMethods(ctrlInterface ControllerInterface, mappingMethod ...string) ControllerOptions { + return func(c *ControllerInfo) { + c.methods = parseMappingMethods(ctrlInterface, mappingMethod) + } +} + +func SetRouterSessionOn(sessionOn bool) ControllerOptions { + return func(c *ControllerInfo) { + c.sessionOn = sessionOn + } +} + // ControllerRegister containers registered router rules, controller handlers and filters. type ControllerRegister struct { routers map[string]*Tree @@ -171,40 +186,67 @@ func NewControllerRegisterWithCfg(cfg *Config) *ControllerRegister { // Add("/api/delete",&RestController{},"delete:DeleteFood") // Add("/api",&RestController{},"get,post:ApiFunc" // Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc") -func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) { - p.addWithMethodParams(pattern, c, nil, mappingMethods...) +func (p *ControllerRegister) Add(pattern string, c ControllerInterface, opts ...ControllerOptions) { + p.addWithMethodParams(pattern, c, nil, opts...) } -func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, mappingMethods ...string) { +func parseMappingMethods(c ControllerInterface, mappingMethods []string) map[string]string { reflectVal := reflect.ValueOf(c) t := reflect.Indirect(reflectVal).Type() methods := make(map[string]string) - if len(mappingMethods) > 0 { - semi := strings.Split(mappingMethods[0], ";") - for _, v := range semi { - colon := strings.Split(v, ":") - if len(colon) != 2 { - panic("method mapping format is invalid") + + if len(mappingMethods) == 0 { + return methods + } + + semi := strings.Split(mappingMethods[0], ";") + for _, v := range semi { + colon := strings.Split(v, ":") + if len(colon) != 2 { + panic("method mapping format is invalid") + } + comma := strings.Split(colon[0], ",") + for _, m := range comma { + if m != "*" && !HTTPMETHOD[strings.ToUpper(m)] { + panic(v + " is an invalid method mapping. Method doesn't exist " + m) } - comma := strings.Split(colon[0], ",") - for _, m := range comma { - if m == "*" || HTTPMETHOD[strings.ToUpper(m)] { - if val := reflectVal.MethodByName(colon[1]); val.IsValid() { - methods[strings.ToUpper(m)] = colon[1] - } else { - panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name()) - } - } else { - panic(v + " is an invalid method mapping. Method doesn't exist " + m) - } + if val := reflectVal.MethodByName(colon[1]); val.IsValid() { + methods[strings.ToUpper(m)] = colon[1] + continue } + panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name()) } } + return methods +} + +func (p *ControllerRegister) addRouterForMethod(route *ControllerInfo) { + if len(route.methods) == 0 { + for m := range HTTPMETHOD { + p.addToRouter(m, route.pattern, route) + } + return + } + for k := range route.methods { + if k != "*" { + p.addToRouter(k, route.pattern, route) + continue + } + for m := range HTTPMETHOD { + p.addToRouter(m, route.pattern, route) + } + } +} + +func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, opts ...ControllerOptions) { + reflectVal := reflect.ValueOf(c) + t := reflect.Indirect(reflectVal).Type() + route := &ControllerInfo{} route.pattern = pattern - route.methods = methods route.routerType = routerTypeBeego + route.sessionOn = p.cfg.WebConfig.Session.SessionOn route.controllerType = t route.initialize = func() ControllerInterface { vc := reflect.New(route.controllerType) @@ -229,23 +271,18 @@ func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInt return execController } - route.methodParams = methodParams - if len(methods) == 0 { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - for k := range methods { - if k == "*" { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - p.addToRouter(k, pattern, route) - } - } + for i := range opts { + opts[i](route) } + + globalSessionOn := p.cfg.WebConfig.Session.SessionOn + if !globalSessionOn && route.sessionOn { + logs.Warn("global sessionOn is false, sessionOn of router [%s] can't be set to true", route.pattern) + route.sessionOn = globalSessionOn + } + + p.addRouterForMethod(route) } func (p *ControllerRegister) addToRouter(method, pattern string, r *ControllerInfo) { @@ -274,7 +311,7 @@ func (p *ControllerRegister) Include(cList ...ControllerInterface) { p.InsertFilter(f.Pattern, f.Pos, f.Filter, WithReturnOnOutput(f.ReturnOnOutput), WithResetParams(f.ResetParams)) } - p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method) + p.addWithMethodParams(a.Router, c, a.MethodParams, SetRouterMethods(c, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)) } } } @@ -380,6 +417,7 @@ func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) { route := &ControllerInfo{} route.pattern = pattern route.routerType = routerTypeRESTFul + route.sessionOn = p.cfg.WebConfig.Session.SessionOn route.runFunction = f methods := make(map[string]string) if method == "*" { @@ -391,13 +429,7 @@ func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) { } route.methods = methods for k := range methods { - if k == "*" { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - p.addToRouter(k, pattern, route) - } + p.addToRouter(k, pattern, route) } } @@ -406,6 +438,7 @@ func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ... route := &ControllerInfo{} route.pattern = pattern route.routerType = routerTypeHandler + route.sessionOn = p.cfg.WebConfig.Session.SessionOn route.handler = h if len(options) > 0 { if _, ok := options[0].(bool); ok { @@ -440,6 +473,7 @@ func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) if !utils.InSlice(rt.Method(i).Name, exceptMethod) { route := &ControllerInfo{} route.routerType = routerTypeBeego + route.sessionOn = p.cfg.WebConfig.Session.SessionOn route.methods = map[string]string{"*": rt.Method(i).Name} route.controllerType = ct pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*") @@ -549,7 +583,7 @@ func (p *ControllerRegister) getURL(t *Tree, url, controllerName, methodName str for _, l := range t.leaves { if c, ok := l.runObject.(*ControllerInfo); ok { if c.routerType == routerTypeBeego && - strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), controllerName) { + strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), `/`+controllerName) { find := false if HTTPMETHOD[strings.ToUpper(methodName)] { if len(c.methods) == 0 { @@ -671,12 +705,15 @@ func (p *ControllerRegister) serveHttp(ctx *beecontext.Context) { r := ctx.Request rw := ctx.ResponseWriter.ResponseWriter var ( - runRouter reflect.Type - findRouter bool - runMethod string - methodParams []*param.MethodParam - routerInfo *ControllerInfo - isRunnable bool + runRouter reflect.Type + findRouter bool + runMethod string + methodParams []*param.MethodParam + routerInfo *ControllerInfo + isRunnable bool + currentSessionOn bool + originRouterInfo *ControllerInfo + originFindRouter bool ) if p.cfg.RecoverFunc != nil { @@ -742,7 +779,12 @@ func (p *ControllerRegister) serveHttp(ctx *beecontext.Context) { } // session init - if p.cfg.WebConfig.Session.SessionOn { + currentSessionOn = p.cfg.WebConfig.Session.SessionOn + originRouterInfo, originFindRouter = p.FindRouter(ctx) + if originFindRouter { + currentSessionOn = originRouterInfo.sessionOn + } + if currentSessionOn { ctx.Input.CruSession, err = GlobalSessions.SessionStart(rw, r) if err != nil { logs.Error(err) diff --git a/server/web/router_test.go b/server/web/router_test.go index 59ccd1fc..bd3953ba 100644 --- a/server/web/router_test.go +++ b/server/web/router_test.go @@ -21,11 +21,19 @@ import ( "strings" "testing" - "github.com/astaxie/beego/core/logs" + "github.com/beego/beego/v2/core/logs" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) +type PrefixTestController struct { + Controller +} + +func (ptc *PrefixTestController) PrefixList() { + ptc.Ctx.Output.Body([]byte("i am list in prefix test")) +} + type TestController struct { Controller } @@ -87,10 +95,24 @@ func (jc *JSONController) Get() { jc.Ctx.Output.Body([]byte("ok")) } +func TestPrefixUrlFor(t *testing.T){ + handler := NewControllerRegister() + handler.Add("/my/prefix/list", &PrefixTestController{}, "get:PrefixList") + + if a := handler.URLFor(`PrefixTestController.PrefixList`); a != `/my/prefix/list` { + logs.Info(a) + t.Errorf("PrefixTestController.PrefixList must equal to /my/prefix/list") + } + if a := handler.URLFor(`TestController.PrefixList`); a != `` { + logs.Info(a) + t.Errorf("TestController.PrefixList must equal to empty string") + } +} + func TestUrlFor(t *testing.T) { handler := NewControllerRegister() - handler.Add("/api/list", &TestController{}, "*:List") - handler.Add("/person/:last/:first", &TestController{}, "*:Param") + handler.Add("/api/list", &TestController{}, SetRouterMethods(&TestController{}, "*:List")) + handler.Add("/person/:last/:first", &TestController{}, SetRouterMethods(&TestController{}, "*:Param")) if a := handler.URLFor("TestController.List"); a != "/api/list" { logs.Info(a) t.Errorf("TestController.List must equal to /api/list") @@ -113,9 +135,9 @@ func TestUrlFor3(t *testing.T) { func TestUrlFor2(t *testing.T) { handler := NewControllerRegister() - handler.Add("/v1/:v/cms_:id(.+)_:page(.+).html", &TestController{}, "*:List") - handler.Add("/v1/:username/edit", &TestController{}, "get:GetURL") - handler.Add("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", &TestController{}, "*:Param") + handler.Add("/v1/:v/cms_:id(.+)_:page(.+).html", &TestController{}, SetRouterMethods(&TestController{}, "*:List")) + handler.Add("/v1/:username/edit", &TestController{}, SetRouterMethods(&TestController{}, "get:GetURL")) + handler.Add("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", &TestController{}, SetRouterMethods(&TestController{}, "*:Param")) handler.Add("/:year:int/:month:int/:title/:entid", &TestController{}) if handler.URLFor("TestController.GetURL", ":username", "astaxie") != "/v1/astaxie/edit" { logs.Info(handler.URLFor("TestController.GetURL")) @@ -145,7 +167,7 @@ func TestUserFunc(t *testing.T) { w := httptest.NewRecorder() handler := NewControllerRegister() - handler.Add("/api/list", &TestController{}, "*:List") + handler.Add("/api/list", &TestController{}, SetRouterMethods(&TestController{}, "*:List")) handler.ServeHTTP(w, r) if w.Body.String() != "i am list" { t.Errorf("user define func can't run") @@ -235,7 +257,7 @@ func TestRouteOk(t *testing.T) { w := httptest.NewRecorder() handler := NewControllerRegister() - handler.Add("/person/:last/:first", &TestController{}, "get:GetParams") + handler.Add("/person/:last/:first", &TestController{}, SetRouterMethods(&TestController{}, "get:GetParams")) handler.ServeHTTP(w, r) body := w.Body.String() if body != "anderson+thomas+kungfu" { @@ -249,7 +271,7 @@ func TestManyRoute(t *testing.T) { w := httptest.NewRecorder() handler := NewControllerRegister() - handler.Add("/beego:id([0-9]+)-:page([0-9]+).html", &TestController{}, "get:GetManyRouter") + handler.Add("/beego:id([0-9]+)-:page([0-9]+).html", &TestController{}, SetRouterMethods(&TestController{}, "get:GetManyRouter")) handler.ServeHTTP(w, r) body := w.Body.String() @@ -266,7 +288,7 @@ func TestEmptyResponse(t *testing.T) { w := httptest.NewRecorder() handler := NewControllerRegister() - handler.Add("/beego-empty.html", &TestController{}, "get:GetEmptyBody") + handler.Add("/beego-empty.html", &TestController{}, SetRouterMethods(&TestController{}, "get:GetEmptyBody")) handler.ServeHTTP(w, r) if body := w.Body.String(); body != "" { @@ -750,3 +772,59 @@ func TestRouterEntityTooLargeCopyBody(t *testing.T) { t.Errorf("TestRouterRequestEntityTooLarge can't run") } } + +func TestRouterSessionSet(t *testing.T) { + oldGlobalSessionOn := BConfig.WebConfig.Session.SessionOn + defer func() { + BConfig.WebConfig.Session.SessionOn = oldGlobalSessionOn + }() + + // global sessionOn = false, router sessionOn = false + r, _ := http.NewRequest("GET", "/user", nil) + w := httptest.NewRecorder() + handler := NewControllerRegister() + handler.Add("/user", &TestController{}, SetRouterMethods(&TestController{}, "get:Get"), + SetRouterSessionOn(false)) + handler.ServeHTTP(w, r) + if w.Header().Get("Set-Cookie") != "" { + t.Errorf("TestRotuerSessionSet failed") + } + + // global sessionOn = false, router sessionOn = true + r, _ = http.NewRequest("GET", "/user", nil) + w = httptest.NewRecorder() + handler = NewControllerRegister() + handler.Add("/user", &TestController{}, SetRouterMethods(&TestController{}, "get:Get"), + SetRouterSessionOn(true)) + handler.ServeHTTP(w, r) + if w.Header().Get("Set-Cookie") != "" { + t.Errorf("TestRotuerSessionSet failed") + } + + BConfig.WebConfig.Session.SessionOn = true + if err := registerSession(); err != nil { + t.Errorf("register session failed, error: %s", err.Error()) + } + // global sessionOn = true, router sessionOn = false + r, _ = http.NewRequest("GET", "/user", nil) + w = httptest.NewRecorder() + handler = NewControllerRegister() + handler.Add("/user", &TestController{}, SetRouterMethods(&TestController{}, "get:Get"), + SetRouterSessionOn(false)) + handler.ServeHTTP(w, r) + if w.Header().Get("Set-Cookie") != "" { + t.Errorf("TestRotuerSessionSet failed") + } + + // global sessionOn = true, router sessionOn = true + r, _ = http.NewRequest("GET", "/user", nil) + w = httptest.NewRecorder() + handler = NewControllerRegister() + handler.Add("/user", &TestController{}, SetRouterMethods(&TestController{}, "get:Get"), + SetRouterSessionOn(true)) + handler.ServeHTTP(w, r) + if w.Header().Get("Set-Cookie") == "" { + t.Errorf("TestRotuerSessionSet failed") + } + +} diff --git a/server/web/server.go b/server/web/server.go index 25841563..280828ff 100644 --- a/server/web/server.go +++ b/server/web/server.go @@ -31,11 +31,11 @@ import ( "golang.org/x/crypto/acme/autocert" - "github.com/astaxie/beego/core/logs" - beecontext "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/logs" + beecontext "github.com/beego/beego/v2/server/web/context" - "github.com/astaxie/beego/core/utils" - "github.com/astaxie/beego/server/web/grace" + "github.com/beego/beego/v2/core/utils" + "github.com/beego/beego/v2/server/web/grace" ) var ( @@ -266,8 +266,8 @@ func (app *HttpServer) Run(addr string, mws ...MiddleWare) { } // Router see HttpServer.Router -func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *HttpServer { - return BeeApp.Router(rootpath, c, mappingMethods...) +func Router(rootpath string, c ControllerInterface, opts ...ControllerOptions) *HttpServer { + return BeeApp.Router(rootpath, c, opts...) } // Router adds a patterned controller handler to BeeApp. @@ -286,8 +286,8 @@ func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *H // beego.Router("/api/create",&RestController{},"post:CreateFood") // beego.Router("/api/update",&RestController{},"put:UpdateFood") // beego.Router("/api/delete",&RestController{},"delete:DeleteFood") -func (app *HttpServer) Router(rootPath string, c ControllerInterface, mappingMethods ...string) *HttpServer { - app.Handlers.Add(rootPath, c, mappingMethods...) +func (app *HttpServer) Router(rootPath string, c ControllerInterface, opts ...ControllerOptions) *HttpServer { + app.Handlers.Add(rootPath, c, opts...) return app } diff --git a/server/web/session/README.md b/server/web/session/README.md index a5c3bd6d..854fb590 100644 --- a/server/web/session/README.md +++ b/server/web/session/README.md @@ -1,67 +1,66 @@ session ============== -session is a Go session manager. It can use many session providers. Just like the `database/sql` and `database/sql/driver`. +session is a Go session manager. It can use many session providers. Just like the `database/sql` +and `database/sql/driver`. ## How to install? - go get github.com/astaxie/beego/session - + go get github.com/beego/beego/v2/session ## What providers are supported? As of now this session manager support memory, file, Redis and MySQL. - ## How to use it? First you must import it import ( - "github.com/astaxie/beego/session" + "github.com/beego/beego/v2/session" ) Then in you web app init the global session manager - + var globalSessions *session.Manager * Use **memory** as provider: - func init() { - globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":3600}`) - go globalSessions.GC() - } + func init() { + globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":3600}`) + go globalSessions.GC() + } * Use **file** as provider, the last param is the path where you want file to be stored: - func init() { - globalSessions, _ = session.NewManager("file",`{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}`) - go globalSessions.GC() - } + func init() { + globalSessions, _ = session.NewManager("file",`{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}`) + go globalSessions.GC() + } * Use **Redis** as provider, the last param is the Redis conn address,poolsize,password: - func init() { - globalSessions, _ = session.NewManager("redis", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}`) - go globalSessions.GC() - } - -* Use **MySQL** as provider, the last param is the DSN, learn more from [mysql](https://github.com/go-sql-driver/mysql#dsn-data-source-name): + func init() { + globalSessions, _ = session.NewManager("redis", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}`) + go globalSessions.GC() + } - func init() { - globalSessions, _ = session.NewManager( - "mysql", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}`) - go globalSessions.GC() - } +* Use **MySQL** as provider, the last param is the DSN, learn more + from [mysql](https://github.com/go-sql-driver/mysql#dsn-data-source-name): + + func init() { + globalSessions, _ = session.NewManager( + "mysql", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}`) + go globalSessions.GC() + } * Use **Cookie** as provider: - func init() { - globalSessions, _ = session.NewManager( - "cookie", `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`) - go globalSessions.GC() - } - + func init() { + globalSessions, _ = session.NewManager( + "cookie", `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`) + go globalSessions.GC() + } Finally in the handlerfunc you can use it like this @@ -80,14 +79,13 @@ Finally in the handlerfunc you can use it like this } } - ## How to write own provider? When you develop a web app, maybe you want to write own provider because you must meet the requirements. -Writing a provider is easy. You only need to define two struct types -(Session and Provider), which satisfy the interface definition. -Maybe you will find the **memory** provider is a good example. +Writing a provider is easy. You only need to define two struct types +(Session and Provider), which satisfy the interface definition. Maybe you will find the **memory** provider is a good +example. type SessionStore interface { Set(key, value interface{}) error //set session value @@ -108,7 +106,6 @@ Maybe you will find the **memory** provider is a good example. SessionGC() } - ## LICENSE BSD License http://creativecommons.org/licenses/BSD/ diff --git a/server/web/session/couchbase/sess_couchbase.go b/server/web/session/couchbase/sess_couchbase.go index 7f15956a..ea94f501 100644 --- a/server/web/session/couchbase/sess_couchbase.go +++ b/server/web/session/couchbase/sess_couchbase.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/couchbase" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/couchbase" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -41,7 +41,7 @@ import ( couchbase "github.com/couchbase/go-couchbase" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var couchbpder = &Provider{} diff --git a/server/web/session/ledis/ledis_session.go b/server/web/session/ledis/ledis_session.go index 5b930fcd..8e34388b 100644 --- a/server/web/session/ledis/ledis_session.go +++ b/server/web/session/ledis/ledis_session.go @@ -12,7 +12,7 @@ import ( "github.com/ledisdb/ledisdb/config" "github.com/ledisdb/ledisdb/ledis" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var ( diff --git a/server/web/session/memcache/sess_memcache.go b/server/web/session/memcache/sess_memcache.go index 168116ef..3f4c9842 100644 --- a/server/web/session/memcache/sess_memcache.go +++ b/server/web/session/memcache/sess_memcache.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/memcache" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/memcache" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -38,7 +38,7 @@ import ( "strings" "sync" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" "github.com/bradfitz/gomemcache/memcache" ) diff --git a/server/web/session/mysql/sess_mysql.go b/server/web/session/mysql/sess_mysql.go index 89da361d..d76ec287 100644 --- a/server/web/session/mysql/sess_mysql.go +++ b/server/web/session/mysql/sess_mysql.go @@ -28,8 +28,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/mysql" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/mysql" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -47,7 +47,7 @@ import ( "sync" "time" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" // import mysql driver _ "github.com/go-sql-driver/mysql" ) diff --git a/server/web/session/postgres/sess_postgresql.go b/server/web/session/postgres/sess_postgresql.go index a83ac083..7745ff5f 100644 --- a/server/web/session/postgres/sess_postgresql.go +++ b/server/web/session/postgres/sess_postgresql.go @@ -38,8 +38,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/postgresql" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/postgresql" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -57,7 +57,7 @@ import ( "sync" "time" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" // import postgresql Driver _ "github.com/lib/pq" ) diff --git a/server/web/session/redis/sess_redis.go b/server/web/session/redis/sess_redis.go index c6e3bcbb..e3d38be3 100644 --- a/server/web/session/redis/sess_redis.go +++ b/server/web/session/redis/sess_redis.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -43,7 +43,7 @@ import ( "github.com/go-redis/redis/v7" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var redispder = &Provider{} diff --git a/server/web/session/redis/sess_redis_test.go b/server/web/session/redis/sess_redis_test.go index 64dbc9f9..fe5c363b 100644 --- a/server/web/session/redis/sess_redis_test.go +++ b/server/web/session/redis/sess_redis_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) func TestRedis(t *testing.T) { diff --git a/server/web/session/redis_cluster/redis_cluster.go b/server/web/session/redis_cluster/redis_cluster.go index d2971e71..e94dccc3 100644 --- a/server/web/session/redis_cluster/redis_cluster.go +++ b/server/web/session/redis_cluster/redis_cluster.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis_cluster" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis_cluster" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -43,7 +43,7 @@ import ( rediss "github.com/go-redis/redis/v7" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var redispder = &Provider{} diff --git a/server/web/session/redis_sentinel/sess_redis_sentinel.go b/server/web/session/redis_sentinel/sess_redis_sentinel.go index 89d73b86..2d64c6b4 100644 --- a/server/web/session/redis_sentinel/sess_redis_sentinel.go +++ b/server/web/session/redis_sentinel/sess_redis_sentinel.go @@ -20,8 +20,8 @@ // // Usage: // import( -// _ "github.com/astaxie/beego/session/redis_sentinel" -// "github.com/astaxie/beego/session" +// _ "github.com/beego/beego/v2/session/redis_sentinel" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -43,7 +43,7 @@ import ( "github.com/go-redis/redis/v7" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var redispder = &Provider{} diff --git a/server/web/session/redis_sentinel/sess_redis_sentinel_test.go b/server/web/session/redis_sentinel/sess_redis_sentinel_test.go index f052a14a..0a8030ce 100644 --- a/server/web/session/redis_sentinel/sess_redis_sentinel_test.go +++ b/server/web/session/redis_sentinel/sess_redis_sentinel_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) func TestRedisSentinel(t *testing.T) { diff --git a/server/web/session/sess_mem.go b/server/web/session/sess_mem.go index 27e24c73..b0a821ba 100644 --- a/server/web/session/sess_mem.go +++ b/server/web/session/sess_mem.go @@ -27,9 +27,9 @@ var mempder = &MemProvider{list: list.New(), sessions: make(map[string]*list.Ele // MemSessionStore memory session store. // it saved sessions in a map in memory. type MemSessionStore struct { - sid string //session id - timeAccessed time.Time //last access time - value map[interface{}]interface{} //session store + sid string // session id + timeAccessed time.Time // last access time + value map[interface{}]interface{} // session store lock sync.RWMutex } diff --git a/server/web/session/sess_utils.go b/server/web/session/sess_utils.go index 8a031dd5..23242d7a 100644 --- a/server/web/session/sess_utils.go +++ b/server/web/session/sess_utils.go @@ -29,7 +29,7 @@ import ( "strconv" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) func init() { diff --git a/server/web/session/session.go b/server/web/session/session.go index bb7e5bd6..6b53ec29 100644 --- a/server/web/session/session.go +++ b/server/web/session/session.go @@ -16,7 +16,7 @@ // // Usage: // import( -// "github.com/astaxie/beego/session" +// "github.com/beego/beego/v2/session" // ) // // func init() { @@ -44,12 +44,12 @@ import ( // Store contains all data for one session process with specific id. type Store interface { - Set(ctx context.Context, key, value interface{}) error //set session value - Get(ctx context.Context, key interface{}) interface{} //get session value - Delete(ctx context.Context, key interface{}) error //delete session value - SessionID(ctx context.Context) string //back current sessionID + Set(ctx context.Context, key, value interface{}) error // set session value + Get(ctx context.Context, key interface{}) interface{} // get session value + Delete(ctx context.Context, key interface{}) error // delete session value + SessionID(ctx context.Context) string // back current sessionID SessionRelease(ctx context.Context, w http.ResponseWriter) // release the resource & save data to provider & return the data - Flush(ctx context.Context) error //delete all data + Flush(ctx context.Context) error // delete all data } // Provider contains global session methods and saved SessionStores. @@ -60,7 +60,7 @@ type Provider interface { SessionExist(ctx context.Context, sid string) (bool, error) SessionRegenerate(ctx context.Context, oldsid, sid string) (Store, error) SessionDestroy(ctx context.Context, sid string) error - SessionAll(ctx context.Context) int //get all active session + SessionAll(ctx context.Context) int // get all active session SessionGC(ctx context.Context) } @@ -82,7 +82,7 @@ func Register(name string, provide Provider) { provides[name] = provide } -//GetProvider +// GetProvider func GetProvider(name string) (Provider, error) { provider, ok := provides[name] if !ok { @@ -107,6 +107,7 @@ type ManagerConfig struct { SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"` EnableSidInURLQuery bool `json:"EnableSidInURLQuery"` SessionIDPrefix string `json:"sessionIDPrefix"` + CookieSameSite http.SameSite `json:"cookieSameSite"` } // Manager contains Provider and its configuration. @@ -239,6 +240,7 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se HttpOnly: !manager.config.DisableHTTPOnly, Secure: manager.isSecure(r), Domain: manager.config.Domain, + SameSite: manager.config.CookieSameSite, } if manager.config.CookieLifeTime > 0 { cookie.MaxAge = manager.config.CookieLifeTime @@ -278,7 +280,9 @@ func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) { HttpOnly: !manager.config.DisableHTTPOnly, Expires: expiration, MaxAge: -1, - Domain: manager.config.Domain} + Domain: manager.config.Domain, + SameSite: manager.config.CookieSameSite, + } http.SetCookie(w, cookie) } @@ -298,25 +302,40 @@ func (manager *Manager) GC() { } // SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request. -func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (session Store) { +func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (Store, error) { sid, err := manager.sessionID() if err != nil { - return + return nil, err } + + var session Store + cookie, err := r.Cookie(manager.config.CookieName) if err != nil || cookie.Value == "" { - //delete old cookie - session, _ = manager.provider.SessionRead(nil, sid) + // delete old cookie + session, err = manager.provider.SessionRead(nil, sid) + if err != nil { + return nil, err + } cookie = &http.Cookie{Name: manager.config.CookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: !manager.config.DisableHTTPOnly, Secure: manager.isSecure(r), Domain: manager.config.Domain, + SameSite: manager.config.CookieSameSite, } } else { - oldsid, _ := url.QueryUnescape(cookie.Value) - session, _ = manager.provider.SessionRegenerate(nil, oldsid, sid) + oldsid, err := url.QueryUnescape(cookie.Value) + if err != nil { + return nil, err + } + + session, err = manager.provider.SessionRegenerate(nil, oldsid, sid) + if err != nil { + return nil, err + } + cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" @@ -335,7 +354,7 @@ func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Reque w.Header().Set(manager.config.SessionNameInHTTPHeader, sid) } - return + return session, nil } // GetActiveSession Get all active sessions count number. diff --git a/server/web/session/ssdb/sess_ssdb.go b/server/web/session/ssdb/sess_ssdb.go index 0adc41bd..c9add89e 100644 --- a/server/web/session/ssdb/sess_ssdb.go +++ b/server/web/session/ssdb/sess_ssdb.go @@ -11,7 +11,7 @@ import ( "github.com/ssdb/gossdb/ssdb" - "github.com/astaxie/beego/server/web/session" + "github.com/beego/beego/v2/server/web/session" ) var ssdbProvider = &Provider{} diff --git a/server/web/staticfile.go b/server/web/staticfile.go index aa3f35d8..e5d3c3ed 100644 --- a/server/web/staticfile.go +++ b/server/web/staticfile.go @@ -26,10 +26,11 @@ import ( "sync" "time" - "github.com/astaxie/beego/core/logs" lru "github.com/hashicorp/golang-lru" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/core/logs" + + "github.com/beego/beego/v2/server/web/context" ) var errNotStaticRequest = errors.New("request not a static file request") @@ -65,12 +66,12 @@ func serverStaticRouter(ctx *context.Context) { } ctx.Redirect(302, redirectURL) } else { - //serveFile will list dir + // serveFile will list dir http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath) } return } else if fileInfo.Size() > int64(BConfig.WebConfig.StaticCacheFileSize) { - //over size file serve with http module + // over size file serve with http module http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath) return } @@ -102,7 +103,7 @@ type serveContentHolder struct { data []byte modTime time.Time size int64 - originSize int64 //original file size:to judge file changed + originSize int64 // original file size:to judge file changed encoding string } @@ -117,7 +118,7 @@ var ( func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, *serveContentReader, error) { if staticFileLruCache == nil { - //avoid lru cache error + // avoid lru cache error if BConfig.WebConfig.StaticCacheFileNum >= 1 { staticFileLruCache, _ = lru.New(BConfig.WebConfig.StaticCacheFileNum) } else { diff --git a/server/web/statistics.go b/server/web/statistics.go index 98f85e96..3677271b 100644 --- a/server/web/statistics.go +++ b/server/web/statistics.go @@ -19,7 +19,7 @@ import ( "sync" "time" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" ) // Statistics struct @@ -35,7 +35,7 @@ type Statistics struct { // URLMap contains several statistics struct to log different data type URLMap struct { lock sync.RWMutex - LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit + LengthLimit int // limit the urlmap's length if it's equal to 0 there's no limit urlmap map[string]map[string]*Statistics } diff --git a/server/web/swagger/swagger.go b/server/web/swagger/swagger.go index a55676cd..c20b31ed 100644 --- a/server/web/swagger/swagger.go +++ b/server/web/swagger/swagger.go @@ -106,7 +106,7 @@ type Parameter struct { type ParameterItems struct { Type string `json:"type,omitempty" yaml:"type,omitempty"` Format string `json:"format,omitempty" yaml:"format,omitempty"` - Items []*ParameterItems `json:"items,omitempty" yaml:"items,omitempty"` //Required if type is "array". Describes the type of items in the array. + Items []*ParameterItems `json:"items,omitempty" yaml:"items,omitempty"` // Required if type is "array". Describes the type of items in the array. CollectionFormat string `json:"collectionFormat,omitempty" yaml:"collectionFormat,omitempty"` Default string `json:"default,omitempty" yaml:"default,omitempty"` } diff --git a/server/web/template.go b/server/web/template.go index d582dcda..65935ca8 100644 --- a/server/web/template.go +++ b/server/web/template.go @@ -27,8 +27,8 @@ import ( "strings" "sync" - "github.com/astaxie/beego/core/logs" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/core/utils" ) var ( @@ -163,12 +163,12 @@ func AddTemplateExt(ext string) { } // AddViewPath adds a new path to the supported view paths. -//Can later be used by setting a controller ViewPath to this folder -//will panic if called after beego.Run() +// Can later be used by setting a controller ViewPath to this folder +// will panic if called after beego.Run() func AddViewPath(viewPath string) error { if beeViewPathTemplateLocked { if _, exist := beeViewPathTemplates[viewPath]; exist { - return nil //Ignore if viewpath already exists + return nil // Ignore if viewpath already exists } panic("Can not add new view paths after beego.Run()") } @@ -303,7 +303,7 @@ func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMod if tpl != nil { continue } - //first check filename + // first check filename for _, otherFile := range others { if otherFile == m[1] { var subMods1 [][]string @@ -316,7 +316,7 @@ func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMod break } } - //second check define + // second check define for _, otherFile := range others { var data []byte fileAbsPath := filepath.Join(root, otherFile) diff --git a/server/web/template_test.go b/server/web/template_test.go index b542494d..9ccacfcd 100644 --- a/server/web/template_test.go +++ b/server/web/template_test.go @@ -24,7 +24,7 @@ import ( assetfs "github.com/elazarl/go-bindata-assetfs" "github.com/stretchr/testify/assert" - "github.com/astaxie/beego/test" + "github.com/beego/beego/v2/test" ) var header = `{{define "header"}} @@ -49,9 +49,8 @@ var block = `{{define "block"}} {{end}}` func TestTemplate(t *testing.T) { - wkdir, err := os.Getwd() - assert.Nil(t, err) - dir := filepath.Join(wkdir, "_beeTmp", "TestTemplate") + tmpDir := os.TempDir() + dir := filepath.Join(tmpDir, "_beeTmp", "TestTemplate") files := []string{ "header.tpl", "index.tpl", @@ -113,11 +112,10 @@ var user = ` ` func TestRelativeTemplate(t *testing.T) { - wkdir, err := os.Getwd() - assert.Nil(t, err) - dir := filepath.Join(wkdir, "_beeTmp") + tmpDir := os.TempDir() + dir := filepath.Join(tmpDir, "_beeTmp") - //Just add dir to known viewPaths + // Just add dir to known viewPaths if err := AddViewPath(dir); err != nil { t.Fatal(err) } @@ -226,10 +224,10 @@ var output = ` ` func TestTemplateLayout(t *testing.T) { - wkdir, err := os.Getwd() + tmpDir, err := os.Getwd() assert.Nil(t, err) - dir := filepath.Join(wkdir, "_beeTmp", "TestTemplateLayout") + dir := filepath.Join(tmpDir, "_beeTmp", "TestTemplateLayout") files := []string{ "add.tpl", "layout_blog.tpl", diff --git a/server/web/tree.go b/server/web/tree.go index fc5a11a2..5a765fd3 100644 --- a/server/web/tree.go +++ b/server/web/tree.go @@ -19,9 +19,9 @@ import ( "regexp" "strings" - "github.com/astaxie/beego/core/utils" + "github.com/beego/beego/v2/core/utils" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) var ( @@ -210,9 +210,9 @@ func (t *Tree) AddRouter(pattern string, runObject interface{}) { func (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) { if len(segments) == 0 { if reg != "" { - t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile("^" + reg + "$")}) + t.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile("^" + reg + "$")}}, t.leaves...) } else { - t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards}) + t.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards}}, t.leaves...) } } else { seg := segments[0] diff --git a/server/web/tree_test.go b/server/web/tree_test.go index e72bc1f9..43511ad8 100644 --- a/server/web/tree_test.go +++ b/server/web/tree_test.go @@ -18,79 +18,122 @@ import ( "strings" "testing" - "github.com/astaxie/beego/server/web/context" + "github.com/beego/beego/v2/server/web/context" ) -type testinfo struct { - url string - requesturl string - params map[string]string +type testInfo struct { + pattern string + requestUrl string + params map[string]string + shouldMatchOrNot bool } -var routers []testinfo +var routers []testInfo + +func matchTestInfo(pattern, url string, params map[string]string) testInfo { + return testInfo{ + pattern: pattern, + requestUrl: url, + params: params, + shouldMatchOrNot: true, + } +} + +func notMatchTestInfo(pattern, url string) testInfo { + return testInfo{ + pattern: pattern, + requestUrl: url, + params: nil, + shouldMatchOrNot: false, + } +} func init() { - routers = make([]testinfo, 0) - routers = append(routers, testinfo{"/topic/?:auth:int", "/topic", nil}) - routers = append(routers, testinfo{"/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth", "/topic/1/2", map[string]string{":id": "1", ":auth": "2"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1", map[string]string{":id": "1"}}) - routers = append(routers, testinfo{"/topic/:id/?:auth:int", "/topic/1/123", map[string]string{":id": "1", ":auth": "123"}}) - routers = append(routers, testinfo{"/:id", "/123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/hello/?:id", "/hello", map[string]string{":id": ""}}) - routers = append(routers, testinfo{"/", "/", nil}) - routers = append(routers, testinfo{"/customer/login", "/customer/login", nil}) - routers = append(routers, testinfo{"/customer/login", "/customer/login.json", map[string]string{":ext": "json"}}) - routers = append(routers, testinfo{"/*", "/http://customer/123/", map[string]string{":splat": "http://customer/123/"}}) - routers = append(routers, testinfo{"/*", "/customer/2009/12/11", map[string]string{":splat": "customer/2009/12/11"}}) - routers = append(routers, testinfo{"/aa/*/bb", "/aa/2009/bb", map[string]string{":splat": "2009"}}) - routers = append(routers, testinfo{"/cc/*/dd", "/cc/2009/11/dd", map[string]string{":splat": "2009/11"}}) - routers = append(routers, testinfo{"/cc/:id/*", "/cc/2009/11/dd", map[string]string{":id": "2009", ":splat": "11/dd"}}) - routers = append(routers, testinfo{"/ee/:year/*/ff", "/ee/2009/11/ff", map[string]string{":year": "2009", ":splat": "11"}}) - routers = append(routers, testinfo{"/thumbnail/:size/uploads/*", - "/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg", - map[string]string{":size": "100x100", ":splat": "items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg"}}) - routers = append(routers, testinfo{"/*.*", "/nice/api.json", map[string]string{":path": "nice/api", ":ext": "json"}}) - routers = append(routers, testinfo{"/:name/*.*", "/nice/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}}) - routers = append(routers, testinfo{"/:name/test/*.*", "/nice/test/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"}}) - routers = append(routers, testinfo{"/dl/:width:int/:height:int/*.*", - "/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg", - map[string]string{":width": "48", ":height": "48", ":ext": "jpg", ":path": "05ac66d9bda00a3acf948c43e306fc9a"}}) - routers = append(routers, testinfo{"/v1/shop/:id:int", "/v1/shop/123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(a)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(b)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(c)", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/:year:int/:month:int/:id/:endid", "/1111/111/aaa/aaa", map[string]string{":year": "1111", ":month": "111", ":id": "aaa", ":endid": "aaa"}}) - routers = append(routers, testinfo{"/v1/shop/:id/:name", "/v1/shop/123/nike", map[string]string{":id": "123", ":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id/account", "/v1/shop/123/account", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:name:string", "/v1/shop/nike", map[string]string{":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)", "/v1/shop//123", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/:id([0-9]+)_:name", "/v1/shop/123_nike", map[string]string{":id": "123", ":name": "nike"}}) - routers = append(routers, testinfo{"/v1/shop/:id(.+)_cms.html", "/v1/shop/123_cms.html", map[string]string{":id": "123"}}) - routers = append(routers, testinfo{"/v1/shop/cms_:id(.+)_:page(.+).html", "/v1/shop/cms_123_1.html", map[string]string{":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v/cms/aaa_:id(.+)_:page(.+).html", "/v1/2/cms/aaa_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v/cms_:id(.+)_:page(.+).html", "/v1/2/cms_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", "/v1/2_cms/ttt_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"}}) - routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"}}) - routers = append(routers, testinfo{"/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"}}) + routers = make([]testInfo, 0) + // match example + routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic", nil)) + routers = append(routers, matchTestInfo("/topic/?:auth:int", "/topic/123", map[string]string{":auth": "123"})) + routers = append(routers, matchTestInfo("/topic/:id/?:auth", "/topic/1", map[string]string{":id": "1"})) + routers = append(routers, matchTestInfo("/topic/:id/?:auth", "/topic/1/2", map[string]string{":id": "1", ":auth": "2"})) + routers = append(routers, matchTestInfo("/topic/:id/?:auth:int", "/topic/1", map[string]string{":id": "1"})) + routers = append(routers, matchTestInfo("/topic/:id/?:auth:int", "/topic/1/123", map[string]string{":id": "1", ":auth": "123"})) + routers = append(routers, matchTestInfo("/:id", "/123", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/hello/?:id", "/hello", map[string]string{":id": ""})) + routers = append(routers, matchTestInfo("/", "/", nil)) + routers = append(routers, matchTestInfo("/customer/login", "/customer/login", nil)) + routers = append(routers, matchTestInfo("/customer/login", "/customer/login.json", map[string]string{":ext": "json"})) + routers = append(routers, matchTestInfo("/*", "/http://customer/123/", map[string]string{":splat": "http://customer/123/"})) + routers = append(routers, matchTestInfo("/*", "/customer/2009/12/11", map[string]string{":splat": "customer/2009/12/11"})) + routers = append(routers, matchTestInfo("/aa/*/bb", "/aa/2009/bb", map[string]string{":splat": "2009"})) + routers = append(routers, matchTestInfo("/cc/*/dd", "/cc/2009/11/dd", map[string]string{":splat": "2009/11"})) + routers = append(routers, matchTestInfo("/cc/:id/*", "/cc/2009/11/dd", map[string]string{":id": "2009", ":splat": "11/dd"})) + routers = append(routers, matchTestInfo("/ee/:year/*/ff", "/ee/2009/11/ff", map[string]string{":year": "2009", ":splat": "11"})) + routers = append(routers, matchTestInfo("/thumbnail/:size/uploads/*", "/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg", map[string]string{":size": "100x100", ":splat": "items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg"})) + routers = append(routers, matchTestInfo("/*.*", "/nice/api.json", map[string]string{":path": "nice/api", ":ext": "json"})) + routers = append(routers, matchTestInfo("/:name/*.*", "/nice/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"})) + routers = append(routers, matchTestInfo("/:name/test/*.*", "/nice/test/api.json", map[string]string{":name": "nice", ":path": "api", ":ext": "json"})) + routers = append(routers, matchTestInfo("/dl/:width:int/:height:int/*.*", "/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg", map[string]string{":width": "48", ":height": "48", ":ext": "jpg", ":path": "05ac66d9bda00a3acf948c43e306fc9a"})) + routers = append(routers, matchTestInfo("/v1/shop/:id:int", "/v1/shop/123", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(a)", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(b)", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/:id\\((a|b|c)\\)", "/v1/shop/123(c)", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/:year:int/:month:int/:id/:endid", "/1111/111/aaa/aaa", map[string]string{":year": "1111", ":month": "111", ":id": "aaa", ":endid": "aaa"})) + routers = append(routers, matchTestInfo("/v1/shop/:id/:name", "/v1/shop/123/nike", map[string]string{":id": "123", ":name": "nike"})) + routers = append(routers, matchTestInfo("/v1/shop/:id/account", "/v1/shop/123/account", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/:name:string", "/v1/shop/nike", map[string]string{":name": "nike"})) + routers = append(routers, matchTestInfo("/v1/shop/:id([0-9]+)", "/v1/shop//123", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/:id([0-9]+)_:name", "/v1/shop/123_nike", map[string]string{":id": "123", ":name": "nike"})) + routers = append(routers, matchTestInfo("/v1/shop/:id(.+)_cms.html", "/v1/shop/123_cms.html", map[string]string{":id": "123"})) + routers = append(routers, matchTestInfo("/v1/shop/cms_:id(.+)_:page(.+).html", "/v1/shop/cms_123_1.html", map[string]string{":id": "123", ":page": "1"})) + routers = append(routers, matchTestInfo("/v1/:v/cms/aaa_:id(.+)_:page(.+).html", "/v1/2/cms/aaa_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"})) + routers = append(routers, matchTestInfo("/v1/:v/cms_:id(.+)_:page(.+).html", "/v1/2/cms_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"})) + routers = append(routers, matchTestInfo("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", "/v1/2_cms/ttt_123_1.html", map[string]string{":v": "2", ":id": "123", ":page": "1"})) + routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members", map[string]string{":pid": "1"})) + routers = append(routers, matchTestInfo("/api/projects/:pid/members/?:mid", "/api/projects/1/members/2", map[string]string{":pid": "1", ":mid": "2"})) + routers = append(routers, matchTestInfo("/?:year/?:month/?:day", "/2020/11/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"})) + routers = append(routers, matchTestInfo("/?:year/?:month/?:day", "/2020/11", map[string]string{":year": "2020", ":month": "11"})) + routers = append(routers, matchTestInfo("/?:year", "/2020", map[string]string{":year": "2020"})) + routers = append(routers, matchTestInfo("/?:year([0-9]+)/?:month([0-9]+)/mid/?:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"})) + routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/2020/mid/10", map[string]string{":year": "2020", ":day": "10"})) + routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/2020/11/mid", map[string]string{":year": "2020", ":month": "11"})) + routers = append(routers, matchTestInfo("/?:year/?:month/mid/?:day/?:hour", "/mid/10/24", map[string]string{":day": "10", ":hour": "24"})) + routers = append(routers, matchTestInfo("/?:year([0-9]+)/:month([0-9]+)/mid/:day([0-9]+)/?:hour([0-9]+)", "/2020/11/mid/10/24", map[string]string{":year": "2020", ":month": "11", ":day": "10", ":hour": "24"})) + routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/11/mid/10/24", map[string]string{":month": "11", ":day": "10"})) + routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/2020/11/mid/10", map[string]string{":year": "2020", ":month": "11", ":day": "10"})) + routers = append(routers, matchTestInfo("/?:year/:month/mid/:day/?:hour", "/11/mid/10", map[string]string{":month": "11", ":day": "10"})) + // not match example + + // https://github.com/beego/beego/v2/issues/3865 + routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", "/read_222htm")) + routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", "/read_222_htm")) + routers = append(routers, notMatchTestInfo("/read_:id:int\\.htm", " /read_262shtm")) + } func TestTreeRouters(t *testing.T) { for _, r := range routers { + shouldMatch := r.shouldMatchOrNot + tr := NewTree() - tr.AddRouter(r.url, "astaxie") + tr.AddRouter(r.pattern, "astaxie") ctx := context.NewContext() - obj := tr.Match(r.requesturl, ctx) + obj := tr.Match(r.requestUrl, ctx) + if !shouldMatch { + if obj != nil { + t.Fatal("pattern:", r.pattern, ", should not match", r.requestUrl) + } else { + return + } + } if obj == nil || obj.(string) != "astaxie" { - t.Fatal(r.url+" can't get obj, Expect ", r.requesturl) + t.Fatal("pattern:", r.pattern+", can't match obj, Expect ", r.requestUrl) } if r.params != nil { for k, v := range r.params { if vv := ctx.Input.Param(k); vv != v { - t.Fatal("The Rule: " + r.url + "\nThe RequestURL:" + r.requesturl + "\nThe Key is " + k + ", The Value should be: " + v + ", but get: " + vv) + t.Fatal("The Rule: " + r.pattern + "\nThe RequestURL:" + r.requestUrl + "\nThe Key is " + k + ", The Value should be: " + v + ", but get: " + vv) } else if vv == "" && v != "" { - t.Fatal(r.url + " " + r.requesturl + " get param empty:" + k) + t.Fatal(r.pattern + " " + r.requestUrl + " get param empty:" + k) } } } @@ -247,7 +290,6 @@ func TestAddTree5(t *testing.T) { t.Fatal("url /v1/shop/ need match router /v1/shop/ ") } } - func TestSplitPath(t *testing.T) { a := splitPath("") if len(a) != 0 { @@ -292,6 +334,7 @@ func TestSplitSegment(t *testing.T) { ":id([0-9]+)": {true, []string{":id"}, `([0-9]+)`}, ":id([0-9]+)_:name": {true, []string{":id", ":name"}, `([0-9]+)_(.+)`}, ":id(.+)_cms.html": {true, []string{":id"}, `(.+)_cms.html`}, + ":id(.+)_cms\\.html": {true, []string{":id"}, `(.+)_cms\.html`}, "cms_:id(.+)_:page(.+).html": {true, []string{":id", ":page"}, `cms_(.+)_(.+).html`}, `:app(a|b|c)`: {true, []string{":app"}, `(a|b|c)`}, `:app\((a|b|c)\)`: {true, []string{":app"}, `(.+)\((a|b|c)\)`}, diff --git a/server/web/unregroute_test.go b/server/web/unregroute_test.go index c675ae7d..9745dbac 100644 --- a/server/web/unregroute_test.go +++ b/server/web/unregroute_test.go @@ -75,9 +75,9 @@ func TestUnregisterFixedRouteRoot(t *testing.T) { var method = "GET" handler := NewControllerRegister() - handler.Add("/", &TestPreUnregController{}, "get:GetFixedRoot") - handler.Add("/level1", &TestPreUnregController{}, "get:GetFixedLevel1") - handler.Add("/level1/level2", &TestPreUnregController{}, "get:GetFixedLevel2") + handler.Add("/", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) + handler.Add("/level1", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel1")) + handler.Add("/level1/level2", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel2")) // Test original root testHelperFnContentCheck(t, handler, "Test original root", @@ -96,7 +96,7 @@ func TestUnregisterFixedRouteRoot(t *testing.T) { // Replace the root path TestPreUnregController action with the action from // TestPostUnregController - handler.Add("/", &TestPostUnregController{}, "get:GetFixedRoot") + handler.Add("/", &TestPostUnregController{}, SetRouterMethods(&TestPostUnregController{}, "get:GetFixedRoot")) // Test replacement root (expect change) testHelperFnContentCheck(t, handler, "Test replacement root (expect change)", method, "/", contentRootReplacement) @@ -117,9 +117,9 @@ func TestUnregisterFixedRouteLevel1(t *testing.T) { var method = "GET" handler := NewControllerRegister() - handler.Add("/", &TestPreUnregController{}, "get:GetFixedRoot") - handler.Add("/level1", &TestPreUnregController{}, "get:GetFixedLevel1") - handler.Add("/level1/level2", &TestPreUnregController{}, "get:GetFixedLevel2") + handler.Add("/", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) + handler.Add("/level1", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel1")) + handler.Add("/level1/level2", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel2")) // Test original root testHelperFnContentCheck(t, handler, @@ -146,7 +146,7 @@ func TestUnregisterFixedRouteLevel1(t *testing.T) { // Replace the "level1" path TestPreUnregController action with the action from // TestPostUnregController - handler.Add("/level1", &TestPostUnregController{}, "get:GetFixedLevel1") + handler.Add("/level1", &TestPostUnregController{}, SetRouterMethods(&TestPostUnregController{}, "get:GetFixedLevel1")) // Test replacement root (expect no change from the original) testHelperFnContentCheck(t, handler, "Test replacement root (expect no change from the original)", method, "/", contentRootOriginal) @@ -167,9 +167,9 @@ func TestUnregisterFixedRouteLevel2(t *testing.T) { var method = "GET" handler := NewControllerRegister() - handler.Add("/", &TestPreUnregController{}, "get:GetFixedRoot") - handler.Add("/level1", &TestPreUnregController{}, "get:GetFixedLevel1") - handler.Add("/level1/level2", &TestPreUnregController{}, "get:GetFixedLevel2") + handler.Add("/", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedRoot")) + handler.Add("/level1", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel1")) + handler.Add("/level1/level2", &TestPreUnregController{}, SetRouterMethods(&TestPreUnregController{}, "get:GetFixedLevel2")) // Test original root testHelperFnContentCheck(t, handler, @@ -196,7 +196,7 @@ func TestUnregisterFixedRouteLevel2(t *testing.T) { // Replace the "/level1/level2" path TestPreUnregController action with the action from // TestPostUnregController - handler.Add("/level1/level2", &TestPostUnregController{}, "get:GetFixedLevel2") + handler.Add("/level1/level2", &TestPostUnregController{}, SetRouterMethods(&TestPostUnregController{}, "get:GetFixedLevel2")) // Test replacement root (expect no change from the original) testHelperFnContentCheck(t, handler, "Test replacement root (expect no change from the original)", method, "/", contentRootOriginal) diff --git a/task/govenor_command.go b/task/govenor_command.go index 15e25e43..20238435 100644 --- a/task/govenor_command.go +++ b/task/govenor_command.go @@ -21,13 +21,13 @@ import ( "github.com/pkg/errors" - "github.com/astaxie/beego/core/governor" + "github.com/beego/beego/v2/core/admin" ) type listTaskCommand struct { } -func (l *listTaskCommand) Execute(params ...interface{}) *governor.Result { +func (l *listTaskCommand) Execute(params ...interface{}) *admin.Result { resultList := make([][]string, 0, len(globalTaskManager.adminTaskList)) for tname, tk := range globalTaskManager.adminTaskList { result := []string{ @@ -39,7 +39,7 @@ func (l *listTaskCommand) Execute(params ...interface{}) *governor.Result { resultList = append(resultList, result) } - return &governor.Result{ + return &admin.Result{ Status: 200, Content: resultList, } @@ -48,9 +48,9 @@ func (l *listTaskCommand) Execute(params ...interface{}) *governor.Result { type runTaskCommand struct { } -func (r *runTaskCommand) Execute(params ...interface{}) *governor.Result { +func (r *runTaskCommand) Execute(params ...interface{}) *admin.Result { if len(params) == 0 { - return &governor.Result{ + return &admin.Result{ Status: 400, Error: errors.New("task name not passed"), } @@ -59,7 +59,7 @@ func (r *runTaskCommand) Execute(params ...interface{}) *governor.Result { tn, ok := params[0].(string) if !ok { - return &governor.Result{ + return &admin.Result{ Status: 400, Error: errors.New("parameter is invalid"), } @@ -68,17 +68,17 @@ func (r *runTaskCommand) Execute(params ...interface{}) *governor.Result { if t, ok := globalTaskManager.adminTaskList[tn]; ok { err := t.Run(context.Background()) if err != nil { - return &governor.Result{ + return &admin.Result{ Status: 500, Error: err, } } - return &governor.Result{ + return &admin.Result{ Status: 200, Content: t.GetStatus(context.Background()), } } else { - return &governor.Result{ + return &admin.Result{ Status: 400, Error: errors.New(fmt.Sprintf("task with name %s not found", tn)), } @@ -87,6 +87,6 @@ func (r *runTaskCommand) Execute(params ...interface{}) *governor.Result { } func registerCommands() { - governor.RegisterCommand("task", "list", &listTaskCommand{}) - governor.RegisterCommand("task", "run", &runTaskCommand{}) + admin.RegisterCommand("task", "list", &listTaskCommand{}) + admin.RegisterCommand("task", "run", &runTaskCommand{}) } diff --git a/task/task.go b/task/task.go index 00cbbfa7..2ea34f24 100644 --- a/task/task.go +++ b/task/task.go @@ -157,6 +157,9 @@ func (t *Task) GetSpec(context.Context) string { func (t *Task) GetStatus(context.Context) string { var str string for _, v := range t.Errlist { + if v == nil { + continue + } str += v.t.String() + ":" + v.errinfo + "
" } return str diff --git a/task/task_test.go b/task/task_test.go index 2cb807ce..5e117cbd 100644 --- a/task/task_test.go +++ b/task/task_test.go @@ -36,9 +36,11 @@ func TestParse(t *testing.T) { if err != nil { t.Fatal(err) } + assert.Equal(t, "0/30 * * * * *", tk.GetSpec(context.Background())) m.AddTask("taska", tk) m.StartTask() time.Sleep(3 * time.Second) + assert.True(t, len(tk.GetStatus(context.Background())) == 0) m.StopTask() } diff --git a/test/Makefile b/test/Makefile index e80e8238..7483cf05 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,2 +1,2 @@ build_view: - $(GOPATH)/bin/go-bindata-assetfs -pkg testdata views/... \ No newline at end of file + $(GOPATH)/bin/go-bindata-assetfs -pkg testdata views/... diff --git a/test/bindata.go b/test/bindata.go index 196ea95c..6dbc08ab 100644 --- a/test/bindata.go +++ b/test/bindata.go @@ -230,12 +230,12 @@ type bintree struct { } var _bintree = &bintree{nil, map[string]*bintree{ - "views": &bintree{nil, map[string]*bintree{ - "blocks": &bintree{nil, map[string]*bintree{ - "block.tpl": &bintree{viewsBlocksBlockTpl, map[string]*bintree{}}, + "views": {nil, map[string]*bintree{ + "blocks": {nil, map[string]*bintree{ + "block.tpl": {viewsBlocksBlockTpl, map[string]*bintree{}}, }}, - "header.tpl": &bintree{viewsHeaderTpl, map[string]*bintree{}}, - "index.tpl": &bintree{viewsIndexTpl, map[string]*bintree{}}, + "header.tpl": {viewsHeaderTpl, map[string]*bintree{}}, + "index.tpl": {viewsIndexTpl, map[string]*bintree{}}, }}, }} diff --git a/test/views/blocks/block.tpl b/test/views/blocks/block.tpl index 2a9c57fc..bd4cf960 100644 --- a/test/views/blocks/block.tpl +++ b/test/views/blocks/block.tpl @@ -1,3 +1,3 @@ {{define "block"}}

Hello, blocks!

-{{end}} \ No newline at end of file +{{end}} diff --git a/test/views/header.tpl b/test/views/header.tpl index 041fa403..0d36989e 100644 --- a/test/views/header.tpl +++ b/test/views/header.tpl @@ -1,3 +1,3 @@ {{define "header"}}

Hello, astaxie!

-{{end}} \ No newline at end of file +{{end}}