1
0
mirror of https://github.com/astaxie/beego.git synced 2024-10-03 09:51:51 +00:00

Revert "Merge pull request #4254 from astaxie/develop-2.0"

This reverts commit e284b0ddae, reversing
changes made to 8ef8fd2606.
This commit is contained in:
Ming Deng 2020-11-26 17:48:29 +08:00
parent e284b0ddae
commit 650fde66aa
455 changed files with 4657 additions and 29993 deletions

View File

@ -1,19 +0,0 @@
name: Mark stale issues and pull requests
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
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'

6
.gitignore vendored
View File

@ -4,9 +4,3 @@
*.swp
*.swo
beego.iml
_beeTmp/
_beeTmp2/
pkg/_beeTmp/
pkg/_beeTmp2/
test/tmp/

View File

@ -1,59 +1,30 @@
language: go
go:
- "1.14.x"
- "1.13.x"
services:
- redis-server
- mysql
- postgresql
- memcached
- docker
env:
global:
- GO_REPO_FULLNAME="github.com/astaxie/beego"
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:
# link the local repo with ${GOPATH}/src/<namespace>/<repo>
- GO_REPO_NAMESPACE=${GO_REPO_FULLNAME%/*}
# relies on GOPATH to contain only one directory...
- mkdir -p ${GOPATH}/src/${GO_REPO_NAMESPACE}
- ln -sv ${TRAVIS_BUILD_DIR} ${GOPATH}/src/${GO_REPO_FULLNAME}
- cd ${GOPATH}/src/${GO_REPO_FULLNAME}
# get and build ssdb
- git clone git://github.com/ideawu/ssdb.git
- cd ssdb
- make
- cd ..
# - prepare etcd
# - prepare for etcd unit tests
- rm -rf /tmp/etcd-data.tmp
- mkdir -p /tmp/etcd-data.tmp
- docker rmi gcr.io/etcd-development/etcd:v3.3.25 || true &&
docker run -d
-p 2379:2379
-p 2380:2380
--mount type=bind,source=/tmp/etcd-data.tmp,destination=/etcd-data
--name etcd-gcr-v3.3.25
gcr.io/etcd-development/etcd:v3.3.25
/usr/local/bin/etcd
--name s1
--data-dir /etcd-data
--listen-client-urls http://0.0.0.0:2379
--advertise-client-urls http://0.0.0.0:2379
--listen-peer-urls http://0.0.0.0:2380
--initial-advertise-peer-urls http://0.0.0.0:2380
--initial-cluster s1=http://0.0.0.0:2380
--initial-cluster-token tkn
--initial-cluster-state new
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.float 1.23"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.bool true"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.int 11"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.string hello"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put current.serialize.name test"
- docker exec etcd-gcr-v3.3.25 /bin/sh -c "ETCDCTL_API=3 /usr/local/bin/etcdctl put sub.sub.key1 sub.sub.key"
# link the local repo with ${GOPATH}/src/<namespace>/<repo>
- GO_REPO_NAMESPACE=${GO_REPO_FULLNAME%/*}
# relies on GOPATH to contain only one directory...
- mkdir -p ${GOPATH}/src/${GO_REPO_NAMESPACE}
- ln -sv ${TRAVIS_BUILD_DIR} ${GOPATH}/src/${GO_REPO_FULLNAME}
- cd ${GOPATH}/src/${GO_REPO_FULLNAME}
# get and build ssdb
- git clone git://github.com/ideawu/ssdb.git
- cd ssdb
- make
- cd ..
install:
- go get github.com/lib/pq
- go get github.com/go-sql-driver/mysql
@ -80,10 +51,7 @@ install:
- go get -u golang.org/x/lint/golint
- go get -u github.com/go-redis/redis
before_script:
# -
- psql --version
# - prepare for orm unit tests
- sh -c "if [ '$ORM_DRIVER' = 'postgres' ]; then psql -c 'create database orm_test;' -U postgres; fi"
- sh -c "if [ '$ORM_DRIVER' = 'mysql' ]; then mysql -u root -e 'create database orm_test;'; fi"
- sh -c "if [ '$ORM_DRIVER' = 'sqlite' ]; then touch $TRAVIS_BUILD_DIR/orm_test.db; fi"
@ -95,11 +63,11 @@ after_script:
- killall -w ssdb-server
- rm -rf ./res/var/*
script:
- go test ./...
- staticcheck -show-ignored -checks "-ST1017,-U1000,-ST1005,-S1034,-S1012,-SA4006,-SA6005,-SA1019,-SA1024" ./
- go test -v ./...
- 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"
postgresql: "9.6"

View File

@ -7,58 +7,17 @@ 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.
## Prepare environment
Firstly, install some tools. Execute those commands **outside** the project. Or those command will modify go.mod file.
```shell script
go get -u golang.org/x/tools/cmd/goimports
go get -u github.com/gordonklaus/ineffassign
```
Put those lines into your pre-commit githook script:
```shell script
goimports -w -format-only ./
ineffassign .
staticcheck -show-ignored -checks "-ST1017,-U1000,-ST1005,-S1034,-S1012,-SA4006,-SA6005,-SA1019,-SA1024" ./
```
## Prepare middleware
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"
export MEMCACHE_ADDR="192.168.0.105:11211"
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.
to **develop** 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.
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.
@ -89,5 +48,5 @@ 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
Also if you don't know how to use it. please make sure you have read though
the docs in http://beego.me/docs

218
README.md
View File

@ -8,21 +8,6 @@ It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific feature
## Quick Start
###### Please see [Documentation](http://beego.me/docs) for more.
###### [beego-example](https://github.com/beego-dev/beego-example)
### Web Application
#### Create `hello` directory, cd `hello` directory
mkdir hello
cd hello
#### Init module
go mod init
#### Download and install
go get github.com/astaxie/beego
@ -31,10 +16,10 @@ It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific feature
```go
package main
import "github.com/astaxie/beego/server/web"
import "github.com/astaxie/beego"
func main(){
web.Run()
beego.Run()
}
```
#### Build and run
@ -46,204 +31,9 @@ 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)
}
```
###### Please see [Documentation](http://beego.me/docs) for more.
###### [beego-example](https://github.com/beego-dev/beego-example)
## Features

View File

@ -1,45 +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 (
"time"
_ "github.com/astaxie/beego/core/governor"
"github.com/astaxie/beego/server/web"
)
// FilterMonitorFunc is default monitor filter when admin module is enable.
// if this func returns, admin module records qps for this request by condition of this function logic.
// usage:
// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
// if method == "POST" {
// return false
// }
// if t.Nanoseconds() < 100 {
// return false
// }
// if strings.HasPrefix(requestPath, "/astaxie") {
// return false
// }
// return true
// }
// beego.FilterMonitorFunc = MyFilterMonitor.
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
// PrintTree prints all registered routers.
func PrintTree() M {
return (M)(web.BeeApp.PrintTree())
}

View File

@ -1,262 +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 (
"net/http"
context2 "github.com/astaxie/beego/adapter/context"
"github.com/astaxie/beego/server/web"
"github.com/astaxie/beego/server/web/context"
)
var (
// BeeApp is an application instance
BeeApp *App
)
func init() {
// create beego application
BeeApp = (*App)(web.BeeApp)
}
// App defines beego application with a new PatternServeMux.
type App web.HttpServer
// NewApp returns a new beego application.
func NewApp() *App {
return (*App)(web.NewHttpSever())
}
// MiddleWare function for http.Handler
type MiddleWare web.MiddleWare
// Run beego application.
func (app *App) Run(mws ...MiddleWare) {
newMws := oldMiddlewareToNew(mws)
(*web.HttpServer)(app).Run("", newMws...)
}
func oldMiddlewareToNew(mws []MiddleWare) []web.MiddleWare {
newMws := make([]web.MiddleWare, 0, len(mws))
for _, old := range mws {
newMws = append(newMws, (web.MiddleWare)(old))
}
return newMws
}
// Router adds a patterned controller handler to BeeApp.
// it's an alias method of HttpServer.Router.
// usage:
// simple router
// beego.Router("/admin", &admin.UserController{})
// beego.Router("/admin/index", &admin.ArticleController{})
//
// regex router
//
// beego.Router("/api/:id([0-9]+)", &controllers.RController{})
//
// custom rules
// beego.Router("/api/list",&RestController{},"*:ListFood")
// beego.Router("/api/create",&RestController{},"post:CreateFood")
// 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...))
}
// UnregisterFixedRoute unregisters the route with the specified fixedRoute. It is particularly useful
// in web applications that inherit most routes from a base webapp via the underscore
// import, and aim to overwrite only certain paths.
// The method parameter can be empty or "*" for all HTTP methods, or a particular
// method type (e.g. "GET" or "POST") for selective removal.
//
// Usage (replace "GET" with "*" for all methods):
// beego.UnregisterFixedRoute("/yourpreviouspath", "GET")
// beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")
func UnregisterFixedRoute(fixedRoute string, method string) *App {
return (*App)(web.UnregisterFixedRoute(fixedRoute, method))
}
// Include will generate router file in the router/xxx.go from the controller's comments
// usage:
// beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
// type BankAccount struct{
// beego.Controller
// }
//
// register the function
// func (b *BankAccount)Mapping(){
// b.Mapping("ShowAccount" , b.ShowAccount)
// b.Mapping("ModifyAccount", b.ModifyAccount)
// }
//
// //@router /account/:id [get]
// func (b *BankAccount) ShowAccount(){
// //logic
// }
//
//
// //@router /account/:id [post]
// func (b *BankAccount) ModifyAccount(){
// //logic
// }
//
// the comments @router url methodlist
// url support all the function Router's pattern
// methodlist [get post head put delete options *]
func Include(cList ...ControllerInterface) *App {
newList := oldToNewCtrlIntfs(cList)
return (*App)(web.Include(newList...))
}
func oldToNewCtrlIntfs(cList []ControllerInterface) []web.ControllerInterface {
newList := make([]web.ControllerInterface, 0, len(cList))
for _, c := range cList {
newList = append(newList, c)
}
return newList
}
// RESTRouter adds a restful controller handler to BeeApp.
// its' controller implements beego.ControllerInterface and
// defines a param "pattern/:objectId" to visit each resource.
func RESTRouter(rootpath string, c ControllerInterface) *App {
return (*App)(web.RESTRouter(rootpath, c))
}
// AutoRouter adds defined controller handler to BeeApp.
// it's same to HttpServer.AutoRouter.
// if beego.AddAuto(&MainContorlller{}) and MainController has methods List and Page,
// visit the url /main/list to exec List function or /main/page to exec Page function.
func AutoRouter(c ControllerInterface) *App {
return (*App)(web.AutoRouter(c))
}
// AutoPrefix adds controller handler to BeeApp with prefix.
// it's same to HttpServer.AutoRouterWithPrefix.
// if beego.AutoPrefix("/admin",&MainContorlller{}) and MainController has methods List and Page,
// visit the url /admin/main/list to exec List function or /admin/main/page to exec Page function.
func AutoPrefix(prefix string, c ControllerInterface) *App {
return (*App)(web.AutoPrefix(prefix, c))
}
// Get used to register router for Get method
// usage:
// beego.Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Get(rootpath string, f FilterFunc) *App {
return (*App)(web.Get(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Post used to register router for Post method
// usage:
// beego.Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Post(rootpath string, f FilterFunc) *App {
return (*App)(web.Post(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Delete used to register router for Delete method
// usage:
// beego.Delete("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Delete(rootpath string, f FilterFunc) *App {
return (*App)(web.Delete(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Put used to register router for Put method
// usage:
// beego.Put("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Put(rootpath string, f FilterFunc) *App {
return (*App)(web.Put(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Head used to register router for Head method
// usage:
// beego.Head("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Head(rootpath string, f FilterFunc) *App {
return (*App)(web.Head(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Options used to register router for Options method
// usage:
// beego.Options("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Options(rootpath string, f FilterFunc) *App {
return (*App)(web.Options(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Patch used to register router for Patch method
// usage:
// beego.Patch("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Patch(rootpath string, f FilterFunc) *App {
return (*App)(web.Patch(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Any used to register router for all methods
// usage:
// beego.Any("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Any(rootpath string, f FilterFunc) *App {
return (*App)(web.Any(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
}))
}
// Handler used to register a Handler router
// usage:
// beego.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
// }))
func Handler(rootpath string, h http.Handler, options ...interface{}) *App {
return (*App)(web.Handler(rootpath, h, options))
}
// InsertFilter adds a FilterFunc with pattern condition and action constant.
// The pos means action constant including
// beego.BeforeStatic, beego.BeforeRouter, beego.BeforeExec, beego.AfterExec and beego.FinishRouter.
// The bool params is for setting the returnOnOutput value (false allows multiple filters to execute)
func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App {
opts := oldToNewFilterOpts(params)
return (*App)(web.InsertFilter(pattern, pos, func(ctx *context.Context) {
filter((*context2.Context)(ctx))
}, opts...))
}

View File

@ -1,77 +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 (
"github.com/astaxie/beego"
"github.com/astaxie/beego/server/web"
)
const (
// VERSION represent beego web framework version.
VERSION = beego.VERSION
// DEV is for develop
DEV = web.DEV
// PROD is for production
PROD = web.PROD
)
// M is Map shortcut
type M web.M
// Hook function to run
type hookfunc func() error
var (
hooks = make([]hookfunc, 0) // hook function slice to store the hookfunc
)
// AddAPPStartHook is used to register the hookfunc
// The hookfuncs will run in beego.Run()
// such as initiating session , starting middleware , building template, starting admin control and so on.
func AddAPPStartHook(hf ...hookfunc) {
for _, f := range hf {
web.AddAPPStartHook(func() error {
return f()
})
}
}
// Run beego application.
// beego.Run() default run on HttpPort
// beego.Run("localhost")
// beego.Run(":8089")
// beego.Run("127.0.0.1:8089")
func Run(params ...string) {
web.Run(params...)
}
// RunWithMiddleWares Run beego application with middlewares.
func RunWithMiddleWares(addr string, mws ...MiddleWare) {
newMws := oldMiddlewareToNew(mws)
web.RunWithMiddleWares(addr, newMws...)
}
// TestBeegoInit is for test package init
func TestBeegoInit(ap string) {
web.TestBeegoInit(ap)
}
// InitBeegoBeforeTest is for test package init
func InitBeegoBeforeTest(appConfigPath string) {
web.InitBeegoBeforeTest(appConfigPath)
}

View File

@ -1,27 +0,0 @@
// Copyright 2020 astaxie
//
// 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
var (
BuildVersion string
BuildGitRevision string
BuildStatus string
BuildTag string
BuildTime string
GoVersion string
GitBranch string
)

View File

@ -1,117 +0,0 @@
// Copyright 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"context"
"time"
"github.com/astaxie/beego/client/cache"
)
type newToOldCacheAdapter struct {
delegate cache.Cache
}
func (c *newToOldCacheAdapter) Get(key string) interface{} {
res, _ := c.delegate.Get(context.Background(), key)
return res
}
func (c *newToOldCacheAdapter) GetMulti(keys []string) []interface{} {
res, _ := c.delegate.GetMulti(context.Background(), keys)
return res
}
func (c *newToOldCacheAdapter) Put(key string, val interface{}, timeout time.Duration) error {
return c.delegate.Put(context.Background(), key, val, timeout)
}
func (c *newToOldCacheAdapter) Delete(key string) error {
return c.delegate.Delete(context.Background(), key)
}
func (c *newToOldCacheAdapter) Incr(key string) error {
return c.delegate.Incr(context.Background(), key)
}
func (c *newToOldCacheAdapter) Decr(key string) error {
return c.delegate.Decr(context.Background(), key)
}
func (c *newToOldCacheAdapter) IsExist(key string) bool {
res, err := c.delegate.IsExist(context.Background(), key)
return res && err == nil
}
func (c *newToOldCacheAdapter) ClearAll() error {
return c.delegate.ClearAll(context.Background())
}
func (c *newToOldCacheAdapter) StartAndGC(config string) error {
return c.delegate.StartAndGC(config)
}
func CreateNewToOldCacheAdapter(delegate cache.Cache) Cache {
return &newToOldCacheAdapter{
delegate: delegate,
}
}
type oldToNewCacheAdapter struct {
old Cache
}
func (o *oldToNewCacheAdapter) Get(ctx context.Context, key string) (interface{}, error) {
return o.old.Get(key), nil
}
func (o *oldToNewCacheAdapter) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) {
return o.old.GetMulti(keys), nil
}
func (o *oldToNewCacheAdapter) Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error {
return o.old.Put(key, val, timeout)
}
func (o *oldToNewCacheAdapter) Delete(ctx context.Context, key string) error {
return o.old.Delete(key)
}
func (o *oldToNewCacheAdapter) Incr(ctx context.Context, key string) error {
return o.old.Incr(key)
}
func (o *oldToNewCacheAdapter) Decr(ctx context.Context, key string) error {
return o.old.Decr(key)
}
func (o *oldToNewCacheAdapter) IsExist(ctx context.Context, key string) (bool, error) {
return o.old.IsExist(key), nil
}
func (o *oldToNewCacheAdapter) ClearAll(ctx context.Context) error {
return o.old.ClearAll()
}
func (o *oldToNewCacheAdapter) StartAndGC(config string) error {
return o.old.StartAndGC(config)
}
func CreateOldToNewAdapter(old Cache) cache.Cache {
return &oldToNewCacheAdapter{
old: old,
}
}

44
adapter/cache/conv.go vendored
View File

@ -1,44 +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 cache
import (
"github.com/astaxie/beego/client/cache"
)
// GetString convert interface to string.
func GetString(v interface{}) string {
return cache.GetString(v)
}
// GetInt convert interface to int.
func GetInt(v interface{}) int {
return cache.GetInt(v)
}
// GetInt64 convert interface to int64.
func GetInt64(v interface{}) int64 {
return cache.GetInt64(v)
}
// GetFloat64 convert interface to float64.
func GetFloat64(v interface{}) float64 {
return cache.GetFloat64(v)
}
// GetBool convert interface to bool.
func GetBool(v interface{}) bool {
return cache.GetBool(v)
}

30
adapter/cache/file.go vendored
View File

@ -1,30 +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 cache
import (
"github.com/astaxie/beego/client/cache"
)
// NewFileCache Create new file cache with no config.
// the level and expiry need set in method StartAndGC as config string.
func NewFileCache() Cache {
// return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix}
return CreateNewToOldCacheAdapter(cache.NewFileCache())
}
func init() {
Register("file", NewFileCache)
}

View File

@ -1,44 +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 memcache for cache provider
//
// depend on github.com/bradfitz/gomemcache/memcache
//
// go install github.com/bradfitz/gomemcache/memcache
//
// Usage:
// import(
// _ "github.com/astaxie/beego/cache/memcache"
// "github.com/astaxie/beego/cache"
// )
//
// bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`)
//
// more docs http://beego.me/docs/module/cache.md
package memcache
import (
"github.com/astaxie/beego/adapter/cache"
"github.com/astaxie/beego/client/cache/memcache"
)
// NewMemCache create new memcache adapter.
func NewMemCache() cache.Cache {
return cache.CreateNewToOldCacheAdapter(memcache.NewMemCache())
}
func init() {
cache.Register("memcache", NewMemCache)
}

View File

@ -1,28 +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 cache
import (
"github.com/astaxie/beego/client/cache"
)
// NewMemoryCache returns a new MemoryCache.
func NewMemoryCache() Cache {
return CreateNewToOldCacheAdapter(cache.NewMemoryCache())
}
func init() {
Register("memory", NewMemoryCache)
}

View File

@ -1,49 +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 redis for cache provider
//
// depend on github.com/gomodule/redigo/redis
//
// go install github.com/gomodule/redigo/redis
//
// Usage:
// import(
// _ "github.com/astaxie/beego/cache/redis"
// "github.com/astaxie/beego/cache"
// )
//
// bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`)
//
// more docs http://beego.me/docs/module/cache.md
package redis
import (
"github.com/astaxie/beego/adapter/cache"
redis2 "github.com/astaxie/beego/client/cache/redis"
)
var (
// DefaultKey the collection name of redis for cache adapter.
DefaultKey = "beecacheRedis"
)
// NewRedisCache create new redis cache with default collection name.
func NewRedisCache() cache.Cache {
return cache.CreateNewToOldCacheAdapter(redis2.NewRedisCache())
}
func init() {
cache.Register("redis", NewRedisCache)
}

View File

@ -1,15 +0,0 @@
package ssdb
import (
"github.com/astaxie/beego/adapter/cache"
ssdb2 "github.com/astaxie/beego/client/cache/ssdb"
)
// NewSsdbCache create new ssdb adapter.
func NewSsdbCache() cache.Cache {
return cache.CreateNewToOldCacheAdapter(ssdb2.NewSsdbCache())
}
func init() {
cache.Register("ssdb", NewSsdbCache)
}

View File

@ -1,177 +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 (
"github.com/astaxie/beego/adapter/session"
newCfg "github.com/astaxie/beego/core/config"
"github.com/astaxie/beego/server/web"
)
// Config is the main struct for BConfig
type Config web.Config
// Listen holds for http and https related config
type Listen web.Listen
// WebConfig holds web related config
type WebConfig web.WebConfig
// SessionConfig holds session related config
type SessionConfig web.SessionConfig
// LogConfig holds Log related config
type LogConfig web.LogConfig
var (
// BConfig is the default config for Application
BConfig *Config
// AppConfig is the instance of Config, store the config information from file
AppConfig *beegoAppConfig
// AppPath is the absolute path to the app
AppPath string
// GlobalSessions is the instance for the session manager
GlobalSessions *session.Manager
// appConfigPath is the path to the config files
appConfigPath string
// appConfigProvider is the provider for the config, default is ini
appConfigProvider = "ini"
// WorkPath is the absolute path to project root directory
WorkPath string
)
func init() {
BConfig = (*Config)(web.BConfig)
AppPath = web.AppPath
WorkPath = web.WorkPath
AppConfig = &beegoAppConfig{innerConfig: (newCfg.Configer)(web.AppConfig)}
}
// LoadAppConfig allow developer to apply a config file
func LoadAppConfig(adapterName, configPath string) error {
return web.LoadAppConfig(adapterName, configPath)
}
type beegoAppConfig struct {
innerConfig newCfg.Configer
}
func (b *beegoAppConfig) Set(key, val string) error {
if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil {
return b.innerConfig.Set(key, val)
}
return nil
}
func (b *beegoAppConfig) String(key string) string {
if v, err := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" && err != nil {
return v
}
res, _ := b.innerConfig.String(key)
return res
}
func (b *beegoAppConfig) Strings(key string) []string {
if v, err := b.innerConfig.Strings(BConfig.RunMode + "::" + key); len(v) > 0 && err != nil {
return v
}
res, _ := b.innerConfig.Strings(key)
return res
}
func (b *beegoAppConfig) Int(key string) (int, error) {
if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil {
return v, nil
}
return b.innerConfig.Int(key)
}
func (b *beegoAppConfig) Int64(key string) (int64, error) {
if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil {
return v, nil
}
return b.innerConfig.Int64(key)
}
func (b *beegoAppConfig) Bool(key string) (bool, error) {
if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil {
return v, nil
}
return b.innerConfig.Bool(key)
}
func (b *beegoAppConfig) Float(key string) (float64, error) {
if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil {
return v, nil
}
return b.innerConfig.Float(key)
}
func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string {
if v := b.String(key); v != "" {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DefaultStrings(key string, defaultVal []string) []string {
if v := b.Strings(key); len(v) != 0 {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DefaultInt(key string, defaultVal int) int {
if v, err := b.Int(key); err == nil {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DefaultInt64(key string, defaultVal int64) int64 {
if v, err := b.Int64(key); err == nil {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DefaultBool(key string, defaultVal bool) bool {
if v, err := b.Bool(key); err == nil {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DefaultFloat(key string, defaultVal float64) float64 {
if v, err := b.Float(key); err == nil {
return v
}
return defaultVal
}
func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
return b.innerConfig.DIY(key)
}
func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) {
return b.innerConfig.GetSection(section)
}
func (b *beegoAppConfig) SaveConfigFile(filename string) error {
return b.innerConfig.SaveConfigFile(filename)
}

View File

@ -1,191 +0,0 @@
// Copyright 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"github.com/pkg/errors"
"github.com/astaxie/beego/core/config"
)
type newToOldConfigerAdapter struct {
delegate config.Configer
}
func (c *newToOldConfigerAdapter) Set(key, val string) error {
return c.delegate.Set(key, val)
}
func (c *newToOldConfigerAdapter) String(key string) string {
res, _ := c.delegate.String(key)
return res
}
func (c *newToOldConfigerAdapter) Strings(key string) []string {
res, _ := c.delegate.Strings(key)
return res
}
func (c *newToOldConfigerAdapter) Int(key string) (int, error) {
return c.delegate.Int(key)
}
func (c *newToOldConfigerAdapter) Int64(key string) (int64, error) {
return c.delegate.Int64(key)
}
func (c *newToOldConfigerAdapter) Bool(key string) (bool, error) {
return c.delegate.Bool(key)
}
func (c *newToOldConfigerAdapter) Float(key string) (float64, error) {
return c.delegate.Float(key)
}
func (c *newToOldConfigerAdapter) DefaultString(key string, defaultVal string) string {
return c.delegate.DefaultString(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DefaultStrings(key string, defaultVal []string) []string {
return c.delegate.DefaultStrings(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DefaultInt(key string, defaultVal int) int {
return c.delegate.DefaultInt(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DefaultInt64(key string, defaultVal int64) int64 {
return c.delegate.DefaultInt64(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DefaultBool(key string, defaultVal bool) bool {
return c.delegate.DefaultBool(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DefaultFloat(key string, defaultVal float64) float64 {
return c.delegate.DefaultFloat(key, defaultVal)
}
func (c *newToOldConfigerAdapter) DIY(key string) (interface{}, error) {
return c.delegate.DIY(key)
}
func (c *newToOldConfigerAdapter) GetSection(section string) (map[string]string, error) {
return c.delegate.GetSection(section)
}
func (c *newToOldConfigerAdapter) SaveConfigFile(filename string) error {
return c.delegate.SaveConfigFile(filename)
}
type oldToNewConfigerAdapter struct {
delegate Configer
}
func (o *oldToNewConfigerAdapter) Set(key, val string) error {
return o.delegate.Set(key, val)
}
func (o *oldToNewConfigerAdapter) String(key string) (string, error) {
return o.delegate.String(key), nil
}
func (o *oldToNewConfigerAdapter) Strings(key string) ([]string, error) {
return o.delegate.Strings(key), nil
}
func (o *oldToNewConfigerAdapter) Int(key string) (int, error) {
return o.delegate.Int(key)
}
func (o *oldToNewConfigerAdapter) Int64(key string) (int64, error) {
return o.delegate.Int64(key)
}
func (o *oldToNewConfigerAdapter) Bool(key string) (bool, error) {
return o.delegate.Bool(key)
}
func (o *oldToNewConfigerAdapter) Float(key string) (float64, error) {
return o.delegate.Float(key)
}
func (o *oldToNewConfigerAdapter) DefaultString(key string, defaultVal string) string {
return o.delegate.DefaultString(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DefaultStrings(key string, defaultVal []string) []string {
return o.delegate.DefaultStrings(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DefaultInt(key string, defaultVal int) int {
return o.delegate.DefaultInt(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DefaultInt64(key string, defaultVal int64) int64 {
return o.delegate.DefaultInt64(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DefaultBool(key string, defaultVal bool) bool {
return o.delegate.DefaultBool(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DefaultFloat(key string, defaultVal float64) float64 {
return o.delegate.DefaultFloat(key, defaultVal)
}
func (o *oldToNewConfigerAdapter) DIY(key string) (interface{}, error) {
return o.delegate.DIY(key)
}
func (o *oldToNewConfigerAdapter) GetSection(section string) (map[string]string, error) {
return o.delegate.GetSection(section)
}
func (o *oldToNewConfigerAdapter) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
return errors.New("unsupported operation, please use actual config.Configer")