1
0
mirror of https://github.com/astaxie/beego.git synced 2025-07-11 14:11:01 +00:00

2628 Commits

Author SHA1 Message Date
fb12e1f743 Merge pull request #4292 from flycash/develop-2.0
Develop 2.0
2020-11-07 22:23:55 +08:00
8c0fc30094 Merge dev 2020-11-07 22:10:02 +08:00
20a0de6bd0 Merge pull request #4290 from flycash/develop-2.0
fix init error of global instance
2020-11-05 23:51:52 +08:00
b4396c97bb fix init error of global instance 2020-11-05 22:00:43 +08:00
cbbb6bfb08 Merge pull request #4284 from flycash/develop
Upgrade version
2020-11-03 22:49:59 +08:00
b2a96234ab Upgrade version 2020-11-03 22:21:32 +08:00
471ebba64d Merge pull request #4281 from flycash/httplibTest
Add test for httplib
2020-10-27 22:08:35 +08:00
d07a1eaa8e Add test for httplib 2020-10-27 21:58:39 +08:00
9524036aab Merge pull request #4278 from flycash/defaultCfg
Add global instance for config module
2020-10-24 22:27:12 +08:00
45260e4119 Add global instance for config module 2020-10-24 22:13:15 +08:00
02234dc503 Merge pull request #4277 from flycash/session
support using json string to init session
2020-10-22 09:53:55 +08:00
05f4e0c146 support using json string to init session 2020-10-21 22:24:53 +08:00
ae108ec826 Merge pull request #4276 from flycash/newHttpServer
Change NewHttpServer API
2020-10-21 21:59:45 +08:00
7c61eb058f Change NewHttpServer API 2020-10-21 20:54:33 +08:00
03ba495b7f Merge pull request #4275 from flycash/fix-4224
add MaxUploadFile to provide more safety uploading controll
2020-10-21 10:04:32 +08:00
d26683799a add MaxUploadFile to provide more safety uploading controll 2020-10-20 23:36:34 +08:00
f9075e8274 Merge pull request #4272 from jianzhiyao/fix-4224
fix 4224:form entity too large casue run out of memory
2020-10-20 20:53:19 +08:00
022ad862ac Merge pull request #4274 from flycash/loadCfg
Fix ini Unmarshall method
2020-10-19 21:51:37 +08:00
93bdf97068 Fix ini Unmarshall method 2020-10-19 21:04:57 +08:00
3c48719999 complete condition 2020-10-19 00:22:55 +08:00
cbb3de741d fix application/x-www-form-urlencoded request body oversize 2020-10-18 23:38:08 +08:00
c510926cb8 fix 4224:form entity too large casue run out of memory 2020-10-18 23:18:13 +08:00
140a4b90a3 Merge pull request #4266 from flycash/loadCfg
Using unmarshaler to parse config in web module
2020-10-14 22:26:12 +08:00
c07acaebbc Support unmarshaler 2020-10-14 22:20:25 +08:00
105b874477 Merge pull request #4265 from flycash/rft/configCtx
Upgrade toml version
2020-10-14 00:28:30 +08:00
3fc21ae6ec Upgrade toml version 2020-10-14 00:25:31 +08:00
ccf873fa8b Merge pull request #4264 from flycash/rft/configCtx
remove config API's context parameter
2020-10-13 22:52:46 +08:00
2572094a8d remove config API's context parameter 2020-10-13 22:33:39 +08:00
568626cd57 Merge pull request #4262 from flycash/ftr/toml
Support toml config
2020-10-12 22:55:55 +08:00
34d6a733e9 Support toml config 2020-10-11 23:26:48 +08:00
db3defa76a Merge pull request #4261 from flycash/reduceCache
make stmt cache smaller
2020-10-10 22:10:43 +08:00
1dffa20435 make stmt cache smaller 2020-10-10 21:35:58 +08:00
e44f16c672 Merge pull request #4257 from flycash/fix/adapter
Remove scripts directory & update readme
2020-10-09 08:48:08 +08:00
d41abdb5e4 Remove scripts directory; update readme 2020-10-08 23:18:10 +08:00
f1358cf78d Merge pull request #4255 from flycash/fix/adapter
Reorganize packages
2020-10-08 18:37:42 +08:00
14c1b76569 remove pkg directory;
remove build directory;
remove githook directory;
2020-10-08 18:29:36 +08:00
8e37fe3b78 Merge pull request #4251 from sc0Vu/fix-typo
Fix typo
2020-10-06 19:44:27 +08:00
2708916f96 Merge pull request #4252 from flycash/fix/adapter
Reset func call depth & add adapter.sh
2020-10-06 18:33:45 +08:00
91e18996bd Fix typo 2020-10-06 18:20:06 +08:00
034cb3222e Add adapter script which is used to replace v1 package with v2 adapter package 2020-10-06 16:43:16 +08:00
66804324f2 Fix: Set func call depth as 3 2020-10-06 11:52:24 +08:00
dc65055cf6 Merge pull request #4250 from flycash/adt/logs
logs Adapter
2020-10-05 23:26:55 +08:00
b8c1e133bf Merge pull request #4226 from vinicio/feature/same-site
session: adds CookieSameSite to ManagerConfig
2020-10-05 23:05:30 +08:00
8cc74652a2 Fix: adapter's controller must implement ControllerInterface 2020-10-05 23:00:20 +08:00
d66321fe4e session: adds CookieSameSite config to hooks.go#registerSession 2020-10-05 11:39:20 -03:00
6aa6c55f07 logs Adapter 2020-10-05 21:55:26 +08:00
ff762b561c Merge pull request #4249 from flycash/rft/moveSession
move core/session to web/session
2020-10-05 19:45:38 +08:00
d8e8f41230 move core/session to web/session 2020-10-05 19:04:57 +08:00
9e6b8fcf34 Merge pull request #4248 from flycash/rft/renameInfra
rename infrastructure to core
2020-10-05 18:40:20 +08:00
48e98482f7 rename infrastructure to core 2020-10-05 18:14:01 +08:00
ff7a8b966b Merge pull request #4247 from flycash/adt/cache
Adapter: cache API
2020-10-05 14:46:13 +08:00
f9bef68aa9 Adapter: cache API 2020-10-05 14:35:12 +08:00
484beb8bad Merge pull request #4245 from flycash/ftr/cache-ctx
Add context to cache API
2020-10-05 14:25:09 +08:00
43560dede4 Merge pull request #4246 from jianzhiyao/frt/seperate_orm_alone
seperate orm alone & deadlock in task module
2020-10-05 14:24:51 +08:00
c435d231ab complete check 2020-10-05 10:38:14 +08:00
b838683731 add api for testing 2020-10-05 10:33:23 +08:00
70cca5e298 make code testable in task module 2020-10-05 10:13:29 +08:00
f1cca45d8d fix deadlock about changed sign 2020-10-05 01:31:27 +08:00
4dc694411f fix deadlock in task module 2020-10-05 00:16:58 +08:00
3364c609de Add context to cache API 2020-10-04 23:12:29 +08:00
c5d43e87fe seperate orm alone 2020-10-04 22:16:19 +08:00
b89d9511ab Merge pull request #4237 from flycash/rft/cache-decup
Decouple web module from cache module
2020-10-04 19:01:31 +08:00
0b7ece44cf Merge pull request #4244 from AllenX2018/develop
testing: fix temporary create failed on Windows
2020-10-04 18:55:37 +08:00
6ffbc0a2b8 testing: fix temporary create failed on Windows
We are creating temporary files on the root directory of beego now
This PR using system temporary directory for testing.

Fixes #4243
2020-09-30 15:50:40 +08:00
325a0821c1 Merge pull request #4239 from flycash/rft/httplib
decouple httplib module from web module and config module
2020-09-29 22:22:27 +08:00
dd3f1ce9be decouple httplib from config 2020-09-27 00:44:02 +08:00
463e96447a decouple httplib from web module 2020-09-27 00:37:46 +08:00
03498529b9 Decouple web module from cache module 2020-09-22 22:58:58 +08:00
9a7c43c404 Merge pull request #4235 from flycash/ftr/adminCommand
decouple web module and task module
2020-09-21 22:50:08 +08:00
44127edefc design Command for governor module & decouple web module from task module 2020-09-20 14:52:29 +00:00
089006525e Merge pull request #4234 from flycash/ftr/multi-sever
Multi server support
2020-09-20 22:44:32 +08:00
2846043f2a Fix UT 2020-09-20 14:27:30 +00:00
e6a257f987 Fix BUG 2020-09-20 12:02:28 +00:00
2473e69417 Rewrite admin service by using multiple server feature 2020-09-20 15:36:53 +08:00
d455805a0a Multiple server refactor 2020-09-20 15:36:53 +08:00
bd1cfefec7 rft: Move build info to pkg 2020-09-20 15:36:53 +08:00
7effdb0e7d Merge pull request #4233 from flycash/esIndexName
Add IndexNaming interface
2020-09-20 14:22:32 +08:00
b027968c0b Merge pull request #4231 from flycash/ut/log
Add tests for log module
2020-09-20 13:50:22 +08:00
961f300c14 Fix JL tests 2020-09-20 13:15:48 +08:00
7570abd310 Merge pull request #4232 from flycash/stale-workflows
Add stale.yml
2020-09-19 23:57:40 +08:00
7c8136710c Add stale.yml 2020-09-19 23:54:33 +08:00
a3ece98cec Add IndexNaming interface so users can custom the index name when they use es as the logger 2020-09-19 23:49:52 +08:00
a31dce6216 Merge pull request #4230 from jianzhiyao/frt/movement_for_4198
movement for 4198
2020-09-19 23:24:57 +08:00
a1782cc22d Add tests for log module 2020-09-19 23:14:17 +08:00
67f64afa85 movement for 4198 2020-09-19 21:45:37 +08:00
2539fe3831 Merge pull request #4229 from wangle201210/develop-2.0
Provides a quick format method by PatternLogFormatter struct
2020-09-19 21:25:12 +08:00
05c125ec2d change to pointer receiver 2020-09-19 20:18:09 +08:00
6e638ef6c8 Provides a quick format method by PatternLogFormatter struct 2020-09-19 18:28:53 +08:00
df043f22fc Merge pull request #4225 from HITWHTigerLiu/develop-2.0
Empty field in validator.Error when label struct tag is not declared #4222
2020-09-17 21:27:18 +08:00
fbaf3380c6 Merge pull request #4203 from jianzhiyao/frt/proposal_4105
warpping for global modelCache
2020-09-17 21:11:33 +08:00
b7bc57c4d1 delete interface 2020-09-16 19:46:14 +08:00
26208a53e6 session: adds CookieSameSite to ManagerConfig 2020-09-15 18:05:33 -03:00
32cdda96bd Merge pull request #4205 from AllenX2018/postgres-query-builder
PostgresQueryBuilder
2020-09-14 21:21:59 +08:00
5995b00fa2 Merge branch 'develop-2.0' into frt/proposal_4105 2020-09-14 19:16:09 +08:00
5618df8c76 Empty field in validator.Error when label struct tag is not declared #4222 2020-09-14 16:18:24 +08:00
c6c9ad46f9 PostgresQueryBuilder 2020-09-14 09:50:28 +08:00
5973ef107c Merge pull request #4221 from flycash/ftr/log_format
fix 4219
2020-09-12 00:02:51 +08:00
b575fa1ebe fix 4219 2020-09-11 23:48:45 +08:00
6bbca96c6c Merge pull request #4220 from flycash/ftr/log_format
refactor log module
2020-09-11 22:08:05 +08:00
63cd8e4e15 refactor log module 2020-09-11 21:47:22 +08:00
93736a8e66 Merge pull request #4216 from flycash/ftr/log_format
Log format support
2020-09-11 00:11:27 +08:00
654d87b210 Merge log_format 2020-09-10 23:31:49 +08:00
0048b7d158 Merge pull request #4188 from IamCathal/custom-log-formatter-third-pr
Custom logging format PR#3
2020-09-10 22:40:48 +08:00
00e44952ff optimize modelCache 2020-09-09 19:04:34 +08:00
8982f5d702 Add unit tests for custom log formatter
Also moved is Colorful check to WriteMsg function to make the interface for user's using the custom logging formatting simpler. The user does not have to check if the text is colorful now, the WriteMsg function handles it.
2020-09-09 00:23:57 +01:00
6612bc4c2a Merge pull request #4214 from flycash/rft/dbOption
Optimize orm by using BDOption rather than hints
2020-09-09 00:06:44 +08:00
f580a714d5 Optimize orm by using BDOption rather than hints 2020-09-08 21:44:14 +08:00
9ccd58bfff Merge pull request #4211 from flycash/adt/all
allow users to ignore some table when run orm commands
2020-09-07 21:52:39 +08:00
0f50b07a20 allow users to ignore some table when run orm commands 2020-09-07 21:40:44 +08:00
b86cf22fc4 Merge pull request #4210 from flycash/adt/all
Move pr 3784
2020-09-07 20:53:45 +08:00
6bf01eaeca Move pr 3784 here 2020-09-07 20:37:05 +08:00
8e015deee5 Merge pull request #4208 from flycash/adt/all
Adapter: all module
2020-09-06 19:58:46 +08:00
3acda41bc7 Fix UT 2020-09-06 10:39:20 +00:00
5b3dd7e50f Adapter: orm 2020-09-06 13:33:52 +08:00
f4a43814be Adapter: utils 2020-09-05 18:07:42 +08:00
35f1bd2119 Adapter: testing 2020-09-05 16:58:49 +08:00
f6c95ad534 Adapter: swagger module 2020-09-05 16:56:56 +08:00
f1950482c2 Adapter: plugin 2020-09-05 16:54:22 +08:00
1dae2c9eb3 Adapter: web module 2020-09-05 16:24:19 +08:00
8ef9965eef Adapter: session module 2020-09-03 23:37:07 +08:00
3530457ff9 Adapter: toolbox module 2020-09-03 21:34:57 +08:00
cbd51616f1 adapter: validation module 2020-09-02 23:23:48 +08:00
bdd8df6751 adapt migration 2020-09-02 21:01:54 +08:00
8fc4f8847c adapt grace and metric 2020-09-02 20:43:35 +08:00
3bf5cde38c adapt context 2020-09-02 20:36:53 +08:00
7a53baaf9b rename modelRegister to modelCacheHandler 2020-09-02 00:33:46 +08:00
7574b91760 add type modelRegister interface into Ormer 2020-09-02 00:26:25 +08:00
78d91062c9 Adapt new API to old API: httplib 2020-09-01 22:16:49 +08:00
23792401b5 Merge pull request #4201 from jianzhiyao/frt/proposal_4105
WIP:supports for proposal 4105
2020-09-01 22:05:15 +08:00
e54dbabf0b movement for global modelCache 2020-09-01 21:56:48 +08:00
cdc8110ea4 Merge pull request #4202 from flycash/adt/config
Using new API to adapt to old API
2020-09-01 21:50:08 +08:00
f6519b29a8 Merge pull request #4198 from CadenGuo/enhancement/orm_mysql_operator_consolidate
Enhancement/Add a new MySQL operator for strict case sensitive query
2020-09-01 21:33:41 +08:00
185d55eb46 adapt config 2020-09-01 21:29:26 +08:00
91410be722 orm_test:use predefined variable to check db driver 2020-08-31 15:47:37 +00:00
ff53e12191 skip strictexact operator test for db drivers other than mysql 2020-08-31 15:29:48 +00:00
8e879726fe Merge pull request #4200 from flycash/ftr/config-sub
Implement Sub, Unmarshaler and OnChange methods for yaml, json, xml
2020-08-31 22:29:14 +08:00
33b052bc7a support json 2020-08-31 14:15:01 +00:00
087399c44a support xml 2020-08-31 13:57:26 +00:00
f4f200cf04 enhance yaml 2020-08-31 13:02:38 +00:00
0a58428220 Merge pull request #4199 from flycash/rft/task-api
Add ctx to Task module API
2020-08-31 19:43:53 +08:00
60bb057783 add a new mysql operator for force case sensitie query 2020-08-31 03:40:18 +00:00
c0462f75bf Add ctx to Task module API 2020-08-30 16:18:59 +00:00
5cf33f2655 Merge pull request #4197 from flycash/rft/session-api
Add ctx to session API
2020-08-31 00:14:52 +08:00
670064686e Add ctx to session API 2020-08-30 15:39:07 +00:00
8736ffaf6f use 'BINARY' key word for exact operator for mysql db 2020-08-30 23:38:52 +08:00
0019e0fc1b Merge pull request #4195 from flycash/ftr/etcd
Add contect as first parameter for all config method
2020-08-30 00:42:15 +08:00
03bec05714 Add contect as first parameter for all config method 2020-08-29 16:25:20 +00:00
e831b97eb8 Merge pull request #4194 from flycash/ftr/etcd
Support etcd
2020-08-29 22:44:55 +08:00
81b9a1382a Fix UT 2020-08-29 14:27:06 +00:00
0189e6329a Add global logging override 2020-08-28 18:47:28 +01:00
6684924e99 empty commit to restart CI again 2020-08-28 18:30:41 +01:00
e0a934af1d empty commit to restart CI 2020-08-28 18:24:57 +01:00
8178f035a0 Custom formatting opts implementation 2020-08-28 18:18:28 +01:00
2b39ff7837 New opts formatter working for console 2020-08-28 18:00:45 +01:00
c2361170b3 Support etcd 2020-08-29 00:07:33 +08:00
5b35bf6065 Merge pull request #4192 from AllenX2018/supplement-datetimePrecision-UT
supplement datetime precision UT
2020-08-26 19:52:19 +08:00
14c911e9d7 Merge pull request #4190 from flycash/ftr/time-precision
Support precision
2020-08-26 12:45:17 +08:00
9472cba6c9 Fix UT 2020-08-26 04:16:09 +00:00
b83094ac1e supplement datetime precision UT 2020-08-26 11:51:05 +08:00
f946a35acd Merge pull request #4191 from mchtech/rawseter_fielder
fix issue #3776
2020-08-26 10:49:38 +08:00
9bd3a27e80 fix #3776 2020-08-25 23:36:15 +08:00
1cb0ff560d Support precision 2020-08-25 13:07:21 +00:00
cceecad8c2 Merge pull request #4186 from AllenX2018/Feature-datetime-precision
Feature: implement the time precison for time.Time type
2020-08-25 21:05:08 +08:00
d24f861629 empty commit to restart CI 2020-08-24 21:00:58 +01:00
c2471b22ad Remove ineffectual assignments
Removed 3 lines due to warning from test suite saying these lines had innefectual assignments
2020-08-24 20:54:55 +01:00
c5970766a3 Add init to es.go 2020-08-24 20:41:39 +01:00
48a98ec1a5 Fix init for alils.go 2020-08-24 20:39:53 +01:00
ed1d2c7f6e Add custom logging format functionality and global formatter functionality 2020-08-24 20:22:38 +01:00
7a94996e22 Feature: implement the time precison for time.Time type 2020-08-24 20:23:54 +08:00
597c55d547 Merge pull request #4183 from flycash/rft/module-2
Reorganize package
2020-08-23 21:43:48 +08:00
026e8bc55a Merge branch 'develop-2.0' of https://github.com/astaxie/beego into rft/module-2 2020-08-23 21:25:15 +08:00
581e48679e Merge pull request #4173 from AllenX2018/fix-bug-queryRow
Fix issue 3866
2020-08-23 21:04:34 +08:00
09afe0ae8e Merge pull request #4179 from IamCathal/custom-log-formatter-secondpr
Custom log formatter secondpr
2020-08-22 21:36:50 +08:00
08e49ca323 Test empty commit 2020-08-20 19:32:42 +01:00
e1da804b2b Add format func to alils 2020-08-20 19:20:30 +01:00
705e091593 Add format call before logging 2020-08-20 19:06:51 +01:00
6bdedff457 LogFormatter Implementation 2020-08-20 19:00:35 +01:00
f3be6dd2e9 Merge pull request #4173 from AllenX2018/fix-bug-queryRow
Fix issue 3866
2020-08-20 22:25:37 +08:00
9fe353dd0b Fix issue 3886 2020-08-20 10:00:49 +08:00
9003ca3eef Merge pull request #4174 from IamCathal/custom-log-formatter-firstpr
Custom Log Formatter PR#1
2020-08-19 23:37:44 +08:00
ff5ac3adf4 Update signature of WriteMsg in es.go 2020-08-19 16:20:19 +01:00
ca4a217783 Merge branch 'develop-2.0' into custom-log-formatter-firstpr 2020-08-19 16:05:42 +01:00
e6ea307549 Merge pull request #4175 from flycash/ftr/config
Add more methods to Configer
2020-08-19 22:44:43 +08:00
2c16c7b917 Add more methods to Configer 2020-08-19 22:09:05 +08:00
77ddc3338f Fix file path logging for enableFullFilePath 2020-08-19 15:07:46 +01:00
ac3a549187 Fix test with new parameters 2020-08-19 14:21:29 +01:00
fe56de06b5 Add enableFullFilePath field to BeeLogger 2020-08-18 21:30:39 +01:00
6c002a3124 Update WriteMsg signatures for custom log formatting update 2020-08-18 21:30:11 +01:00
cead72c6df Merge pull request #4170 from flycash/rft/ormFilter
Refactor orm filter
2020-08-18 22:46:45 +08:00
7fe4eaef50 Refactor orm filter 2020-08-18 14:31:06 +00:00
63599c0032 Merge pull request #4168 from flycash/ftr/layout
Add git hooks
2020-08-18 21:08:56 +08:00
4db256c9fb Add git hooks 2020-08-18 20:56:15 +08:00
c548764c8e Merge pull request #4163 from flycash/ftr/rmFiles
Remove files
2020-08-16 23:17:05 +08:00
b4a85c8f13 Remove files 2020-08-16 23:09:19 +08:00
94f476fa39 Merge pull request #4158 from jianzhiyao/frt/fix_spk_upsert
fix:return error when calling ``InsertOrUpdate`` is successful with string primary key
2020-08-16 21:21:25 +08:00
8574e30b3a Merge pull request #4160 from AllenX2018/Improve-orm.Fielder-function
fix issue #3776
2020-08-14 22:20:07 +08:00
7442919f5a fix issue #3776 2020-08-14 17:11:52 +08:00
f6ec4efc70 Merge pull request #4156 from flycash/ftr/bean
Supporting default value by using filter
2020-08-14 15:47:50 +08:00
7b899aa9af add ErrLastInsertIdUnavailable 2020-08-14 15:09:47 +08:00
f73eee75ff Merge develop-2.0 2020-08-14 14:34:59 +08:00
739b8bab0c fix UT 2020-08-14 10:31:08 +08:00
139c393f08 add const ErrLastInsertIdUnavailable 2020-08-14 09:59:11 +08:00
bdec93986b Bean: Support autowire by tag
Orm: Support default value filter
2020-08-13 21:26:39 +08:00
7ce0fde171 fix:return error when calling `InsertOrUpdate` is successful with string primary key 2020-08-13 19:14:00 +08:00
d6a2621b3c Merge pull request #4137 from phiphi282/change_redis_provider
Add additional options to redis session prov
2020-08-12 13:38:44 +08:00
813a4df3c5 Make sure expiry time is in seconds 2020-08-11 16:21:43 +02:00
7267f5e573 Add new config option into provider struct 2020-08-11 16:09:29 +02:00
5bc8d90d7f Merge pull request #4150 from jianzhiyao/frt/fix_3830
fix:return error after inserting data when primary key is string
2020-08-11 21:22:17 +08:00
2d1c02e1c1 Merge branch 'develop-2.0' of https://github.com/astaxie/beego into frt/fix_3830
# Conflicts:
#	pkg/orm/orm_test.go
2020-08-11 17:37:24 +08:00
9ca9535c48 fix:return error after inserting data when primary key is string 2020-08-11 16:53:31 +08:00
d1d9df74c7 Merge branch 'develop-2.0' of github.com:astaxie/beego into change_redis_provider 2020-08-11 10:47:06 +02:00
d326d74c34 Merge pull request #4148 from flycash/fix/end2end
Fix prometheus and opentracing bug found in end2end tests
2020-08-11 16:33:54 +08:00
82178a487b Merge develop-2.0 and resolve conflict 2020-08-11 08:16:04 +00:00
a1b7fd3c93 Merge pull request #4147 from jianzhiyao/frt/specify_index_2
specify index
2020-08-11 16:13:13 +08:00
0813471202 Merge branch 'develop-2.0' of github.com:astaxie/beego into change_redis_provider 2020-08-11 09:52:53 +02:00
ce698aacf6 rm some methods 2020-08-11 12:06:02 +08:00
c22af4c611 Fix Tracing and prometheus bug 2020-08-11 03:23:38 +00:00
f8c0e6fec5 fix UT 2020-08-11 00:06:36 +08:00
882f1273c8 add UT for specifying indexes 2020-08-10 23:27:03 +08:00
5a1fa4e1ec specify index 2020-08-10 18:46:16 +08:00
d05460237c Merge pull request #4145 from flycash/ftr/ormTracing
Support prometheus and opentracing for ORM and httplib module
2020-08-10 13:53:23 +08:00
75107f735e Support opentracing filter 2020-08-09 14:59:41 +00:00
2e891152dd deprecated httplib and then support prometheus for httplib 2020-08-09 14:59:41 +00:00
dec98f004c Support opentracing filter for Orm 2020-08-09 14:59:41 +00:00
26b016a3a4 Merge pull request #4143 from flycash/fix/moveIni
Move init so it will be default implementation of config
2020-08-09 22:51:47 +08:00
19aae0b7e1 Merge pull request #4107 from AllenX2018/fix-comment-router-issue
add comment router path configuration
2020-08-09 19:23:05 +08:00
2e192e1ed0 Depracated config module and recommend using pkg/config 2020-08-08 13:26:30 +00:00
f9a3eae9d5 Move init so it will be default implementation of config 2020-08-08 13:17:49 +00:00
7fc1e4de96 Merge pull request #4141 from flycash/ftr/ormInterceptor
Orm filter support
2020-08-08 20:52:37 +08:00
993ccac2bd fix comment router generate issue 2020-08-08 16:17:12 +08:00
2fd65a469c Support prometheus 2020-08-07 14:14:07 +00:00
a2fa073072 Merge pull request #4139 from IamCathal/coc-grammar-fixes
More minor grammar fixes
2020-08-07 22:00:22 +08:00
08cec9178f Orm filter support 2020-08-07 13:45:24 +00:00
63b3fc4a99 Fix retry amount comment 2020-08-06 16:09:06 +01:00
1b4bb43df0 More minor grammar fixes 2020-08-06 16:07:18 +01:00
ec55edfbc4 Add additional options to redis session prov
Adding option for frequency of checking timed out connections as well as
an option to specify retries.

These changes make redis provider more stable since connection problems
are becoming fewer.

Since redigo does not have this options and since redis_sentinel and
redis_cluster are using go-redis as a client, this commit changes from
redigo to go-redis for redis session provider.

Added tests for redis session provider as well.
2020-08-06 11:14:36 +02:00
2fce8f9d1b Merge pull request #4124 from phiphi282/session_exists_return_err
Update session provider interface to return errors on SessionExist
2020-08-06 09:17:49 +08:00
15489fa76a Merge pull request #4135 from IamCathal/grammar-fixes
Minor grammar fixes
2020-08-06 09:05:30 +08:00
e7d8bab5d9 Improved definition of DefaultEvery 2020-08-05 17:56:11 +01:00
2f5683610f Minor grammar fixes 2020-08-05 17:50:05 +01:00
5c8c088684 Revert "Change interface in session README"
This reverts commit 6f5c5bd3a6.
2020-08-05 18:33:17 +02:00
009074725e Move interface change to pkg/session/README.md 2020-08-05 18:32:33 +02:00
ce50ca22d7 Merge branch 'develop-2.0' of github.com:astaxie/beego into session_exists_return_err 2020-08-05 18:30:19 +02:00
3052c64b6c Revert "Add error to SessionExist interface"
This reverts commit 28e6b3b924.
2020-08-05 18:29:47 +02:00
5f2f6e4f86 Add interface change in pkg folder 2020-08-05 18:29:22 +02:00
3382a5baa1 Merge pull request #4134 from flycash/ftr/ormInterceptor
Deprecated old web module
2020-08-05 22:22:59 +08:00
882aa9b967 Deprecated old web module 2020-08-05 21:57:20 +08:00
02972d8702 Merge pull request #4130 from flycash/ftr/prometheuseAndOpentracing
Support prometheus and opentracing by using FilterChainFunc
2020-08-05 15:46:03 +08:00
261b704d8b Fix UT 2020-08-05 07:25:34 +00:00
6c6cf91741 Support prometheus and opentracing filter 2020-08-04 23:15:42 +08:00
ae8461f95d Merge pull request #4125 from flycash/ftr/middleware
Support FilterChain
2020-08-04 23:06:18 +08:00
aa3987f816 Merge remote-tracking branch 'origin/develop' into ftr/middleware 2020-08-04 22:26:01 +08:00
3dc5ec1060 Merge pull request #4129 from astaxie/revert-4128-fix-ci-fail
Revert "fix CI fail for connection log test"
2020-08-04 21:38:50 +08:00
1961c1e441 Revert "fix CI fail for connection log test" 2020-08-04 21:37:46 +08:00
787bb60b42 Merge pull request #4128 from AllenX2018/fix-ci-fail
fix CI fail for connection log test
2020-08-04 21:14:45 +08:00
12b984861d fix CI fail for connection log test 2020-08-04 20:32:07 +08:00
79ffef90e3 support filter chain 2020-08-04 07:26:51 +00:00
310161f9d4 Merge pull request #4126 from flycash/fix/secureFlagV1
XSRF add secure and http only flag
2020-08-03 21:24:23 +08:00
a0d1c42dac XSRF add secure and http only flag 2020-08-03 21:04:33 +08:00
6f5c5bd3a6 Change interface in session README 2020-08-03 13:33:30 +02:00
28e6b3b924 Add error to SessionExist interface
Implement changed interface for all default providers as well and change
tests accordingly
2020-08-03 13:31:49 +02:00
9e1346ef4d Merge pull request #4113 from flycash/ftr/usingPkg
using pkg module
2020-07-31 13:40:39 +08:00
9f295067b7 Resolve conflict 2020-07-30 22:44:44 +08:00
71776e4bef Merge pull request #4114 from wangle201210/develop-2.0
Add the operator(>,>=,<,<=,=,!=) of orm
2020-07-30 16:51:02 +08:00
87b40ee9e7 Merge pull request #4116 from livelyRyan/patch-2
添加 BConfig.Listen.ClientAuth 字段及处理逻辑
2020-07-30 16:07:00 +08:00
7831638f37 移除多余的条件判断 2020-07-30 14:48:46 +08:00
5203804165 调整默认配置中的 ClientAuth 值,使之与原来的行为保持一致 2020-07-30 14:46:17 +08:00
d4074b5004 Merge pull request #4103 from flycash/ftr/newOrmWithDB
Enhance: NewOrmUsingDB & remove useless methods
2020-07-30 11:43:47 +08:00
0815e77f9a 修复笔误产生的拼写错误 2020-07-30 11:20:22 +08:00
c46ba86215 修复笔误产生的拼写错误 2020-07-30 11:18:14 +08:00
9d23e5a3fb 简化代码写法 2020-07-30 11:03:32 +08:00
513a4afff1 对 Listen 结构体增加 ClientAuth 字段
对 Listen 结构体增加 ClientAuth 字段,赋予默认配置对象该字段值为 tls.VerifyClientCertIfGiven,与原代码逻辑的默认值保持一致
2020-07-30 10:59:32 +08:00
15e11931fc 添加对 BConfig.Listen.ClientAuth 字段的逻辑处理。当指定了该配置时,使用配置的值来作为验证客户端的方式。如果没指定,使用默认值 tls.RequireAndVerifyClientCert 2020-07-30 10:53:30 +08:00
7d561607d8 Merge pull request #4111 from liuhaogui/develop
添加配置文件路径环境变量
2020-07-30 09:14:12 +08:00
22b8cae73b Add the operator(>,>=,<,<=,=,!=) of orm
eg:
qs.Filter("counts__>=","20")
qs.Filter("counts__!=","20")
2020-07-29 23:23:02 +08:00
aa06a10493 uing pkg module 2020-07-29 14:42:27 +00:00
9b58c2836c Merge develop-2.0 and resolve confilct 2020-07-29 22:26:29 +08:00
15f04b8da4 add env BEEGO_CONFIG_PATH 2020-07-29 21:57:16 +08:00
7312197732 Merge pull request #4098 from jianzhiyao/frt/stmt_config
make stmt cache size configurable & wrap kv
2020-07-29 20:57:07 +08:00
e87de70c6d adapt wrapping kv 2020-07-29 00:45:41 +08:00
4304b40a82 Merge branch 'frt/wrap_kv' into frt/stmt_config
# Conflicts:
#	pkg/orm/constant.go
#	pkg/orm/db_alias.go
2020-07-28 18:32:24 +08:00
e8facd28f5 wrap kv 2020-07-28 17:37:36 +08:00
54ef476600 add tag interfaces and remove log.go 2020-07-28 06:28:51 +00:00
756df9385f make stmt cache size configurable 2020-07-28 12:57:19 +08:00
21f281655d remove QueryRelated and QueryRelatedCtx 2020-07-27 21:22:40 +08:00
2e7fb81348 deprecated orm.go and add NewOrmUsingDB method 2020-07-27 21:19:34 +08:00
ebc0207909 Merge pull request #4096 from jianzhiyao/request_context
fix memory leak of request context
2020-07-27 18:04:37 +08:00
2386c9c80d delete useless if-stmt 2020-07-26 22:37:42 +08:00
b9f9fcca5f Merge pull request #4099 from jianzhiyao/fix_3869
orm.rawPrepare support FlatParams
2020-07-26 21:01:39 +08:00
16d71893cd orm.rawPrepare support FlatParams 2020-07-26 19:40:13 +08:00
cfff0f3b46 fix memory leak of request context 2020-07-25 00:00:34 +08:00
93eb7c6b83 Merge pull request #4091 from flycash/ftr/moveToPkg
Ftr: move to pkg
2020-07-23 09:36:29 +08:00
79c2157ad4 Fix UT 2020-07-22 15:46:29 +00:00
30eb889a91 Format code 2020-07-22 23:00:06 +08:00
9c51952db4 Move package 2020-07-22 22:55:59 +08:00
16b66509f6 Merge pull request #4083 from IamCathal/content-length
Add Content-length field for logging
2020-07-21 15:47:58 +08:00
d5695060c5 Merge pull request #4082 from flycash/ftr/newOrm
Refactor RegisterDatabase
2020-07-21 15:47:40 +08:00
af2143f8fb Merge pull request #4084 from astaxie/develop
Align develop-2.0
2020-07-21 09:36:54 +08:00
a66b9950e7 Add Content-length field for logging 2020-07-20 21:23:21 +01:00
44460bc457 Refactor RegisterDatabase 2020-07-20 15:52:40 +00:00
41feb3a711 Merge pull request #4078 from jianzhiyao/frt/orm_merge
refactor orm
2020-07-20 23:50:40 +08:00
b6f7d30f9f fix unit test 2020-07-20 19:10:57 +08:00
4aad313de7 do not judge tx status in txOrm 2020-07-20 17:34:58 +08:00
aefe21b63a complete error log 2020-07-20 17:25:27 +08:00
32da446eb1 refactor orm 2020-07-19 23:46:42 +08:00
d9c016ed98 Merge pull request #4076 from flycash/ftr/taskLog
Store nearest error info
2020-07-19 23:23:13 +08:00
7258ef113a Store nearest error info 2020-07-19 14:34:57 +00:00
d6779c4a90 Merge pull request #4075 from flycash/fix/stable-ut
Fix orm test when using Driver = mysql
2020-07-19 21:22:36 +08:00
192a278a2a Fix orm test when using Driver = mysql 2020-07-19 12:56:58 +00:00
7a48fbb698 Merge pull request #4066 from playHing/self-dev
Fix concurrent issue of context/input Query method
2020-07-16 13:52:11 +08:00
3e2c795410 Rlock for form query 2020-07-15 20:44:59 +08:00
55e6298f29 Fix concurrent form parsing and getting 2020-07-15 20:44:59 +08:00
b50fb44950 Add bench test on context input query 2020-07-15 20:44:59 +08:00
9d936c58bf Merge pull request #4070 from flycash/develop-2.0
Move orm to pkg/orm
2020-07-15 10:50:05 +08:00
ffe1d52120 Move orm to pkg/orm 2020-07-15 10:05:11 +08:00
1c0714405a Merge pull request #4068 from jianzhiyao/fix_3898
fix `index out of range` when sid len = 1
2020-07-15 00:03:59 +08:00
678b90385b add log 2020-07-14 09:57:13 +08:00
5940ae33c2 fix index out of range when sid len = 1
add unit test for sess_file.go
2020-07-13 19:14:53 +08:00
3db31385cf Merge pull request #4065 from Acmefocus/develop
update README.md
2020-07-11 23:16:36 +08:00
2b9aaa5b0d update README.md
Signed-off-by: Acmefocus <107723772@qq.com>
2020-07-10 09:58:06 +08:00
dced745d55 Merge branch 'develop' of https://github.com/Acmefocus/beego into develop 2020-07-09 18:15:25 +08:00
25ba78ea72 update README.md
Signed-off-by: Acmefocus <107723772@qq.com>
2020-07-09 18:14:31 +08:00
863b5bd0f4 Merge branch 'develop' of https://github.com/Acmefocus/beego into develop
Signed-off-by: Acmefocus <107723772@qq.com>
2020-07-09 17:59:07 +08:00
ba3153621a Merge branch 'develop' of https://github.com/Acmefocus/beego into develop 2020-07-09 17:47:46 +08:00
40cdc877b6 Update README.md
Signed-off-by: Acmefocus <107723772@qq.com>
2020-07-09 17:38:08 +08:00
76debb1899 Update README.md 2020-07-09 17:18:01 +08:00
35dcc3df7c Merge pull request #4058 from a631807682/fix/issues/4054
Fix response payload too large
2020-07-09 16:41:11 +08:00
c3f14a0ad6 refactor: log error when payload too large 2020-07-09 09:45:40 +08:00
8ee167bc7b Merge pull request #4051 from gmelodie/sleep-on-reconnect-3972
Add sleep on reconnect
2020-07-09 09:41:04 +08:00
2eccb23461 Add sleep on reconnect functionality 2020-07-08 17:30:34 +01:00
28d3f624a3 Merge pull request #4055 from tayoogunbiyi/develop
Allow Healthcheck endpoint return JSON for Kubernetes
2020-07-08 23:51:03 +08:00
926b80d1d8 Merge pull request #4061 from flycash/race-condition
Fix 4059
2020-07-08 23:49:54 +08:00
c08b27111c Fix 4059 2020-07-08 23:32:18 +08:00
03f78b2e4a fix: add error code support 2020-07-08 18:09:01 +08:00
946a42c021 fix: response http 413 when body size larger then MaxMemory. 2020-07-08 17:14:52 +08:00
d7b0d55357 added extra check for same response lengths 2020-07-07 17:23:52 +01:00
728bf34006 refacted cache health check from toolbox 2020-07-07 16:46:59 +01:00
e0f8c6832d added test for buildingHealthCheckResponse 2020-07-07 16:28:16 +01:00
469dc7bea9 refactored the building of healthcheck response map 2020-07-07 16:09:22 +01:00
ca0c64b69e refactored tests for health check endpoint 2020-07-07 15:21:38 +01:00
5a4a082af0 renamed functions for clarity 2020-07-07 14:54:21 +01:00
9dc660c1da Merge pull request #4056 from gmelodie/reconn-bug-3971
Fix reconnection bug in logs/conn.go
2020-07-07 20:25:44 +08:00
d8724cb122 Add error returning to writeln 2020-07-06 21:38:47 +02:00
fc56c562db Fix logger reconnection 2020-07-06 21:38:47 +02:00
8d1a9bc92e added tests for health check endpoints 2020-07-06 19:34:48 +01:00
db547a7c84 added test for execJson 2020-07-06 16:04:29 +01:00
7c575585e9 added conditional json flag when trying to view healthchecks 2020-07-06 15:27:12 +01:00
289f86247e Merge pull request #4053 from flycash/ftr/test-docker
Add docker-compose to support running unit test locally
2020-07-05 22:08:20 +08:00
ca9b21bb30 Add docker-compose to support running test 2020-07-04 13:42:20 +00:00
d6ef33feee Merge pull request #4045 from flycash/preprare-1.12.2
Remove tidb dependency
2020-06-30 23:16:41 +08:00
2f5ed5b433 Remove tidb dependency 2020-06-30 21:04:37 +08:00
9c18dbe7dc Merge pull request #4044 from flycash/upgrade_version
upgrade version
2020-06-30 20:58:14 +08:00
01219944a4 upgrade version 2020-06-30 20:55:31 +08:00
4fac6ceb3f Merge pull request #4039 from flycash/fixbug
Fix ES bug
2020-06-30 13:18:13 +08:00
1c4085e7ea Update es.go 2020-06-30 10:12:10 +08:00
2117562113 Update es.go 2020-06-30 10:09:36 +08:00
1f9da8d75b Fix ES bug 2020-06-29 22:25:22 +08:00
9dea9f9ae7 Merge pull request #3994 from HarryWang29/develop
update support bit operation
2020-06-29 20:27:36 +08:00
0f6735e20d Merge branch 'develop' of https://github.com/astaxie/beego into develop
 Conflicts:
	go.mod
	go.sum
2020-06-29 16:48:03 +08:00
ad68e8d866 Merge pull request #4033 from jianzhiyao/develop
make redis client idle timeout configurable
2020-06-28 23:14:28 +08:00
26beef756f Merge pull request #4038 from flycash/fixbug
Fix ES index problem
2020-06-28 23:14:07 +08:00
5c9cc805a1 make redis client idle timeout configurable 2020-06-28 22:20:46 +08:00
de51bd28d7 Fix ES index problem 2020-06-28 21:12:12 +08:00
6b6a0e8a56 Merge pull request #4032 from jianzhiyao/develop
fix strings.Repeat panic
2020-06-26 17:51:47 +08:00
8039cc8e59 Merge pull request #4017 from guhan121/fix#4000
Prohibit multiple calls SetDefaultMessage.
2020-06-26 17:49:36 +08:00
b88b7d2899 fix strings.Repeat panic 2020-06-25 23:48:07 +08:00
e725192072 fix #4000 2020-06-25 22:11:32 +08:00
469f2c226d Merge pull request #3998 from guhan121/go_modules_route_compatibility
for go modules, generate route by `GO111MODULE=on`
2020-06-25 20:30:27 +08:00
828b20163d Merge pull request #4029 from flycash/feature/buildInfo
Add build info for prometheus
2020-06-25 18:37:11 +08:00
9c5eab4834 Add build info for prometheus 2020-06-25 17:44:40 +08:00
1813d414ae Merge pull request #4027 from flycash/develop
Move many PR's change here since the original authors are responseless
2020-06-25 02:17:49 +08:00
6052524a28 Merge pull request #4028 from jianzhiyao/develop
acquire() in Lock
2020-06-23 23:58:42 +08:00
3ce68d6a30 Move many PR's change here since the original authors are responseless 2020-06-23 23:14:51 +08:00
89420eacd0 go destroy 2020-06-23 23:05:58 +08:00
6d9862b924 acquire() in Lock 2020-06-23 22:29:41 +08:00
96658121dc Merge pull request #3818 from dbt4516/develop
Get the real location of the log directory before using filepath.Walk function when remove old logs
2020-06-23 21:17:14 +08:00
43a3623f51 Merge pull request #3803 from yinggaozhen/fix-statistics
GetMapData change to read lock
2020-06-23 21:08:32 +08:00
089dfbdbee Merge pull request #4016 from huija/develop
Update redis.go
2020-06-23 20:41:42 +08:00
526a5463d6 Merge pull request #4025 from jianzhiyao/develop
Fix: Too Many Prepare Statement
2020-06-23 20:33:04 +08:00
a28d294a83 upgrade acquire method return *sql.Stmt 2020-06-23 13:46:19 +08:00
f70fd5babf add comments on Scan func 2020-06-23 12:32:26 +08:00
a764e17fbf check ci 2020-06-23 10:43:51 +08:00
f5c580a403 Merge pull request #3739 from nuczzz/develop
fix graceful bug: old process didn't exist when graceful restart
2020-06-23 00:10:53 +08:00
7210dc24b6 Merge pull request #3743 from Colstuwjx/fix/orm-end-printstack
Fix/orm end printstack
2020-06-22 23:59:16 +08:00
1060dc7df8 Merge pull request #4026 from flycash/develop
fix UT
2020-06-22 23:36:25 +08:00
3ab1e48217 fix UT 2020-06-22 23:24:15 +08:00
a5e8344a0a add stmt garbage recycle 2020-06-22 23:23:52 +08:00
e1386c448c Merge pull request #4022 from jianzhiyao/develop
stmt: fix bug of non concurrent security & add double check
2020-06-21 18:01:14 +08:00
6e4d0917b2 Merge pull request #4023 from flycash/feature/prometheus
Change prometheus patter
2020-06-21 17:39:02 +08:00
9b43a90138 Change prometheus patter 2020-06-21 17:36:13 +08:00
b7833fb297 Merge pull request #4021 from flycash/feature/prometheus
Add prometheus support
2020-06-21 17:11:00 +08:00
16b81d09a7 Add prometheus support 2020-06-21 17:10:34 +08:00
0056b92d0b Merge pull request #4007 from flycash/fix3949
Store RouterPattern before filter execute
2020-06-21 17:05:04 +08:00
decc75e025 fix bug of non concurrent security & add double check 2020-06-21 16:25:32 +08:00
f2bae3e367 add UT for Scan function 2020-06-19 22:55:40 +08:00
6eeea141d8 Merge pull request #4018 from flycash/fix/xss
Using HTMLEscapeString in adminui.go to avoid XSS attack
2020-06-19 22:21:51 +08:00
6c0db4db3d Using HTMLEscapeString in adminui.go to avoid XSS attack 2020-06-19 21:49:17 +08:00
b9fbcbd906 Merge pull request #4014 from jianzhiyao/develop
over size file do not run openFile
2020-06-19 20:19:16 +08:00
40181c1042 Update redis.go
use `scan` instead of `keys`
2020-06-19 14:21:12 +08:00
3879fd9c34 修改测试用例 2020-06-18 17:25:48 +08:00
af238ee047 Merge remote-tracking branch 'origin/develop' into go_modules_route_compatibility
# Conflicts:
#	go.mod
#	go.sum
2020-06-18 16:41:03 +08:00
86935ada01 Merge pull request #3943 from zhlicen/master
#3942 fix encoded url(with slash) router match problem
2020-06-18 16:04:16 +08:00
8160059182 big size file lead to memory leak 2020-06-16 14:56:58 +08:00
dc70e9fc47 update go test 2020-06-15 18:16:40 +08:00
bac2b31afe Merge pull request #3975 from nicowaisman/patch-2
Change permission mask
2020-06-13 23:40:13 +08:00
a134cb8d17 update go test 2020-06-11 23:45:06 +08:00
4ad699b7b8 Merge pull request #3981 from zwei0526/develop
Update parser.go
2020-06-10 16:38:15 +08:00
14fc935cb6 Merge pull request #4005 from keminar/develop
fix graceful bug
2020-06-10 16:34:32 +08:00
d9f262e277 update go test 2020-06-10 12:31:38 +08:00
131748bb3d update go.mod&go.sum 2020-06-10 11:34:58 +08:00
2c3c66ccea Merge remote-tracking branch 'origin/develop' into develop 2020-06-10 11:16:17 +08:00
71cb1379b4 update support bit operation 2020-06-10 11:15:23 +08:00
b351f02525 Merge branch 'develop' of https://github.com/astaxie/beego into develop
 Conflicts:
	go.sum
2020-06-10 11:05:57 +08:00
8e29300f85 fix graceful bug 2020-06-09 12:20:08 +08:00
5f31bf45d4 Fix #3949 : store RouterPattern before filter execute so that filter can use the pattern 2020-06-07 23:16:26 +08:00
3e30f37172 Merge pull request #4006 from flycash/develop
fix CI and UT
2020-06-06 21:16:08 +08:00
ce4ce74c8d Fix validation test 2020-06-06 20:50:48 +08:00
ce0e7525ad Fix ES client 2020-06-06 20:14:01 +08:00
d0b7244d57 Fix ledis 2020-06-06 19:21:57 +08:00
5100a8c396 fix CI and UT 2020-06-06 18:16:36 +08:00
b8efb3ef45 Merge pull request #3984 from jianzhiyao/develop
fix bug:static can not real hit cache & memory leak
2020-06-06 13:10:58 +08:00
ae15b54f83 Merge pull request #3992 from maxshine/fix-3991
[Fix-Issue-3991] Fix Read with SQLite not supporting SELECT FOR UPDAT…
2020-06-06 13:10:08 +08:00
0dab959c95 Merge pull request #4004 from gokangaroo/develop
avoid `panic: send on closed channel` after closing logger.
2020-06-06 13:09:36 +08:00
ee615dd08f Merge pull request #3985 from leapsea/develop
修复多线程下数据库连接异常问题
2020-06-06 12:40:50 +08:00
b879a07b3a avoid panic: send on closed channel after closing logger. 2020-06-04 14:52:54 +08:00
c265f6e49c add comment 2020-06-02 20:02:58 +08:00
690e91e1b6 static file module:make cache file size and cache file numbers configurable 2020-06-02 18:22:47 +08:00
50f71a8a21 fix bug of getting int error 2020-06-02 18:10:17 +08:00
677d010d86 [Fix-Issue-3991] Add warn for SQLite Read is invoked isForUpdate=true 2020-06-01 23:12:12 +08:00
db2a1134ce Merge pull request #3993 from skanger/develop
fix httplib PostFile method
2020-06-01 22:05:01 +08:00
c2771397be delete vendor 2020-06-01 15:06:49 +08:00
70733d9810 fix label == `` #4001 2020-06-01 15:06:33 +08:00
11740cede6 Merge pull request #3996 from bharrat/3995-fix-middleware-not-working-with-graceful
Fixes #3995 Use handlers with middleware when starting Graceful server
2020-05-31 22:23:05 +08:00
4ffe26a1d2 for go modules, generate route by GO111MODULE=on 2020-05-22 11:35:45 +08:00
075db4773b Fixes #3995 Use handlers with middleware when starting Graceful server 2020-05-18 10:00:14 -07:00
2fd9dfca7b update support bit operation 2020-05-18 19:18:35 +08:00
eea20f6ceb fix httplib PostFile method 2020-05-16 11:00:15 +08:00
8055357576 [Fix-Issue-3991] Fix Read with SQLite not supporting SELECT FOR UPDATE syntax 2020-05-15 17:36:01 +08:00
9fda81b7f3 modify static cache total size about 100m 2020-05-09 18:24:14 +08:00
4b12e053b7 fix 2020-05-09 17:58:10 +08:00
0307c8b110 set static file cahce limit:file size & file count 2020-05-09 17:57:00 +08:00
867f83de34 修复数据库连接异常问题 2020-05-09 16:31:30 +08:00
af19822293 not modify go.mod 2020-05-09 14:06:51 +08:00
2449aad105 add cache-hit test example 2020-05-09 10:44:37 +08:00
d31975a752 complete test example 2020-05-08 17:35:02 +08:00
b28d5e2716 fix bug:static canot real hit cache
opt:reduce risk of memory leak with lru cache
2020-05-08 17:10:19 +08:00
ab33d683ea Update parser.go
修复genRouterCode方法解析  router 注释(// @router) 单双引号引起的bug
2020-04-26 19:26:10 +08:00
f99cbe0fa4 Change permission mask 2020-04-22 08:42:54 -07:00
0aa82d875a Update input.go 2020-03-05 14:46:17 +00:00
8f3d1c5f42 Merge pull request #3922 from BurtonQin/bug-1-2-3-inconsistent-field-protection
cache, context, session: add lock to fix inconsistent field protection
2020-02-22 15:09:25 +08:00
2410b364af Merge pull request #3923 from timchenxiaoyu/develop
fix exist typo
2020-02-22 11:25:13 +08:00
713503e43d fix exist typo 2020-02-14 16:47:47 +08:00
cfdd1cd5be cache, context, session: add lock to fix inconsistent field protection 2020-02-10 21:49:46 +08:00
de5650b723 version 1.12.1 2020-02-07 16:23:57 +08:00
e5e4a3bea7 Merge pull request #3868 from holtyuzhuyanbo/fix_session_destory
fix: session destory
2020-02-07 11:49:54 +08:00
90d0b43f34 Merge pull request #3888 from gavin2014/develop
[Fix] Fix create table with SQLite not supporting COMMENT syntax
2020-02-07 11:46:52 +08:00
1b7f5ba2c4 Merge pull request #3900 from aixiaoxiang/develop
httplib:fixes network request failed to create an invalid file and automatically created file directory
2020-02-07 11:10:56 +08:00
96f01079cb Merge pull request #3905 from ywk253100/200110_context
Send the request from context rather than the original one to handlers
2020-02-07 11:05:01 +08:00
9d4b5b313f Merge pull request #3911 from liuzhang/develop
验证调整,增加label, xx不能为空
2020-02-07 11:04:11 +08:00
b882009979 Merge pull request #3919 from wy65701436/develop-sha256
update hash algorithm for signing the cookie for xsrf token
2020-02-07 11:01:10 +08:00
a768bf8f00 update hash algorithm for signing the cookie for xsrf token
Due to the chosen-prefix collision in SHA-1(details at https://sha-mbles.github.io/), SHA-1 hash functions should to be deprecated and SHA-2/SHA-3 should be used instead.

Signed-off-by: wang yan <wangyan@vmware.com>
2020-02-06 17:31:24 +08:00
034599ca1d 验证调整,增加label, xx不能为空 2020-01-17 16:47:19 +08:00
5a02c556b2 Send the request from context rather than the original one to handlers
The filters may do some changes to the request, such as putting values in the request's context

Signed-off-by: Wenkai Yin <yinw@vmware.com>
2020-01-10 17:58:00 +08:00
axx
dc5c42e981 httplib:fixes network request failed to create an invalid file and automatically created file directory 2019-12-30 11:24:55 +08:00
92a4119258 Update cmd_utils.go
[Fix] Fix create table with SQLite not supporting COMMENT syntax
2019-12-11 16:50:08 +08:00
aa90c67a75 Merge pull request #3867 from ywk253100/191119_xsrf
Abort with the pre-defined status code when handling XSRF error
2019-11-29 18:43:02 +08:00
38a144c68f fix: session destory 2019-11-19 21:25:30 +08:00
793047097c Abort with the pre-defined status code when handling XSRF error
As the status codes(422 and 417) are set in the error map, abort with them directly to active the pre-defined error handlers

Signed-off-by: Wenkai Yin <yinw@vmware.com>
2019-11-19 18:55:54 +08:00
1923b8c767 Merge pull request #3841 from HKail/develop
添加16开头手机号验证
2019-10-23 22:22:52 +08:00
fb640f0075 更新16开头手机号的正则测试 2019-10-22 17:07:22 +08:00
241f10b429 添加16开头手机号验证,162电信,165移动,166/167联通。 2019-10-22 16:58:05 +08:00
b8d626bbea 添加16开头手机号验证,162电信,165移动,166/167联通。 2019-10-22 16:28:19 +08:00
2a6ceca861 Update README.md 2019-10-10 11:23:19 +08:00
10236b9f2d Merge pull request #3814 from cloudzhou/patch-2
leak opened file
2019-10-10 00:48:24 +08:00
b3ae5d4ac6 Update file.go
According to issue#4759 (https://github.com/golang/go/issues/4759) filepath.Walk function in golang cannot handle symbolic path, meanwhile symbolic path for log directory is pretty common used. In such scenario this deleteOldLog function will fail without any error log. Get the real location of the log directory before using walk function can fix this.
2019-10-09 15:53:22 +08:00
77fc8e4e38 According to issue#4759 (https://github.com/golang/go/issues/4759) filepath.Walk function in golang cannot handle symbolic path, meanwhile symbolic path for log directory is pretty common used. In such scenario this deleteOldLog function will fail without any error log. Get the real location of the log directory before using walk function can fix this. 2019-10-09 15:33:38 +08:00
5a5482c77f leak opened file
should defer file.Close()
2019-09-27 19:27:44 +08:00
11774c87a5 update version 1.13 2019-09-19 00:19:33 +08:00
6d47b4a2e0 GetMapData change to read lock 2019-09-09 17:44:10 +08:00
8395a26061 Merge pull request #3801 from DennisMao/develop
fix annotation on orm/utils #3777
2019-09-09 00:46:36 +08:00
4348356d0a fix annotation on orm/utils 2019-09-09 00:47:20 +08:00
b551949a2b Add PrintStack() while orm abnormally exit. 2019-07-31 14:08:58 +08:00
32cd76396d fix graceful bug 2019-07-27 18:54:13 +08:00
5620608418 Update README.md 2019-07-21 22:58:28 +08:00
32ee728078 Merge pull request #3586 from astaxie/develop
V1.12.0
2019-07-05 12:26:39 +08:00
de7ce2f9b0 v1.12.0 2019-07-05 11:58:41 +08:00
d6c2a9fd4b Merge pull request #3703 from jkylin/develop
email的Attach和AttachFile 的参数检查逻辑有误。len(args) < 1 && len(args) > 2 改为 l…
2019-07-05 11:35:47 +08:00
582a4fa34b Merge pull request #3699 from orgmatileg/develop
router.go: add comment func LogAccess
2019-07-05 11:34:59 +08:00
99647986de Merge pull request #3689 from GeorgeXc/addStmt
Add stmt
2019-07-05 11:34:40 +08:00
5bcde306ea Revert "update"
This reverts commit 2909ff3366.
2019-06-28 23:37:32 +08:00
2909ff3366 update 2019-06-28 23:23:01 +08:00
40078cba2c update 2019-06-28 23:13:18 +08:00
5d0c0a03d7 update 2019-06-28 22:56:32 +08:00
8cfd7f5c19 email的Attach和AttachFile 的参数检查逻辑有误。len(args) < 1 && len(args) > 2 改为 len(args) < 1 || len(args) > 2 2019-06-28 20:09:23 +08:00
62d96c2e93 router.go: add comment func LogAccess 2019-06-25 08:04:21 +07:00
e844058aed Merge pull request #3632 from Wusuluren/develop
fix concurrent map access problem on BeegoInput.data
2019-06-18 12:09:34 +08:00
1eab6bb32a Merge pull request #3669 from xfwduke/develop
fix bugs of ParseForm about time in RFC3339 format
2019-06-18 12:08:55 +08:00
c265d32c36 Merge pull request #3685 from Anderson-Lu/fix_orm_datarace
fix orm datarace
2019-06-18 12:05:54 +08:00
06692c3e27 update 2019-06-17 23:38:07 +08:00
394a73c75f fix orm datarace 2019-06-14 14:43:02 +08:00
cbcde8bd1f Merge branch 'develop' of https://github.com/Wusuluren/beego into develop 2019-06-09 22:10:22 +08:00
b17e49e6aa fix concurrent map access problem on BeegoInput.data 2019-06-09 22:09:38 +08:00
873f62edff update 2019-06-09 01:19:17 +08:00
cc0eacbe02 update 2019-06-08 23:53:42 +08:00
649c5c861d fix bugs of ParseForm about time in RFC3339 format 2019-05-31 15:52:19 +08:00
206a7ed1fc Merge pull request #3662 from npu21/develop
fix typos
2019-05-27 11:07:52 +02:00
3c046a4dbf fix two typos 2019-05-27 16:38:30 +08:00
f2be6af2ca Merge pull request #3658 from priyesh-lb/patch-1
Beego skipping some migrations
2019-05-18 09:38:09 +08:00
804b9769e0 Merge pull request #3642 from GeorgeXc/fixBatchUpdate
Fix BatchUpdate not update the auto_now field
2019-05-18 09:28:22 +08:00
585df01899 Merge pull request #3635 from edwardhey/develop
Incr和Decr应该改成排它锁,否则在并发的时候会出现非期望的结果值
2019-05-18 09:27:38 +08:00
1a529c061c Merge pull request #3633 from MarxGo/develop
fix:utils.GetGOPATHs() when go version equal or after go1.10
2019-05-18 09:27:08 +08:00
fcacfc08e3 Beego skipping some migrations
Beego skipping some migrations #3657
2019-05-17 16:19:26 +05:30
a0ca3d61d6 update 2019-05-08 23:11:57 +08:00
39bd40e512 Incr和Decr应该改成排它锁,否则在并发的时候会出现非期望的结果值 2019-05-01 13:10:21 +08:00
Guo
8748de95c7 fix:utils.GetGOPATHs() when go version equal or after go1.10 func does not return defaultGoPATH() 2019-04-30 06:43:25 +08:00
0939e8e493 fix concurrent map access problem on BeegoInput.data 2019-04-30 00:15:24 +08:00
6a33feee46 Merge pull request #1 from astaxie/develop
update
2019-04-29 23:19:27 +08:00
58b2ac702c Merge pull request #3623 from Martinho0330/develop
make routers configurable for beego multi-instance in the same repo
2019-04-29 18:19:22 +08:00
175714f69a Merge pull request #3627 from haleyly/develop
route request put amendment
2019-04-29 18:18:19 +08:00
d5b70118a3 Merge branch 'develop' of https://github.com/haleyLy/beego into dev 2019-04-28 08:51:34 +08:00
a9629f707e route request put amendment 2019-04-28 08:50:30 +08:00
6123c72752 Merge pull request #3621 from guanle/guanle-patch-1
Update templatefunc.go  for default value tag
2019-04-27 23:28:35 +08:00
56afa5c2bf Merge pull request #3625 from hsluoyz/develop
remove the 1000-row limit for ORM result set
2019-04-27 23:27:58 +08:00
0c576dac82 Merge pull request #3599 from Wusuluren/cache_file
fix bug on cache/file
2019-04-27 23:27:27 +08:00
8462372c03 Merge pull request #3598 from Wusuluren/develop
fix race problem on toolbox/task
2019-04-27 23:26:29 +08:00
20ff97d53d Merge pull request #3595 from JessonChan/log_revet
Log revet
2019-04-27 23:26:06 +08:00
8ce5b6cc52 Merge pull request #3593 from JessonChan/trace_method
Trace method
2019-04-27 23:25:44 +08:00
afb787d49d remove the 1000-row limit for ORM result set 2019-04-27 16:58:00 +08:00
0b165b78a1 make routers configurable for beego multi-instance in the same repo 2019-04-22 22:18:37 +08:00
fa97488bdc Update templatefunc.go 2019-04-21 10:27:35 +08:00
3086081ec0 v1.11.2 2019-04-06 13:50:14 +08:00
dfab44c24a fix bug on cache/file 2019-04-05 22:32:28 +08:00
1900246054 fix bug on cache/file 2019-04-05 22:17:56 +08:00
e980f92c63 fix race problem on toolbox/task 2019-04-05 20:28:24 +08:00
ce3800e3ef // Deprecated: use github.com/astaxie/beego/logs instead. 2019-04-03 14:13:38 +08:00
e3d668f450 revet to log.go
https://github.com/astaxie/beego/issues/3591
https://github.com/astaxie/beego/issues/3588
2019-04-03 14:08:42 +08:00
75b4bc5896 it's no need to override Trace method. 2019-04-03 10:19:09 +08:00
c0ecf32d17 update travis 2019-04-02 21:53:01 +08:00
3155f07ccd no need to override Trace method. 2019-03-27 13:43:27 +08:00
02bead5097 handle trace request must NOT CACHE
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cache-Control
2019-03-27 13:40:34 +08:00
e8b29c9fd1 handle trace request 2019-03-27 13:34:46 +08:00
610f27d684 Merge pull request #3530 from GeorgeXc/develop
[orm] add ignore auto_now_add field when update
2019-03-27 00:14:07 +08:00
59466f6678 Merge pull request #3554 from grahamjamesaddis/travis-ci-build
Allow forked beego project to pass travis ci builds
2019-03-26 19:24:06 +08:00
3ddd8f860e Merge pull request #3561 from JessonChan/develop
refactor color logger
2019-03-26 19:23:14 +08:00
8535ec0819 Merge pull request #3567 from bsdelf/feature/ensure-custom-error-handler
Ensure custom error handler is called
2019-03-26 19:22:54 +08:00
f294121ab7 Merge pull request #3583 from maxshine/develop
[Fix] Fix the issue that genRouterCode results in @Import annotations getting overwritten
2019-03-26 19:13:44 +08:00
0b8ebaf387 Update db.go 2019-03-26 01:00:04 +08:00
3b00cfccec [Fix] Fix the issue that genRouterCode incorrect logic results in @Import annotations getting overwritten 2019-03-24 14:41:28 +08:00
005391be81 update 2019-03-23 00:33:26 +08:00
bc8fffe347 Merge pull request #3571 from dxas90/patch-1
Fixes #3570
2019-03-14 19:16:15 +01:00
914bbfd710 Update apiauth.go fixed infinite recursive call 2019-03-14 09:14:12 -04:00
be31bd2bbd Ensure custom error handler is called 2019-03-13 16:24:04 +08:00
95ff817019 undefined: beego.BeeLogger fixed 2019-03-13 09:41:13 +08:00
ea91e7638c move log function to log package 2019-03-12 17:01:23 +08:00
4564e9810c logger_test imported and not used: "bytes" 2019-03-12 16:36:00 +08:00
44a1a8f6be println is builtin function 2019-03-12 15:51:43 +08:00
9cecb22170 NewAnsiColorWriter remove 2019-03-12 15:13:54 +08:00
7693502aaa logAdapter is more readable 2019-03-12 13:20:13 +08:00
c0fae547e9 remove ansicolor code,import ansicolor package 2019-03-12 12:14:09 +08:00
0ba77a0d87 colorful is the switch to level label 2019-03-12 12:12:59 +08:00
661dcbb6ca router logger modify 2019-03-12 12:11:25 +08:00
578440a18d add ansicolor to beego 2019-03-12 12:09:41 +08:00
93485df3d2 color should be false by default otherwise the http logger's color would be wrong 2019-03-08 14:42:06 +08:00
121fab61f1 ResetColor function 2019-03-08 12:18:45 +08:00
915eec7943 Merge branch 'develop' of github.com:astaxie/beego into develop 2019-03-08 12:16:00 +08:00
8432a1c758 better comment for color map 2019-03-08 12:10:57 +08:00
4a5e108527 logger color function refactor,easy to read and run more quickly 2019-03-08 11:50:30 +08:00
6dd5171fdf logger color function refactor,easy to read and run more quickly 2019-03-08 11:08:39 +08:00
c2b6cb5c3a Merge pull request #3560 from JessonChan/develop
TestToJson bug fixed
2019-03-08 00:18:39 +08:00
1f93040af6 Merge remote-tracking branch 'upstream/develop' into develop 2019-03-07 18:07:37 +08:00
52f8ccd06c TestToJson bug fixed 2019-03-07 17:15:30 +08:00
3b86feab8a Merge pull request #3555 from hellomrleeus/develop
spelling mistake of word "Header"
2019-03-06 09:58:54 +08:00
aba51d99a1 spelling mistake of word "Header" 2019-03-04 11:05:29 +08:00
8454e8417e Allow forked beego project to pass travis ci builds 2019-03-01 14:00:20 +00:00
422e8285b5 Merge pull request #3494 from nuczzz/develop
simplify beego grace with http.Shutdown
2019-02-26 16:31:40 +08:00
bb6ca6b100 Merge pull request #3522 from saromanov/check-input-data
SessionRead: check of the length for input sid variable
2019-02-25 23:17:57 +08:00
1483c1f545 Merge pull request #3524 from Quasilyte/quasilyte/bytesreader
config/yaml: s/bytes.NewBuffer/bytes.NewReader/
2019-02-25 23:16:39 +08:00
3d6a68de77 Merge pull request #3535 from gadelkareem/develop
Make LogAccess() function public
2019-02-25 23:11:14 +08:00
387d387080 Merge pull request #3547 from snedzad/patch-1
Register .gohtml extension
2019-02-25 11:43:37 +08:00
94ed35e781 Register .gohtml extension
Goland as of 2018.3 seems to support only '.tpl.gohtml" and ".gohtml" templates. The regular ".tpl" templates will be rendered as plain text files which is not acceptable.
2019-02-23 22:49:32 +01:00
8995b291a9 Make LogAccess public 2019-02-14 16:30:25 +01:00
1942438b22 Merge pull request #3 from astaxie/develop
develop
2019-02-14 16:23:35 +01:00
40d653e659 Merge pull request #3533 from tvanriper/patch-1
APIBaiscAuth is misspelling of APIBasicAuth
2019-02-13 02:10:25 +08:00
ddcd28e67f APIBaiscAuth is misspelling of APIBasicAuth
Corrected APIBaiscAuth to APIBasicAuth.  Maintained old name (forwarding to new one) for those still using the previous API function name.
2019-02-12 13:00:11 -05:00
65f587d5e9 fix ineffectual assignment 2019-02-12 19:05:22 +08:00
2fefd8cbbf update len 2019-02-12 18:53:34 +08:00
ba17bdd366 add ignore auto_now_add field when update 2019-02-12 18:05:29 +08:00
c998e52cc0 config/yaml: s/bytes.NewBuffer/bytes.NewReader/
When io.Reader is required out of []byte,
it's better to use bytes.NewReader than bytes.NewBuffer.

Signed-off-by: Iskander Sharipov <quasilyte@gmail.com>
2019-02-10 20:37:43 +03:00
3224369ac9 Merge pull request #3523 from Quasilyte/quasilyte/boolExprSimplify
Simplify boolean expressions
2019-02-09 16:16:31 +01:00
67666dbe0f all: simplify boolean expressions
- !(a == b) => a != b
- !(a != b) => a == b

Signed-off-by: Iskander Sharipov <quasilyte@gmail.com>
2019-02-09 17:18:59 +03:00
d7430eb921 SessionRead: check of the length for input sid variable 2019-02-04 11:03:27 +05:00
26a6b426f1 Merge pull request #3487 from duyazhe/patch-1
Update orm_log.go
2019-02-04 11:26:42 +08:00
6f35ce67f7 Merge pull request #3493 from bharat-p/3492-add-db-stats-to-ormer
Add DBStats method wrapper to provide sql.DBStats when using ormer
2019-02-04 11:24:13 +08:00
3406d58797 Merge pull request #3503 from wtospit/develop
fix: when parse post form it didnt parse fields correctly
2019-02-04 11:23:23 +08:00
7925458fc0 Merge pull request #3502 from Quasilyte/patch-1
cache: remove excessive type assertions
2019-02-02 16:43:04 +08:00
b6854aaf9f Merge pull request #3506 from DennisMao/hotfixFileCachePanic
fix panic cause by the map
2019-02-02 16:38:11 +08:00
656f595226 Merge pull request #3508 from Quasilyte/patch-2
replace unchecked Compile calls with MustCompile
2019-02-02 16:36:15 +08:00
280aaf9d3b Merge pull request #3519 from zav8/add_support_for_pointer_fields
add support for pointer fields of structs to method QueryRows()
2019-02-02 16:35:41 +08:00
7abdb05f91 little fix 2019-02-01 15:39:40 +08:00
af4464ce58 add support for pointer fields of structs to method QueryRows() 2019-02-01 15:27:10 +08:00
6ca0978777 replace unchecked Compile calls with MustCompile
For constant patterns and especially when errors are ignored,
`regexp.MustCompile` is a better choice than `regexp.Compile`.

Signed-off-by: Iskander Sharipov <quasilyte@gmail.com>
2019-01-26 14:13:53 +03:00
8506194d2c fix panic cause by the map 2019-01-25 19:08:39 +08:00
3bd7614ade refactoring code after discussion 2019-01-25 11:00:24 +07:00
bd1b421491 fix: adding test for issue due to testing is not reflect changed 2019-01-25 09:04:01 +07:00
920207f72c add testing for ParseForm when form post has a slice in body 2019-01-25 00:38:14 +07:00
12fdc04f1b fix: when parse post form it didnt parse fields which have same name but the first index is empty but another is not 2019-01-25 00:15:40 +07:00
d0c744ae6a Merge pull request #3499 from JessonChan/develop
fix download filename(chinese) bug
2019-01-24 17:27:29 +08:00
dc07fa7085 cache: remove excessive type assertions
Assign type switch variable to get properly-typed value
inside case clauses.

Signed-off-by: Iskander Sharipov <quasilyte@gmail.com>
2019-01-24 08:52:30 +03:00
1c893996c0 improve the download func code 2019-01-23 12:36:14 +08:00
a9ffc2a078 https://github.com/astaxie/beego/issues/3446
Use UTF-8 as the encoding of the "filename*" parameter, when
                           present, because at least one existing implementation only
                           implements that encoding.
2019-01-23 12:30:57 +08:00
712bbfe575 Merge pull request #3498 from JessonChan/develop
change gosimple to staticcheck
2019-01-23 11:31:37 +08:00
0145fe3486 remove SA1024 staticchek 2019-01-22 20:52:06 +08:00
2a579eb27c staticcheck checks -ST1003 remove 2019-01-22 20:41:07 +08:00
5b42afa324 modiyf staticcheck checks 2019-01-22 20:30:05 +08:00
97713849a1 delete stackcheck config file and ignore some staticcheck checks 2019-01-22 20:21:00 +08:00
abc9c38224 ignore some staticcheck checks 2019-01-22 20:04:30 +08:00
f237ff049a redis_sentinel test ignore 2019-01-22 19:45:32 +08:00
00264650b5 modify travis and redis_sentinel test 2019-01-22 19:29:53 +08:00
2956d33bab no need gosimple 2019-01-22 19:12:25 +08:00
c3eca637fb no need gosimple 2019-01-22 19:10:23 +08:00
0d54bbff02 make staticcheck happy 2019-01-22 19:09:57 +08:00
e65a9cbc00 Gosimple has been deprecated. Please use staticcheck instead. 2019-01-22 18:01:14 +08:00
3ed82c0882 Gosimple has been deprecated. Please use staticcheck instead. 2019-01-22 17:43:55 +08:00
475feb7e24 camel name style 2019-01-22 16:25:17 +08:00
30b80cba92 errors is better style 2019-01-22 16:23:10 +08:00
fe519bd2a0 update tls KeepAlive setting 2019-01-20 11:17:10 +08:00
f508f8d959 Nil check 2019-01-18 16:51:40 -08:00
e295c3c7c3 add shutdown log 2019-01-18 19:50:22 +08:00
313be996cd call cancel after shutdown 2019-01-18 19:33:45 +08:00
2ae480556d Add DBStats method wrapper to provide sql.DBStats when using ormer 2019-01-17 09:56:42 -08:00
7173fd7490 modify http graceful 2019-01-17 20:17:57 +08:00
d792536c23 Update orm_log.go
orm log支持用户自定义函数处理
2019-01-14 15:14:11 +08:00
80aabdd372 Merge pull request #3472 from sangheee/develop
fix: negative WaitGroup counter has not been resolved yet.
2019-01-08 23:54:40 +08:00
6892369cc6 Merge pull request #3464 from zhl11b/develop
手机号起始三位补全
2019-01-08 23:54:00 +08:00
5b80a56c36 Merge pull request #3468 from DennisMao/hotfix/UpdateDependencyGoes
update dependency
2019-01-08 23:52:39 +08:00
bf15535a5b fix panic: sync: negative WaitGroup counter 2019-01-03 22:44:32 +09:00
edb1c52dee fix function changes 2019-01-02 17:01:46 +08:00
6e16b8cdcf fix ci losing dependency 2019-01-02 16:46:27 +08:00
24215fb3eb update dependency 2019-01-02 15:37:41 +08:00
d02699a189 add new test case for china mobile phone 2018-12-30 20:51:21 +08:00
2034d1b101 联通171,175 电信173 2018-12-29 17:41:59 +08:00
5fe19d639f Merge pull request #3456 from japettyjohn/master
Fix bug in memcache sessions
2018-12-28 22:35:11 +08:00
1dea80d4ea Fixed error handling in memcache sessions 2018-12-27 16:20:26 -08:00
28f0008075 Merge pull request #3434 from zav8/add_sql_null_support
Add support for field of type sql.NullXxx in rawSet.setFieldValue()
2018-12-19 22:26:23 +08:00
ffe1b00baf Merge branch 'develop' of https://github.com/astaxie/beego into add_sql_null_support 2018-12-18 10:41:17 +08:00
d2c289193a add test case for QueryRow and QueryRows 2018-12-18 10:37:41 +08:00
f867583256 Merge pull request #3433 from DennisMao/FixOrmDescriptionTag
Fix Issue #3337
2018-12-18 09:20:36 +08:00
98dfb92e17 Merge pull request #3443 from zhiquan911/develop
add GetProvider
2018-12-18 09:10:17 +08:00
c8f22be675 Add redis sentinel session support (#3427)
Add Redis Sentinel session support
2018-12-17 14:47:47 +01:00
f03a7d1128 add GetProvider 2018-12-13 15:37:19 +08:00
6da4a66c20 merge switch cases 2018-12-06 16:09:39 +08:00
5e4241fc87 add support for field of type sql.NullXxx in rawSet.setFieldValue() 2018-12-06 16:07:07 +08:00
bf468c8d0c fix format 2018-12-06 10:57:32 +08:00
0d77a3f8d2 FixOrmDescrptionTag 2018-12-06 10:49:50 +08:00
1b6edafc96 Merge pull request #3412 from astaxie/develop
v1.11.1
2018-11-30 21:54:26 +08:00
8152ade1b6 Merge pull request #3419 from xpzouying/close_fs_when_is_not_nil
Close fs when is not nil
2018-11-30 16:57:49 +08:00
6350f8b904 Merge pull request #3420 from xpzouying/format_list_travis_yml
format list in .travis.yml
2018-11-30 16:57:25 +08:00
0c5398a19c update travis 2018-11-30 16:42:44 +08:00
4b656268d3 travis 2018-11-28 16:17:53 +08:00
10729a1fc5 update vendor & module 2018-11-28 16:05:15 +08:00
cdb3ef808f format list in .travis.yml 2018-11-28 08:59:27 +08:00
a5a2471f2c close fs only when fs open without error
panic when close nil filesystem
2018-11-28 08:55:20 +08:00
6282747f6d update vendor 2018-11-27 14:11:14 +08:00
d5fd5cad38 Merge pull request #3417 from xpzouying/update_code_format
better format
2018-11-27 14:01:59 +08:00
fab7c6b6d0 better format
- add comments for public function
- format import order in admin.go
- better format for NewControllerRegister in router.go
2018-11-26 23:19:05 +08:00
42ade6aa49 v1.11.1 2018-11-22 13:10:52 +08:00
55d9b69cd9 update mod 2018-11-22 13:08:39 +08:00
2a8d6f943f Merge pull request #3408 from nlimpid/develop
add different column name parse strategy
2018-11-21 17:18:39 +08:00
6b0155c4fb add different column name parse strategy 2018-11-20 22:47:56 +08:00
e22a5143bc Merge pull request #3403 from nlimpid/develop
add context for db operation
2018-11-20 15:44:25 +08:00
a17eb54515 Merge pull request #3405 from coldnight/feature-add-elapsed-in-response
Add .Elapsed in context.ResponseWriter for monitor purpose
2018-11-20 15:39:13 +08:00
d5cf1050db check qs is nil before get forContext 2018-11-19 23:42:56 +08:00
b021686521 Add .Elapsed in context.ResponseWriter for monitor purpose
With this commit we can record per requests's elapsed time,
so we can easy to monitor that by use a filter.
2018-11-19 16:38:14 +08:00
b0e2bbce2a Merge pull request #3391 from astaxie/develop
V1.11.0
2018-11-19 14:40:43 +08:00
7a50ea7e36 Merge pull request #3395 from astaxie/AddTestForSnakeString
#3192 AddTestSnakeString
2018-11-18 21:59:48 +08:00
3070cfc60b Merge pull request #3396 from astaxie/FixAnnotationOnSnakeString
Fix #3192
2018-11-18 21:59:35 +08:00
e56d1b718f add context for db operation 2018-11-18 21:54:25 +08:00
c4c3067a31 Update utils.go 2018-11-15 15:16:41 +08:00
81346fe641 Update utils_test.go 2018-11-15 14:50:38 +08:00
1a66ad56c6 Merge pull request #3317 from HSoshiant/master
Lock
2018-11-14 19:24:23 +08:00
31f2adb79d Update session.go 2018-11-14 19:24:10 +08:00
f514ae309b Update session.go 2018-11-14 19:23:10 +08:00
277d3d98e3 v1.11.0 2018-11-14 17:01:12 +08:00
2c46877b36 Merge pull request #3390 from astaxie/FixDataRaceOnCache
Fix  #3354
2018-11-14 15:58:20 +08:00
cfe54a02c5 Merge pull request #3388 from s00500/develop
Closes #2515 Autodetect timezone in NewOrmWithDB()
2018-11-13 16:48:18 +08:00
55f390d08a Merge pull request #3387 from wuyumin/master
dynamically add task #2708
2018-11-13 14:51:41 +08:00
cf31222643 Merge pull request #3386 from DennisMao/AddTransportSetting
add transport setting
2018-11-13 14:50:28 +08:00
9e036bcab5 Update memory.go 2018-11-13 14:43:23 +08:00
d02170e3cb Closes #2515 Autodetect timezone in NewOrmWithDB() 2018-11-12 10:18:05 +01:00
2d6f1af1a5 dynamically add task 2018-11-12 17:17:06 +08:00
430457609f Update httplib_test.go 2018-11-12 13:04:17 +08:00
0333e26b3e Merge pull request #3382 from lxShaDoWxl/add_custom_fs_template
Add custom fs template
2018-11-10 22:44:28 +08:00
d0d28566b9 chore(GoMod): add dependency go-bindata-assetfs in vendor dir 2018-11-10 13:41:47 +06:00
872b787e6c refactor(FileSystem): add comments function 2018-11-10 12:34:53 +06:00
01a99edf80 chore(GoMod): add dependency go-bindata-assetfs 2018-11-10 12:26:19 +06:00
6050d37d2a Merge remote-tracking branch 'me/develop' into add_custom_fs_template 2018-11-10 11:39:28 +06:00
876dce8e54 fix the routerInfo is nil 2018-11-09 18:03:26 +08:00
24885c28f2 fix the comments update 2018-11-09 17:54:20 +08:00
5ea04bdfd3 update mod 2018-11-09 12:37:28 +08:00
9fdc1eaf3a Merge pull request #3352 from SongLiangChen/develop
add sessionid prefix
2018-11-08 23:29:05 +08:00
6b5a70d246 Merge pull request #3378 from nukc/develop
orm: support filter raw sql
2018-11-08 23:28:30 +08:00
8391d26220 Merge pull request #3383 from LockGit/develop
security question, fix arbitrary file read
2018-11-08 23:21:18 +08:00
f193e313a3 refactor(FileSystem): using single-line if 2018-11-07 20:21:34 +06:00
9ac4928113 refactor(Template): a detailed description of the error 2018-11-07 20:20:10 +06:00
9865779f14 security question, fix arbitrary file read 2018-11-07 11:31:27 +08:00
aa6d0f9f0b fix(Template): correct check error 2018-11-06 21:40:43 +06:00
68b0bd98fd fix(Template): error handling when reading files 2018-11-06 20:41:05 +06:00
3447798494 fix(Template): dependencies in travis 2018-11-06 20:18:48 +06:00
ca1b96f986 feat(Template): use interface http.FileSystem 2018-11-06 20:06:21 +06:00
771fe35431 feat(Template): testing fs bindata 2018-11-05 22:58:59 +06:00
2f00ad1602 fix(Template): close open file 2018-11-05 22:51:20 +06:00
f740b71ded fix(Template): remove duplicate check open/exists 2018-11-05 21:08:03 +06:00
7aae58a543 feat(Template): create interface FileSystem for to create custom fs 2018-11-05 21:05:19 +06:00
c8da875f83 add sessionId prefix 2018-11-05 09:51:27 +08:00
501d8a97f6 add sessionId prefix 2018-11-05 09:50:19 +08:00
736e66fcda orm: support filter raw sql 2018-11-05 03:47:21 +08:00
d3ad810f16 add sessionId prefix 2018-10-29 13:35:31 +08:00
abc8b78065 add sessionId prefix 2018-10-29 12:18:06 +08:00
f64e6b72e9 Merge pull request #3362 from SmartBrave/develop
modify qbs to qps
2018-10-28 20:01:23 +08:00
4e83b4400a Merge pull request #3371 from HaraldNordgren/go_versions
Bump Go versions and use 1.n.x to get latest minor versions
2018-10-28 19:49:27 +08:00
f6f61513a1 Bump Go versions and use 1.n.x to get latest minor versions 2018-10-28 00:58:36 +02:00
8217817a0b modify qbs to qps 2018-10-24 10:38:59 +08:00
833f54d818 Merge pull request #3319 from Colstuwjx/annotated-filter
Annotated filter
2018-10-23 13:45:18 +08:00
706c086bc5 Merge pull request #3345 from dingyuanhong/develop
fix / can use dynamic directory
2018-10-23 13:43:45 +08:00
187add9b84 add sessionid prefix 2018-10-10 11:02:45 +08:00
5b8e468a13 Merge pull request #3344 from akhedrane/patch-1
duo to #3278 numRow should be 0
2018-10-05 21:16:18 +08:00
dff9c8f5fa fix / can use dynamic directory 2018-10-01 15:16:35 +08:00
21a8623002 duo to #3278 numRow should be 0 2018-09-30 10:45:18 +01:00
ea9c5822e6 Merge pull request #3292 from SongLiangChen/master
Read over 4096 length values
2018-09-30 16:03:45 +08:00
ad0d166d46 Merge pull request #3295 from GNURub/feature/outputWithformat
feature/outputwithformat
2018-09-30 16:01:07 +08:00
2c2ace9a60 Merge pull request #3313 from oiooj/pr-module
support go modules
2018-09-30 15:55:57 +08:00
8134a89e81 Merge pull request #3333 from akhedrane/patch-1
Return error when wrong filtering field
2018-09-30 15:45:23 +08:00
e342a0099f Merge pull request #3340 from GNURub/feature/update-travis
Add go 1.11 version
2018-09-30 15:44:46 +08:00
c4ed5030da Merge pull request #3339 from GNURub/hotfix/redis-uri
Support redis URI format
2018-09-30 15:43:41 +08:00
7b9c24567d Merge pull request #3335 from GNURub/hotfix/ranking-response-times
Added link to time ranking
2018-09-30 15:42:05 +08:00
6906c5ce30 Updated travis go version 2018-09-27 18:27:38 +02:00
e4605f232b Support redis URI 2018-09-26 18:05:09 +02:00
6092e737a1 Added link to ranking 2018-09-24 18:33:56 +02:00
0e4d954fa7 Return error when wrong filtering field
When end user put wrong filtering field ORM should return error instead of Panic()
so developers can handle this error.
2018-09-23 12:18:15 +02:00
1cbba4d56f Add annotated filter, support @Import, @Filter.
Signed-off-by: Colstuwjx <Colstuwjx@gmail.com>
2018-09-07 15:59:57 +08:00
kun
cf5d1f3f3c support go modules 2018-09-05 14:05:16 +08:00
1097ac3682 GetProvider 2018-08-28 15:12:28 -04:00
755cc98ef7 Fix content type 2018-08-21 12:32:16 +02:00
5c407ff2e3 Add map shortcut and ServeFormatted method in output 2018-08-20 22:55:50 +02:00
8f455ef199 Read over 4096 length values 2018-08-17 11:40:00 +08:00
7e0649d661 Merge pull request #3289 from nezorflame/patch-1
Remove panic from Redirect()
2018-08-16 09:22:22 +08:00
1a3dcb4f84 Remove panic from Redirect()
This `panic(ErrAbort)` is unnecessary in `Redirect` function and causes problems in the production code.
2018-08-12 05:11:03 +03:00
b606f1f73f Merge pull request #3283 from JessonChan/develop
typo fixed
2018-08-09 17:05:25 +08:00
8241f219fd Merge pull request #3278 from hurisheng/revert-3247-develop
Revert "send ErrNoRows if the query returns zero rows ... in method orm_query…"
2018-08-09 17:05:01 +08:00
dea45a3d6c fix TestAll() 2018-08-07 16:36:27 +08:00
34a812d45f typo fixed
#3260
2018-08-07 12:08:15 +08:00
842336834f Merge pull request #3275 from WiFeng/master
fix bug of tasks that only some but not all are executed
2018-08-07 10:07:29 +08:00
58fe012446 Merge pull request #3274 from gombaniro/improvement/make-TestSet-on-map-self-contained
breaks dependency on TestNewBeeMap Testcase
2018-08-07 10:02:29 +08:00
bf0d40bca6 Merge pull request #3280 from GNURub/feature/pusher
Add access to pusher
2018-08-07 09:58:56 +08:00
48e6658eca Add access to pusher 2018-08-03 12:33:46 +02:00
1bd3fb7a33 Revert "send ErrNoRows if the query returns zero rows ... in method orm_query…" 2018-08-03 13:35:48 +08:00
d86410a631 fix bug of tasks that only some but not all are executed 2018-08-01 11:20:22 +08:00
6b62502b99 breaks rely on TestNewBeeMap 2018-08-01 10:24:39 +08:00
053a075344 Merge pull request #3271 from astaxie/develop
add vendor gopkg.in/yaml.v2
2018-07-31 21:18:48 +08:00
9dd7d19ce7 add vendor gopkg.in/yaml.v2 2018-07-31 21:18:07 +08:00
efe0f67388 Merge pull request #3267 from astaxie/develop
beego 1.10.1
2018-07-31 20:52:47 +08:00
de66d2bdfd beego 1.10.1 2018-07-31 20:09:08 +08:00
0e4fe4d177 Merge pull request #3270 from astaxie/revert-3269-master
Revert "hible"
2018-07-31 20:07:18 +08:00
6d84db1e93 Revert "hible" 2018-07-31 20:07:03 +08:00
2486f3826a Merge pull request #3269 from 514366607/master
hible
2018-07-31 20:06:55 +08:00
d7b8aa8b52 only add golang.org vendor 2018-07-31 19:25:43 +08:00
c7c0b01ec5 hible
cache add function
// IncrBy increase counter by num.
IncrBy(key string, num int)
// DecrBy decrease counter by num.
DecrBy(key string, num int)
2018-07-31 17:19:09 +08:00
6d69047fff update go vet 2018-07-30 15:13:04 +08:00
787ab12605 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2018-07-30 15:01:58 +08:00
f4112accef update go vet 2018-07-30 15:01:49 +08:00
42c394e28b Merge pull request #3263 from guomao545/master
Support return middle level value
2018-07-30 12:27:05 +08:00
5051d902fb Merge pull request #2986 from oxgo/hourlylog
add hourly log rotate
2018-07-30 12:26:37 +08:00
48acfa08be add vendor 2018-07-30 12:05:51 +08:00
39fc30b8b2 Support return middle level value
fix multilevel yaml config can't correct return middle level value bug
2018-07-27 15:33:24 +08:00
two
046cb248e0 edit test case 2018-07-26 15:08:14 +08:00
two
31c746d9d7 fix all confict 2018-07-26 14:34:25 +08:00
two
38a2f32252 fix one confict 2018-07-26 14:29:26 +08:00
d55f54a8ab Merge pull request #3149 from liaoishere/feature/support-begintx
Support DB.BeginTx in go 1.8
2018-07-23 20:25:17 +08:00
feb0e67fd7 upgrade go version from 1.9.2 to 1.9.7 in test env.
upgrade to avoid bug: https://github.com/golang/go/issues/22976

Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-23 15:58:12 +08:00
a09bafbf2a Merge pull request #3233 from astaxie/develop
beego 1.10.0
2018-07-21 15:55:28 +08:00
03de7456ca Merge pull request #3250 from 0x0400/develop
acquire lock when access config data
2018-07-21 15:25:23 +08:00
78f2fd8d14 acquire lock when access config data 2018-07-21 14:56:09 +08:00
a048ed51a7 ready to release 1.10.0 2018-07-21 09:29:00 +08:00
164a9231e8 Merge pull request #3249 from GNURub/feature/autocert
Feature/autocert
2018-07-21 09:20:07 +08:00
aaa7e33778 Autocert ok 2018-07-20 19:54:25 +02:00
f7008e2877 Removed patch 2018-07-20 19:02:09 +02:00
cf6e825547 Domains 2018-07-20 18:59:45 +02:00
38f9a3c49e AutoCert 2018-07-20 18:53:57 +02:00
f18283a517 Merge pull request #3181 from GNURub/feature/YAML
Feature/yaml
2018-07-20 23:41:15 +08:00
61aec396e0 Update .travis.yml 2018-07-20 23:40:11 +08:00
5ba9e63086 Merge branch 'develop' into feature/YAML 2018-07-20 23:24:51 +08:00
5acc56648d Merge branch 'develop' into feature/support-begintx 2018-07-20 23:16:12 +08:00
bc773039ca Merge pull request #2997 from DennisMao/master
fix the model can not be registered correctly on Ubuntu 32bit
2018-07-20 23:14:41 +08:00
868fc2a29f fix go1.10.3 orm test failed 2018-07-20 22:45:44 +08:00
81f69f12ab Merge branch 'develop' of https://github.com/astaxie/beego into develop 2018-07-20 22:30:25 +08:00
0711c3289f fix the orm test 2018-07-20 19:58:56 +08:00
b8868d6d2d remove unnecessary conversion
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 17:07:17 +08:00
30bbc81a2e fix test case that calls All()
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 16:51:36 +08:00
1a3f1d66c1 rename orm_go18.go to orm.go
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 16:36:06 +08:00
6bdd152d91 upgrade postgres in travis
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 16:36:06 +08:00
443c77b303 support DB.BeginTx of golang 1.8
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 16:36:06 +08:00
0dff771707 fix unquoted identifier that may be misleading in postgres
Signed-off-by: Penghui Liao <liaoishere@gmail.com>
2018-07-20 16:36:06 +08:00
c9b6e4f825 Merge pull request #2981 from TankTheFrank/fix_template_render_with_automatic_parameter_routing
fixes template rendering with automatic mapped parameters (see #2979)
2018-07-20 15:39:10 +08:00
abd02c7de4 Merge pull request #2985 from terryding77/fix_orm_Field_SetRaw_function_error_judge_problem
fix orm fields SetRaw function error judge problem
2018-07-20 15:36:40 +08:00
eb4e0e4030 Merge pull request #3022 from chenpeiyuan/develop
do html escape before display path, avoid xss
2018-07-20 15:33:12 +08:00
96dffcd27f Merge pull request #3105 from ckahi/hotfix_log_dir
auto create log dir
2018-07-20 15:32:42 +08:00
0d0d87f600 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2018-07-20 15:25:04 +08:00
2c779a4287 Merge pull request #3141 from gadelkareem/patch-2
Improve access log
2018-07-20 15:20:15 +08:00
f25893832f Merge pull request #3142 from amitash1109/fix_response_http_code
Fix response http code
2018-07-20 15:18:54 +08:00
af73a2d515 Merge branch 'develop' into fix_response_http_code 2018-07-20 15:18:30 +08:00
67a6b8723c Merge pull request #3146 from Wang-Kai/master
Add code style for logs README
2018-07-20 15:17:31 +08:00
fdccd85330 Merge pull request #3152 from joshtechnologygroup/staticfile_unexpected_eof_bug_gix
[#2973] Fix Unexpected EOF bug in staticfile
2018-07-20 15:09:07 +08:00
ca394fc8ab Merge pull request #3182 from GNURub/feature/autobind
Add method to set the data depending on the accepted
2018-07-20 15:05:28 +08:00
9c9ba0129f Merge pull request #3226 from jianjianzhu/master
Fix the wrong status code in prod
2018-07-20 14:53:08 +08:00
b61c91d93d remove unnecessary conversion 2018-07-20 14:47:11 +08:00
f15732798f Merge pull request #3239 from wilhelmguo/develop
add session redis IdleTimeout config
2018-07-20 14:44:07 +08:00
efbe655d6a Merge pull request #3245 from 0x0400/patch-1
fix typo
2018-07-20 14:43:38 +08:00
27ced1d9c3 Merge pull request #3247 from mohan2808/develop
send ErrNoRows if the query returns zero rows ... in method orm_query…
2018-07-20 14:34:23 +08:00
8f6bce3b87 fix test case 2018-07-20 14:26:43 +08:00
be75f93d43 add miss dep 2018-07-20 12:14:27 +08:00
541fb181fe Merge branch 'master' into develop 2018-07-20 12:00:53 +08:00
293b54192f send ErrNoRows if the query returns zero rows ... in method orm_queryset.All() 2018-07-19 18:51:16 +05:30
0e0718d110 fix typo
hasReuired --> hasRequired
2018-07-17 23:32:11 +08:00
6fec0a7831 add session redis IdleTimeout config 2018-07-12 10:48:50 +08:00
654ebebe3c Merge pull request #3217 from jinxjinxagain/develop
fix: When multiply comment routers on one func
2018-07-08 16:13:21 +08:00
08c3ca642e Merge pull request #3230 from Colstuwjx/fix/correct-httplib-maxidleconnection-default-value
Fix: correct MaxIdleConnsPerHost value to net/http default 100.
2018-07-08 16:11:35 +08:00
b3c46a87ac Fix: correct MaxIdleConnsPerHost value to net/http default 100. 2018-07-05 19:15:42 +08:00
464d080518 fix httpcode in prod 2018-07-02 11:21:06 +08:00
227c04c9e6 fix: When multiply comment routers on one func, only generates the last one controller 2018-06-28 15:54:17 +08:00
e5d68aceed Merge pull request #3185 from kaka89/master
Fix defaut value bug, and add config for maxfiles
2018-06-23 22:54:35 +08:00
67d9241abc Merge pull request #3171 from whomm/master
debug stringsToJSON
2018-06-23 22:50:11 +08:00
110dbcb31f Merge pull request #3208 from hurisheng/qs_forupdate
add 'FOR UPDATE' support for querySet
2018-06-23 22:49:01 +08:00
740bf72f0c Merge pull request #3202 from openset/develop
Update: Htmlquote Htmlunquote
2018-06-23 22:43:53 +08:00
6b3b8607a0 Merge branch 'develop' into develop 2018-06-23 22:43:45 +08:00
b21c59ee70 Merge pull request #3206 from whilei/gofmt-2018-Jun-17-00-39
gofmt
2018-06-23 22:38:07 +08:00
fc2c96a177 add 'FOR UPDATE' support for querySet 2018-06-23 22:25:05 +08:00
ia
87ba3f3cd3 all: gofmt
Run standard gofmt command on project root.

- go version go1.10.3 darwin/amd64

Signed-off-by: ia <isaac.ardis@gmail.com>
2018-06-17 00:47:51 +02:00
b80b7b06fc Update: Redundant semicolon disableEscapeHTML 2018-06-14 11:55:07 +08:00
ad6c97ec1b Update: Htmlquote Htmlunquote 2018-06-13 15:43:01 +08:00
d3d97de312 Merge pull request #3200 from openset/master
Update: use PathEscape replace QueryEscape
2018-06-12 22:45:14 +08:00
bf915c3280 Update: use PathEscape replace QueryEscape
If filename contain space(" "), QueryEscape use "+" instead.
2018-06-12 16:15:20 +08:00
19c5cd130d Merge pull request #3190 from NSObjects/develop
add field comment on create table
2018-06-07 11:06:23 +08:00
1df2662924 add field comment on create table 2018-06-06 12:33:28 +08:00
f979050a45 Fix defaut value bug, and add default maxfiles
1. add default value for maxlines(100000), maxsize(1 << 28)
2. add maxfiles for configure, just like `maxlines` & maxsize
2018-06-03 23:08:03 +08:00
45b68d444d Add method to set the data depending on the accepted 2018-06-01 19:11:01 +02:00
732f79e758 Add dep travis 2018-05-31 14:52:47 +02:00
4e954e32b8 Test YAML 2018-05-31 13:48:24 +02:00
92e81ccf50 Merge branch 'develop' into feature/YAML 2018-05-31 13:35:44 +02:00
91f2005067 Test YAML 2018-05-31 13:35:23 +02:00
7c80bf6f9d Add YAML 2018-05-30 16:06:40 +02:00
cc2c98c112 update travis 2018-05-30 22:01:59 +08:00
c3c0adbf55 Merge pull request #3175 from mo0feng/master
Create redis_cluster.go
2018-05-28 16:48:06 +08:00
jz
04c305f273 fix use it comments
fix  use it comments
2018-05-24 15:14:56 +08:00
jz
8c8cf46b55 Create redis_cluster.go
super redis cluster
2018-05-23 17:30:13 +08:00
e96ae0c24a debug stringsToJSON
json char: \u four-hex-digits number(http://json.org/)
2018-05-21 15:18:18 +08:00
98a3cda260 Fix Unexpected EOF bug in staticfile 2018-05-07 13:51:05 +05:30
1fd7fa5df7 make example runable 2018-05-03 22:04:49 +08:00
3d3f2ed4c5 Merge pull request #3127 from kaka89/master
Refactor yaml config for support multilevel
2018-05-03 14:07:59 +08:00
0f73050567 add code style for logs README 2018-05-03 12:05:59 +08:00
a40899e6be Merge pull request #3145 from gadelkareem/develop
Allow log prefix
2018-05-03 11:27:50 +08:00
a9a15e2c54 Allow log prefix 2018-05-02 00:24:09 +02:00
896c258e44 Log redirects and abort after redirect 2018-04-30 17:48:01 +02:00
6df42d63e2 Fix response http code 2018-04-29 15:12:32 +03:00
33bf80b052 Merge branch 'pr/3141' into patch-2 2018-04-28 20:07:23 +02:00
d5c1c0e9a4 log errors in access log and make static request logging optional 2018-04-28 20:03:39 +02:00
8e61a6a6de Allow access log regardless of the log level 2018-04-28 17:15:19 +02:00
ccaa2dd9e0 Update yaml.go
delete white line.
2018-04-20 19:44:22 +08:00
507ea757d7 Merge pull request #3039 from cloudzhou/patch-1
execElem.FieldByName as local variable
2018-04-20 19:41:07 +08:00
9d526dfd50 Merge pull request #3100 from godcong/master
change github.com/garyburd/redigo to newest branch github.com/gomodul…
2018-04-20 19:40:30 +08:00
ba89253e4a Update yaml.go
add support for multilevel yaml config
2018-04-20 19:40:06 +08:00
0d6f190e72 Merge pull request #3107 from sergeylanzman/patch-1
Update .travis.yml golang 1.10
2018-04-20 19:33:50 +08:00
91b9a65db0 Merge pull request #3109 from Jeff885/Jeff885-patch-1
When log maxSize set big int,FileWrite Init fail
2018-04-20 19:33:33 +08:00
e96a5fb3ca Merge pull request #3115 from m4grio/minor-typo
Amend a very minor typo in a variable name
2018-04-20 19:26:42 +08:00
f5f70f386d Merge pull request #3126 from aruhi/master
In dev mode, template parse error cause program lock
2018-04-20 19:26:24 +08:00
242efcf7fa Merge pull request #3103 from qshuai/master
fix typo
2018-04-20 19:26:00 +08:00
51cc6fc257 Update template.go 2018-04-20 19:42:50 +09:00
5fb29cb772 Amend a very minor typo in a variable name 2018-04-10 12:19:50 +08:00
2da894d4a7 When log maxSize set big int,FileWrite Init fail
example:
beego.SetLogger("multifile", {"filename":"logs/liverelay.log","separate":[ "emergency", "error", "info", "debug"],"maxsize":250000000}).

json: cannot unmarshal number 2.5e+08 into Go value of type int

The err should return and show the developer.
2018-04-06 00:50:35 +08:00
2623b15ce0 Update .travis.yml 2018-04-05 16:30:08 +03:00
6db9ad7002 auto create log dir 2018-04-04 15:59:52 +08:00
889408136b fix typo 2018-03-28 00:26:06 +08:00
886fefe738 change github.com/garyburd/redigo to newest branch github.com/gomodule/redigo 2018-03-26 16:59:01 +08:00
768406f134 Merge pull request #3076 from gadelkareem/patch-1
Set default Beego RunMode to production
2018-03-11 16:26:00 +08:00
075e63b2bd Merge pull request #2999 from moririnson/fix_unable_to_add_column
fix the issue #2998
2018-03-11 16:18:50 +08:00
0057c08a90 Merge pull request #3085 from WUMUXIAN/swagger
Swagger: Allow example values with different types, allow example for enum.
2018-03-11 10:48:48 +08:00
09b073356d Swagger:
1. Allow example value to be given based on the field type, previously it's a string.
2. Allow to give example values for Enum values.

This is for the beego/bee pull request to work well.
2018-03-10 17:15:24 +08:00
3c9ed48630 Set default Beego RunMode to production 2018-03-02 18:23:20 +01:00
65d8b4f544 Merge pull request #3064 from takeo-lvgs/dev
fix the issue #3063
2018-02-22 17:22:39 +08:00
6d18d4dcdd Merge pull request #3066 from takeo-lvgs/fix_3065
fix the issue #3065
2018-02-22 17:16:38 +08:00
21fe2d519e fix the issue #3065 2018-02-20 17:40:18 +09:00
9a7554fa01 fix the issue #3063 2018-02-20 11:39:29 +09:00
37d1c13603 Merge pull request #3046 from aspacca/master
Handle pointer validation
2018-02-02 18:57:13 +08:00
5ed112e946 added CanSkipAlso 2018-02-02 10:22:43 +01:00
453f112094 added more test case 2018-02-01 18:31:04 +01:00
faa3341603 Fix after test failure 2018-01-28 18:19:27 +01:00
ee9cf05796 Handle pointer validation 2018-01-28 17:40:05 +01:00
6de538b136 execElem.FieldByName as local variable
execElem.FieldByName(fieldType.Name) as local variable
2018-01-25 17:52:09 +08:00
47c1072b78 do html escape before display path, avoid xss 2018-01-08 19:35:53 +08:00
e81f1e53bf Merge pull request #3017 from Medicean/develop
Update: Fix migration generate SQL
2018-01-05 00:10:16 +08:00
cf92d2c6ef Update: Fix migration generate SQL 2018-01-04 10:42:39 +08:00
0507076c3f Merge pull request #3004 from pcallewaert/develop
redis cache: make MaxIdle configurable
2017-12-30 13:54:11 +08:00
59fd3952b7 bug: restore the default value 2017-12-26 11:48:34 +01:00
7fd80e6aa1 feat(redis.go): make MaxIdle configurable 2017-12-26 11:48:08 +01:00
24fa6189b5 fix the issue #2998 2017-12-23 16:41:56 +09:00
0bde9cbd91 fix the issue #2995 2017-12-22 16:21:23 +08:00
122414d789 Merge pull request #2992 from priteshgudge/develop
Update Documentation in Output.go
2017-12-21 17:08:10 +08:00
aac69674ad Update Documentation in Output.go
Fix Documentation for HTTP status codes descriptions.
2017-12-21 13:50:28 +05:30
1a42154c64 add file test 2017-12-20 17:54:40 +08:00
e81cca304b add file test 2017-12-20 16:19:58 +08:00
07aa97aa9a add hourly rotate file.go 2017-12-20 15:56:36 +08:00
94fba0b2aa fix orm fields SetRaw function error judge problem 2017-12-20 14:53:00 +08:00
80aa47f605 Merge pull request #2976 from szyhf/develop
Fix #2975
2017-12-19 23:34:17 +08:00
f16688817a Merge pull request #2978 from BorisBorshevsky/fix_reflection_bug
fix bug #2972
2017-12-18 19:18:59 +08:00
2670a86005 fix #2979 2017-12-14 17:55:08 +02:00
0e369e6df8 fix bug 2017-12-13 15:27:32 +02:00
84443b9c05 Fix #2975
修复AccessLog输出会多换一行的bug
2017-12-12 12:21:55 +08:00
33be6803a3 Merge pull request #2970 from gcy3y/master
update log.go add GetLevel Function to Log
2017-12-10 20:26:46 +08:00
aef2f1c66e Merge pull request #2971 from PureWhiteWu/fix_typo
fix a typo
2017-12-10 18:47:54 +08:00
619cd2d908 fix a typo 2017-12-08 23:01:21 +08:00
4613acd88e update log.go add GetLevel Function to Log 2017-12-08 15:35:12 +08:00
bf5c5626ab Merge pull request #2943 from astaxie/develop
1.9.2
2017-12-06 23:37:36 +08:00
0fbbc67c3d Merge pull request #2961 from zhlicen/master
Add lock while releasing session
2017-12-06 14:44:25 +08:00
3e1916ec3c Merge pull request #2953 from szyhf/develop
Proposal to #2952
2017-12-06 14:43:12 +08:00
b068a676dd Merge pull request #2950 from huhaocc/change_httpmethod_type
Change the type of HTTPMETHOD
2017-12-06 14:42:35 +08:00
ed73bdcfab Add lock while releasing session
Solve the problem of SessionRead failure while ReleaseSession is in progress
2017-12-05 16:18:56 +08:00
ae94b705ea Merge pull request #2954 from axetroy/master
test: Improve test case for utils/safemap, make it 100% cover
2017-12-01 23:33:46 +08:00
08fb921053 test: Improve test case for utils/safemap, make it 100% cover 2017-12-01 01:04:15 +08:00
e67e57f8fb orm: 修复logic enum因为type enum改变而产生的位错位。 2017-11-30 20:26:34 +08:00
b30969704a Proposal to #2952 2017-11-30 18:12:49 +08:00
646acc423e Change HTTPMETHOD type 2017-11-30 01:43:50 +08:00
c3a81a23f9 beego 1.9.2 2017-11-27 15:52:31 +08:00
103dd22151 remove mysq travis 2017-11-27 15:42:18 +08:00
ec6cb43711 fix ci failed 2017-11-27 14:07:05 +08:00
84cb9a5986 update to go1.9.2 2017-11-26 14:35:37 +08:00
9b8bc2aef7 Merge pull request #2941 from BorisBorshevsky/report-card
add report card to readme.md
2017-11-26 14:32:57 +08:00
9710d9e961 Merge pull request #2940 from BorisBorshevsky/golint
fix golint comments
2017-11-26 14:32:40 +08:00
58bb49a78c add report card to readme.md 2017-11-25 19:23:46 +02:00
df37739c7d fix golint comments 2017-11-25 19:18:37 +02:00
a5dd5d161d Merge pull request #2659 from ansiz/master
to close issue #1899(redis cache doubt)
2017-11-19 11:13:42 +08:00
6827107177 Merge pull request #2706 from fat4lix/bugfix
Fix run controller if it set by RumController and RunMethod in Filterfunc
2017-11-19 11:12:48 +08:00
a30a89e57e Merge pull request #2849 from iclinux/grace-patch
Make parent process exit gracefully.
2017-11-19 11:09:13 +08:00
d352e4abcb Merge pull request #2852 from Radar8/master
validation: fix ErrorMap, added AddError(key, message)
2017-11-19 11:08:31 +08:00
a948d4c1e1 set default to apache format 2017-11-19 11:07:57 +08:00
b7eb3963f5 Merge pull request #2863 from gadelkareem/develop
Add JSON or Apache access log formatting option to config:  AccessLogsFormat = JSON_FORMAT or APACHE_FORMAT  ref #2738
2017-11-19 11:05:12 +08:00
f7afb3cb75 Merge pull request #2878 from silviucm/master
Add the ability to unregister fixed routes
2017-11-19 10:41:40 +08:00
348bf51a42 Merge pull request #2914 from AbelZhou/master
Add sys env feature
2017-11-19 10:41:22 +08:00
dfea2cc5f3 Merge pull request #2928 from ilylia/develop
add Enum field to Schema
2017-11-19 10:27:11 +08:00
532eab8e1d Merge pull request #2932 from lotus-wu/Branch_v1.9.0
1.Add Mutual HTTPS  Option!
2017-11-19 10:26:59 +08:00
3872382a4b 1.Add Mutual HTTPS Option! 2017-11-15 22:42:30 +08:00
4018693fbd add Enum field to Schema 2017-11-13 14:36:08 +08:00
3b829504f6 Merge pull request #2920 from chenpeiyuan/develop
avoid unnecessary read of large log file
2017-11-07 09:35:09 -06:00
80fa51468c avoid unnecessary read of large log file
If w.MaxLines is not set, there is no need to calc large log file’s lines. It may takes more than 10mins to calc a 10G file.
2017-11-07 22:58:39 +08:00
3504d2a4da Add host env feature. 2017-10-31 19:19:14 +08:00
229d8b9530 Add host env feature. 2017-10-30 13:54:36 +08:00
9536d460d0 Create test file for the route unregistering functionality 2017-10-28 14:49:41 -04:00
e211e4839c Merge pull request #2906 from mlgd/patch-1
Update for MySQL timezone detection bug
2017-10-27 09:47:09 -05:00
3332dbe595 Update for MySQL timezone detection bug
Use "DefaultTimeLoc" for "al.TZ" default value
Don't set TZ on alias when t.Location() is empty

You can set your MySQL server timezone on main.go init function.
Example :
orm.DefaultTimeLoc, _ = time.LoadLocation("Europe/Paris")
2017-10-26 14:32:42 +02:00
b9c8c08c03 Add host env feature. 2017-10-26 19:25:05 +08:00
663f22d849 Merge pull request #2893 from melotusme/master
Typo fixed
2017-10-23 06:48:46 -05:00
fbaa4d1233 Merge pull request #2898 from skOak/swagger
remove omitempty for swagger.Response.Description, because it's Required according to Swagger2.0 Spec
2017-10-23 06:48:22 -05:00
7dc8991140 Merge pull request #2894 from skOak/develop
add custom middleware options for beego.Run()
2017-10-23 06:48:03 -05:00
0ce70b8c99 remove omitempty for swagger.Response.Description, because it's Required according to Swagger2.0 Spec 2017-10-18 22:34:24 +08:00
b169ea4b63 Merge pull request #2896 from tinycedar/master
misc: fix typos
2017-10-17 21:22:27 +08:00
72ec4df679 Merge branch 'master' into master 2017-10-17 04:30:59 -05:00
b91263a254 misc: fix typos 2017-10-17 17:27:03 +08:00
e91afb1938 add custom middleware options for beego.Run() 2017-10-16 14:55:08 +08:00
74eb613919 Typo fixed 2017-10-16 00:06:20 +08:00
32d4310861 Merge pull request #2886 from hurisheng/patch-1
add XMLBody method for httplib
2017-10-14 07:57:02 -05:00
c56704f3fd Merge branch 'master' into develop 2017-10-14 17:53:40 +08:00
c5118e9535 Merge pull request #2889 from lidaobing/fix_typo
fix typo
2017-10-14 03:28:56 -05:00
9b57566963 fix typo 2017-10-11 14:35:31 +08:00
8d59e7afd1 for the root path, all methods must be covered
use continue instead of return
2017-10-07 13:16:36 -04:00
fd733f76f0 simplify replacement of the base (root) tree 2017-10-07 12:14:28 -04:00
37d4bb3df5 add XMLBody method for httplib 2017-10-05 14:34:52 -05:00
5697c6d7cc Remove redundant return to pass gosimple Travis check 2017-09-25 23:17:57 -04:00
51a6162363 Update app.go 2017-09-25 21:45:42 -04:00
5a12b3d020 Add the ability to unregister fixed routes
Certain web application inherit most of the routes from a base application by using the underscore import 
(e.g. import _ "myoldapp.com/routers").
The new application might want to only overwrite certain pages, such as "/about" or "/faq"

The proposed new UnregisterFixedRoute method allows unregistering of the specified paths.
 Usage (replace "GET" with "*" for all methods):
  beego.UnregisterFixedRoute("/yourpreviouspath", "GET")
  beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")
The children paths are left intact.
For example, /yourpreviouspath/oldchildsubpath should still continue to function in legacy mode.
2017-09-25 20:52:19 -04:00
bebd2c469d Remove typo 2017-09-13 22:15:40 +02:00
d15e66a4ff check if SetEscapeHTML exists instead of checking Go version 2017-09-13 22:14:41 +02:00
c04d43695c fix dependency go-version for travis 2017-09-13 03:16:33 +02:00
d813334a24 Merge branch 'develop' of github.com:gadelkareem/beego into develop 2017-09-13 03:10:08 +02:00
9fef2f2eb4 Do not escape html if Golang version < 1.7 2017-09-13 03:09:53 +02:00
0c746f4547 Merge branch 'master' into develop 2017-09-13 02:16:50 +02:00
f5c8b1c6ac Merge branch 'master' of github.com:gadelkareem/beego 2017-09-13 02:05:15 +02:00
4921014c64 Add JSON or Apache access log formatting option to config: AccessLogsFormat = JSON_FORMAT or APACHE_FORMAT ref #2738 2017-09-13 02:03:46 +02:00
520753415f Merge pull request #2846 from hikenote/master
return template build error rather than log error
2017-09-09 06:42:02 +08:00
3162da131d Merge pull request #2858 from astaxie/revert-2854-master
Revert "should use time.Since instead of time.Now().Sub"
2017-09-09 06:29:59 +08:00
a7354d2d08 Revert "should use time.Since instead of time.Now().Sub" 2017-09-09 06:29:38 +08:00
07a9a2d0f3 Merge pull request #2854 from wgliang/master
should use time.Since instead of time.Now().Sub
2017-09-09 06:29:31 +08:00
c8c25549e7 should use time.Since instead of time.Now().Sub
Signed-off-by: wgliang <liangcszzu@163.com>
2017-09-07 19:01:34 +08:00
6641a436a2 validation: fix ErrorMap, added func AddError(key, message) 2017-09-06 16:49:21 +08:00
1dd50fb65f Make parent process exit gracefully.
With beego.BConfig.Listen.Graceful  enabled, when received SIGHUP, we'll fork a child process.
But the parent process still have jobs to finish, So we can't kill the parent process directly.
2017-09-05 11:53:42 +08:00
4bc4f77c29 return template build error 2017-09-02 17:55:26 +08:00
ef36ecd376 avoid some proxy not support select command 2017-08-31 20:26:32 +08:00
c6cef853c7 Merge pull request #2813 from mlgd/develop
Add IPV6 compatibility
2017-08-23 16:54:59 +08:00
33ad8d5db4 Merge pull request #2815 from wisererik/patch-1
Fix the quick start section of the orm/README.md
2017-08-23 16:53:41 +08:00
33e6d57754 Merge pull request #2820 from crazcalm/doc_error
fixed mispelled word
2017-08-22 23:18:31 +08:00
afa57ca1f2 fixed mispelled word 2017-08-20 23:32:11 +08:00
510dd02a06 Fix the quick start section of the orm/README.md
Increase the init method by adding the `RunSyncdb` method to resolve the problem that the table is not created.
2017-08-11 11:34:18 +08:00
166e88c103 Update input.go 2017-08-09 21:05:06 +02:00
51b6adeb24 Add IPV6 compatibility 2017-08-09 10:23:03 +02:00
51c19c374a Merge pull request #2801 from nightlyone/patch-1
fix bad error code in seesion handling
2017-08-06 22:29:05 +08:00
b23452dc3f Merge pull request #2805 from ninjacn/master
comment edit
2017-08-06 22:28:36 +08:00
f61038e6bd Merge pull request #2803 from iamzhout/log_add_milliseconds
add millisecond to timestamp in log output
2017-08-06 22:28:19 +08:00
b9117e2ff1 add millisecond to timestamp in log output 2017-08-04 00:11:59 +08:00
5a7a3da909 comment edit 2017-08-03 19:15:32 +08:00
3f4502990a fix bad error code
By providing a unique error code instead of a format specifier without using an error formatting function.
2017-08-03 01:52:24 +02:00
e14113aa0e Merge pull request #2656 from BorisBorshevsky/develop
Allow injecting dependencies to controllers
2017-07-30 23:36:52 +08:00
d96289a81b Merge pull request #2771 from astaxie/develop
v1.9.0
2017-07-19 00:56:48 +08:00
4fc95b0d69 gofmt and golint 2017-07-19 00:52:27 +08:00
aa3d6c5363 fix the gosimple 2017-07-19 00:37:42 +08:00
5ac0cb929c v1.9.0 2017-07-18 23:58:22 +08:00
b27ab53017 fix issue for runMethod and runRouter from context 2017-07-18 23:41:50 +08:00
1aba294405 Merge pull request #2740 from xlwcom/master
fix the bugs in the "ParseBool" function in the file of config.go
2017-07-18 13:39:45 +08:00
657e55ed59 Merge pull request #2692 from jerson/master
added statusCode and pattern to FilterMonitorFunc
2017-07-17 11:06:09 +08:00
621c25396e Merge pull request #2766 from yangsf5/master
sort ControllerComments
2017-07-17 11:02:28 +08:00
715ba918f0 Merge pull request #2744 from gnanakeethan/feature/database-migration
[Proposal] Database Migrations;
2017-07-17 10:54:44 +08:00
8bb0a70847 Update: Fix in SQL Generation
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-16 08:48:44 +05:30
94e79eddcf Update: removing remnant of revert commit ( a call to function
m.DDLSpec() )

Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-16 08:37:27 +05:30
749a4028b4 Revert "Update: removing the need to call DDLSpec in the migration file"
The odds of getting this perfectly up is not good.

This reverts commit d58ad2ee36.
2017-07-16 08:11:10 +05:30
fc55c2b57c Update: missed to call DDLSpec in Down migration
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-16 07:30:53 +05:30
d58ad2ee36 Update: removing the need to call DDLSpec in the migration file
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-16 07:24:58 +05:30
cb38ab4f85 Update: fixing a SQL generation code
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-16 07:10:09 +05:30
fc86f6422d sort ControllerComments 2017-07-15 17:26:20 +08:00
d453242e48 Update: moving package to bottom
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-14 14:42:56 +05:30
7c2ec075a4 Update: fixing some methods and adding documentation
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-13 21:03:30 +05:30
c903de41e4 updated sample for FilterMonitorFunc
added pattern to sample
2017-07-12 09:51:37 -05:00
e8c8366308 Merge pull request #2754 from imiskolee/develop
supported gzip for req.Header has `Content-Encoding: gzip`
2017-07-12 19:57:29 +08:00
4901567bba Merge pull request #2749 from satng/patch-4
oracle插入占位符
2017-07-12 19:49:32 +08:00
29bcd31b27 supported gzip for req.Header has Content-Encoding: gzip 2017-07-10 21:27:54 +08:00
83a563c0ab oracle插入占位符 2017-07-09 12:25:51 +08:00
e888fee4e0 Update: Foreign Key & Comments
Summary: Foreign Key functions are now available

Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-06 20:26:37 +05:30
c1ba11f531 Fixing typo
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-06 14:58:40 +05:30
ed558a0e70 Fix: typo due to find and replace migration renamed to m
Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-06 07:45:07 +05:30
6b9c3f4824 [Proposal] Database Migrations;
Summary: The database migrations now can be created using the methods on
the migration struct. it does not break any existing migration features.
it upgrades the migration struct and adds few more struct types so that
the migrations can be efficiently generated for create, alter, reverse,
drop.

Current Features:
* Supports creation of columns
   * `m.NewCol("name").SetDataType("VARCHAR(10)").SetNullable("true")`
   * **NOTE** `SetNullable` & `SetDefault` methods should not be called on
   same column for consistency
* Supports addition of primary keys
   * `m.PriCol("id").SetDataType("INT(10)").SetNullable("true")`
   * **NOTE** `setAuto(true)` can be only called on Primary keys
* Supports addition of unique keys
   * `m.UniCol("unique_index","column_name").SetDataType("VARCHAR(23)").SetNullable("true")`
   * **NOTE** `UniCol` can be called again with the same index name to
   add column to the index
* Supports rename of columns
   * `m.RenameColumn("from_name","to_name")`
   * Allows standard column methods and methods such that, `SetOldDefault` allows
   reversibility of renames

* TODO:
   * ForeignKey

Signed-off-by: Gnanakeethan Balasubramaniam <gnanakeethan@gmail.com>
2017-07-06 07:44:48 +05:30
7ec819deed fix #2725 big form 2017-07-04 21:16:59 +08:00
4cfb3678f8 Merge pull request #2741 from miraclesu/validation
validation: support required option for some struct tag valids
2017-07-04 15:49:36 +08:00
3c17e2a7e6 remove the comments 2017-07-04 11:03:49 +08:00
e72b02b7cc validation: support required option for some struct tag valids 2017-07-03 16:26:23 +08:00
82586c70e9 Merge pull request #2683 from jialijelly/master
Provide permission to access old files to everyone
2017-07-03 11:23:49 +08:00
cb86bcc9e8 Merge pull request #2728 from miraclesu/validation
validation: support int64 int32 int16 and int8 type on 64-bit platform
2017-07-01 15:35:48 +08:00
234708062a fix the bug in the "ParseBool" function in the file of config.go 2017-06-29 13:32:40 +08:00
6e34f43721 Fix break API change
support int64 on 64-bit platform
2017-06-28 16:56:37 +08:00
3249ec8ebf Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-27 10:49:10 +08:00
31b2b21dbc Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-27 10:48:52 +08:00
d0c1936922 Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-22 19:18:49 +08:00
338a23a12b Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-22 19:18:34 +08:00
932def1ed2 Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-22 18:55:37 +08:00
16b5a11484 Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-22 18:55:25 +08:00
547fbce86c Merge branch 'master' of https://github.com/jialijelly/beego 2017-06-22 18:53:29 +08:00
5a2eea07cb Provide permission to access old log files to everyone 2017-06-22 18:51:52 +08:00
2231841d74 validation: support int64 int32 int16 and int8 type 2017-06-21 14:13:30 +08:00
805a674825 Merge pull request #2712 from eyalpost/develop
incorrect error rendering (wrong status)
2017-06-16 13:34:28 +08:00
f2925978f1 Merge pull request #2717 from huwenbo/master
fix panic sync: negative WaitGroup counter
2017-06-16 13:26:36 +08:00
fe3a224a23 Merge pull request #2724 from JessonChan/develop
AddAPPStartHook func modify
2017-06-16 08:20:45 +08:00
2754edc849 Merge pull request #2726 from moqiancong/develop
fix cache/memory fatal error: concurrent map iteration and map write
2017-06-16 08:20:03 +08:00
79f60274a0 fix cache/memory fatal error: concurrent map iteration and map write 2017-06-16 01:26:55 +08:00
a87c1c5e8e AddAPPStartHook func modify 2017-06-15 17:36:37 +08:00
2b00b7d66d fix panic: sync: negative WaitGroup counter 2017-06-13 20:15:43 +08:00
3d9286f089 fix panic: sync: negative WaitGroup counter 2017-06-13 15:34:57 +08:00
55e6c15073 fix panic: sync: negative WaitGroup counter 2017-06-13 15:19:51 +08:00
8b504e7d51 incorrect error rendering (wrong status) 2017-06-12 21:05:40 +03:00
47ef2b343e Fix run controller if it set by RumController and RunMethod in Filterfunc 2017-06-09 15:53:03 +03:00
80dcdb8645 Fix run controller if it set by RumController and RunMethod in FilterFunc 2017-06-09 15:27:26 +03:00
d1c3bd8416 Merge pull request #2701 from eyalpost/develop
correctly handle multiple params with same type
2017-06-09 15:33:37 +08:00
0240e182c6 correctly handle multiple params with same type 2017-06-09 10:15:36 +03:00
7f2e3feb3c added pattern to FilterMonitorFunc 2017-06-05 18:21:31 -05:00
d15dd2795c added statusCode in FilterMonitorFunc 2017-06-03 15:24:45 -05:00
0ea34fff27 Provide permission to access old log files to everyone 2017-06-02 10:56:55 +08:00
4e8f212069 refactor: #1899 redis cache module refactor
redis cache module refactor, to view the discussion:

  https://github.com/astaxie/beego/issues/1899
2017-05-20 19:56:38 +08:00
eb71d0ea7f Merge remote-tracking branch 'upstream/master' 2017-05-20 19:39:24 +08:00
b24ddb953c merge from upstram + resolve conflicts 2017-05-20 02:42:00 +03:00
12f8fbe37f Allow injecting dependencies to controllers 2017-05-20 02:06:28 +03:00
5e8312bc23 Merge pull request #2654 from casbin/master
Fix the new repo address for casbin.
2017-05-19 23:34:58 +08:00
88d07058a5 Fix the new repo address for casbin. 2017-05-19 22:19:31 +08:00
cab8458c1c Merge pull request #2651 from astaxie/develop
v1.8.3
2017-05-19 21:19:18 +08:00
f0b95c552b Merge pull request #2315 from sch00lb0y/master
issue no:#2261 fix for xsrf panic error
2017-05-19 18:50:56 +08:00
ce677202e5 issue no:#2261 fix for xsrf panic error 2017-05-19 14:02:14 +05:30
720c323e20 Merge pull request #2652 from gouyang/gouyang/dev
Support timeformat "2006-01-02T15:04:05"
2017-05-19 09:48:35 +08:00
47e351e11d Support timeformat "2006-01-02T15:04:05"
Fixes #2649

Signed-off-by: Guohua Ouyang <guohuaouyang@gmail.com>
2017-05-19 09:22:27 +08:00
248beab557 v1.8.3 2017-05-18 22:55:10 +08:00
388a5610fa Merge pull request #2365 from chesedo/RequiredValidationCatchSpaces
[WIP]Have Required validator trim strings to fix #2361
2017-05-18 22:44:15 +08:00
41498758fe Merge pull request #2620 from hsluoyz/authz
Add an authorization plugin that supports ACL, RBAC based on casbin.
2017-05-18 18:18:12 +08:00
655484b4df Merge pull request #2586 from eyalpost/develop
Automatic Parameter Router
2017-05-18 18:14:49 +08:00
11b4bf8aaa move to context 2017-05-18 10:38:12 +03:00
2513bcf584 remove Redirect to avoid confusion 2017-05-18 10:32:51 +03:00
3e51823c0f move response 2017-05-18 09:05:49 +03:00
e32a18203b fix gosimple 2017-05-17 21:27:32 +03:00
ee1d8bc30e fix gosimple 2017-05-17 20:50:41 +03:00
828cbbdf5d Refactor a bit to consolidate packages 2017-05-17 20:38:59 +03:00
d54cd4fa5f Merge remote-tracking branch 'upstream/develop' into develop 2017-05-17 20:02:40 +03:00
7747e9ec8b Merge branch 'develop' of https://github.com/astaxie/beego into develop 2017-05-17 20:52:53 +08:00
9765519f38 Merge pull request #2637 from alexsunxl/develop
allow o.Raw(sql).QueryRows(&container) pass nested struct
2017-05-17 16:45:14 +08:00
69f0b94745 fix gosimple 2017-05-16 22:21:43 +08:00
3c9b6c99b7 Merge pull request #2643 from rbw0/master
Spelling fixes
2017-05-16 11:26:16 +08:00
b5c6eb54d2 Missing PK error spelling fix 2017-05-16 00:58:20 +02:00
e1c90bfc09 Table not found spelling fixes 2017-05-16 00:27:57 +02:00
91400f10b0 Merge pull request #2640 from franzwilhelm/master
Moved Security to Operation struct to support swagger API security auth
2017-05-14 19:15:20 +08:00
c814893d65 add support for global security 2017-05-14 12:13:35 +02:00
2325090101 add test case that used nested struct test QueryRows 2017-05-14 12:03:34 +08:00
40bc52b844 fix security struct placement and formatting 2017-05-14 00:42:09 +02:00
589f3755f0 允许o.Raw(sql).QueryRows(&container) 传入的container包含结构的嵌套 2017-05-12 18:11:42 +08:00
1004678005 popular status codes 2017-05-12 09:57:56 +03:00
0ac2e47162 location=>paramType 2017-05-12 09:28:46 +03:00
b6a35a8944 more tests 2017-05-12 09:25:12 +03:00
74dc3c7500 tests 2017-05-11 19:32:44 +03:00
cb4f252a06 defValue -> defaultValue 2017-05-11 17:58:25 +03:00
bceefc9075 Merge pull request #2636 from guanly/master
ISSUE2630 使用sqlite,orm中通过filter后的delete删除不成功
2017-05-11 22:04:27 +08:00
10cd1070f4 使用sqlite,orm中通过filter后的delete删除不成功
https://github.com/astaxie/beego/issues/2630
2017-05-11 21:45:38 +08:00
9b01b1c63d ISSUE2630 使用sqlite,orm中通过filter后的delete删除不成功
https://github.com/astaxie/beego/issues/2630
2017-05-11 14:49:01 +08:00
b2e7720fcd Add an authorization plugin that supports ACL, RBAC based on casbin. It requires the built-in HTTP basic authentication by default. 2017-05-04 14:02:21 +08:00
83814a76cc hotfix: err nil 2017-05-02 12:47:15 +08:00
d3a16dca85 Redirect should returns error 2017-05-01 08:57:57 +03:00
7452151bee Merge pull request #2611 from astaxie/develop
1.8.2
2017-05-01 13:01:59 +08:00
1b8f05cef1 golint fixes 2017-04-30 19:28:26 +03:00
cfb2f68dd6 Merge remote-tracking branch 'upstream/develop' into develop 2017-04-30 18:59:50 +03:00
e76423e6dc revert #2518, fix #2605 2017-04-30 23:59:38 +08:00
947980b5eb beego 1.8.2 2017-04-30 23:43:46 +08:00
44bdf1df63 ignore NilErr 2017-04-30 23:38:48 +08:00
79b66ef053 fix the beego ORM test 2017-04-30 22:55:39 +08:00
a91e2e9950 add golint check and fix all golints 2017-04-30 22:41:23 +08:00
ea3d0690cf golint 2017-04-29 09:13:28 +08:00
1c32c011a1 fix misspell 2017-04-28 23:37:40 +08:00
64b475d7d6 fix ReadOrCreate test case 2017-04-28 22:58:17 +08:00
aa8f7bc146 fix ineffectual 2017-04-28 22:36:28 +08:00
3e29078f68 add check ineffect and gofmt 2017-04-28 21:38:08 +08:00
a1bc94e648 dont generate comment if router not found 2017-04-26 01:00:25 +03:00
4cba78afd9 small fixes 2017-04-25 23:42:35 +03:00
f311ae9ebe feature: Export function printTree (#2597)
This exports PrintTree function which allow to set Role Based Access Control, Create our own requests statistics...etc
2017-04-25 18:12:03 +02:00
cbd831042a move under context 2017-04-25 18:39:42 +03:00
522b3a4a70 Merge pull request #2596 from astaxie/develop
beego 1.8.1
2017-04-25 22:51:23 +08:00
cd67f13bf9 add template layout test #2481 2017-04-25 22:21:27 +08:00
0f554d9b1a update travis to latest go version 2017-04-25 22:21:08 +08:00
9b79437778 all types working + controller comments generation 2017-04-25 16:00:49 +03:00
3742d1178c httplib support delete params fix #2593 2017-04-25 20:42:43 +08:00
b9e3cbbf44 feat: export function printTree
we can do more thing with an exported PrintTree function, such as
  set role base access control,create our own requests statistics.
2017-04-25 12:42:36 +08:00
3c0c87f473 Merge pull request #1 from astaxie/master
merge from origin repo
2017-04-25 12:38:32 +08:00
3b29a9c12a Merge remote-tracking branch 'upstream/develop' into develop 2017-04-24 18:23:58 +03:00
d03285a0ee Merge pull request #2555 from Liaodd/master
Update ini.go: change the key to lowercase when set a new key for ini configer
2017-04-24 22:37:25 +08:00
e810f2e930 add more oracle alias 2017-04-24 21:36:07 +08:00
41aac79ac0 Merge pull request #2590 from amrfaissal/fix-2587
Fix warnings raised by gometalinter and gosimple
2017-04-24 21:14:00 +08:00
52f916a28a support Go1.8 default GOPATH 2017-04-24 21:10:03 +08:00
864693d2f8 mall fixes 2017-04-24 02:35:04 +03:00
08ea9b3339 Merge remote-tracking branch 'upstream/develop' into develop 2017-04-23 22:07:46 +03:00
19f4a6ac0b slice support 2017-04-23 21:37:09 +03:00
bf6bd6b292 Fixes #2587
Fixes warnings and errors raised by gometalinter and gosimple.
2017-04-23 19:19:05 +02:00
89e01d125c all types implemented 2017-04-23 01:33:50 +03:00
3bb4ca5adc Merge pull request #2583 from OlegFX/develop
Fixed InsertOrUpdate bug
2017-04-22 11:19:15 +08:00
712df81c99 Fixed InsertOrUpdate bug 2017-04-21 19:57:04 +03:00
3d7ef599cc Merge pull request #2 from astaxie/develop
Update
2017-04-21 19:50:33 +03:00
9aedb4d05a phase #1 2017-04-21 15:26:41 +03:00
453691728a gofmt simplify 2017-04-20 10:56:09 +08:00
e7e3ca77ad Merge pull request #2491 from chendx79/master
Fix routing bug for splat matching
2017-04-19 21:20:30 +08:00
d3f3956def Merge pull request #2574 from extrlibs/master
Fix the following template reference
2017-04-19 21:18:26 +08:00
7206214105 Merge pull request #2575 from PaulChen2016/master
Beego 运行过程中动态增减定时任务时,now的时间需要更新,否则等待时间会不正确
2017-04-19 21:17:38 +08:00
b08ace7532 Merge pull request #2577 from ggicci/develop
Fix ini parsing error for multiple users on one machine.
2017-04-19 20:17:45 +08:00
d1a2583972 Fix ini parsing error for multiple users on one machine.
If there were multiple users working on one machine, it's common that
"/tmp/beego" will be owned by one of them, and the others won't be able
to access to it. So, it's better to add an "id-like" postfix to the
temporary directory.
2017-04-19 19:50:11 +08:00
0cb8de4218 Beego 运行过程中动态增减定时任务时,now的时间需要更新,否则等待时间会不正确
beego 启动时,执行toolbox.StartTask()
运行过程中,动态添加定时任务(这个是now时间已经不是starttask的时间了,需要刷新)     
     case <-changed:
			now = time.Now().Local()
			continue
2017-04-19 16:22:58 +08:00
0cd31a247f fix Template nesting problem 2017-04-19 07:47:05 +08:00
7886e69236 Update sess_file.go 2017-04-17 12:37:54 -04:00
405c170d45 Merge pull request #2556 from zjjott/master
fix: log mode should be 0440 should not be 440
2017-04-10 21:14:34 +08:00
932019770d fix: log mode 0440 should not be 440 2017-04-10 17:37:55 +08:00
d5c03f5b8f Update ini.go
change the key to lowercase when set a new key for ini configer
2017-04-10 11:30:23 +08:00
3d20c0b8f4 Merge pull request #2543 from Bobochka/fix_route_hander_docs
Fix example for Hander func
2017-04-07 23:04:38 +08:00
a4fb4c6a03 Merge pull request #2547 from TrueFurby/patch-1
Update README.md
2017-04-03 20:25:41 +02:00
a9941b6edc Merge branch 'develop' into patch-1 2017-04-02 13:46:06 +02:00
6a32b048bd Update README.md 2017-04-02 11:04:08 +02:00
fb04d3cff1 Fix example for Hander func 2017-03-30 12:53:12 +03:00
5c7673e73d update to 1.8.1 2017-03-29 10:22:27 +08:00
54b05377d9 Merge pull request #2466 from gouyang/gouyang/develop
Parse form time by its length
2017-03-29 10:01:03 +08:00
f49f3f92ec Merge pull request #2533 from cnxh/redis-session-poolsize
redis poolsize could set to zero
2017-03-29 10:00:28 +08:00
b18b94f03b Merge pull request #2539 from astaxie/revert-2421-develop
Revert "close mysql connection"
2017-03-29 09:57:54 +08:00
bf469f0b55 Revert "close mysql connection" 2017-03-29 09:57:18 +08:00
c12709dbc9 Merge pull request #2536 from ChristophPech/master
Fix for IndexExists in SQLite driver
2017-03-29 09:53:55 +08:00
2808a13f07 Fix for IndexExists in SQLite driver, they added the "origin" and "partial" columns to the index_list pragma.
see: https://www.sqlite.org/src/info/2743846cdba572f6
2017-03-28 12:38:27 +02:00
a8d48aa5ea Merge pull request #2535 from ketanhwr/patch-1
Update README.md
2017-03-28 10:49:52 +02:00
fdb2660a2a Update README.md 2017-03-28 11:29:20 +05:30
7c3a997735 poolsize could set to zero
sometimes we may want disable the redis pool
2017-03-27 23:34:58 +08:00
1760f0ceca Merge pull request #2532 from vbalien/patch-1
Fix markdown formatting
2017-03-27 13:34:19 +08:00
c387aeeb36 fix markdown formatting 2017-03-27 14:30:42 +09:00
83d4385f1f Support time.RFC3339
Signed-off-by: Guohua Ouyang <guohuaouyang@gmail.com>
2017-03-25 07:52:43 +08:00
ae0a75c464 console debug use diffrent color 2017-03-21 23:55:40 +08:00
a05e5a7c09 Merge branches 'master' and 'develop' of https://github.com/astaxie/beego into develop 2017-03-21 23:47:32 +08:00
75ca7b77b6 Merge pull request #2518 from sicojuy/develop
Fix set cookie bug, zero max age is not valid.
2017-03-21 09:44:37 +08:00
b0e2012a17 Fix set cookie bug, zero max age is not valid. 2017-03-21 09:15:30 +08:00
12dff072fa Merge pull request #2509 from sergeylanzman/add-gosimple
add go simple support
2017-03-18 13:37:31 +08:00
d956444965 Merge branch 'develop' into add-gosimple 2017-03-18 11:20:30 +08:00
8dbf9eb0bf Merge pull request #2512 from sergeylanzman/add-unconvert
add unconverted support
2017-03-18 11:05:28 +08:00
faa981fb6a Merge pull request #2511 from sergeylanzman/drop-go1.4-1.5-travis
drop support go1.4/5 in travis yml
2017-03-18 11:02:39 +08:00
1ea3c13ff5 Merge branch 'develop' into drop-go1.4-1.5-travis 2017-03-18 11:02:15 +08:00
46d8fef0ad Merge pull request #2510 from sergeylanzman/travis-add-1.7-1.8
add support go1.7/8 to travis yml
2017-03-18 11:01:27 +08:00
37c1ffc57a add go simple support 2017-03-17 20:22:20 +02:00
856fde28dc add unconverted support 2017-03-17 19:45:30 +02:00
3204d7631b drop support go1.4/5 in travis yml 2017-03-17 19:33:54 +02:00
f5fc2edfd3 add support go1.7/8 to travis yml 2017-03-17 19:32:31 +02:00
21d1267c14 Merge pull request #2501 from sergeylanzman/change-template-error-log
temple parse error write in log as trace. change to error
2017-03-14 20:04:42 +08:00
3e37b97549 temple parse error write in log as trace. change to error 2017-03-14 12:55:40 +02:00
206f736819 Merge pull request #2496 from eyalpost/develop
Don't panic during AddViewPath if adding the same path twice
2017-03-14 12:54:48 +08:00
24d4a27842 Don't panic during AddViewPath if adding the same path twice 2017-03-13 08:46:57 +02:00
46f3ea4f43 Merge pull request #2494 from miraclesu/develop
validation: fix email valid
2017-03-12 22:26:25 +08:00
c9cc642d37 validation: amend email test case 2017-03-12 20:27:09 +08:00
b34853f8cc validattion: add test case for email valid 2017-03-12 19:30:23 +08:00
d41f4c0a3a validation: fix email valid 2017-03-12 19:23:46 +08:00
8e46decc8e fix routing bug for splat 2017-03-10 09:28:25 +08:00
323a1c4214 Merge pull request #2485 from astaxie/develop
beego 1.8.0
2017-03-06 21:59:04 +08:00
c5f838e785 beego 1.8.0 2017-03-06 21:29:41 +08:00
f53e98d11b Merge pull request #2348 from hongliang81/develop
Add Aliyun Logger
2017-03-05 22:45:32 +08:00
c2f7f3efa7 Merge pull request #2380 from fugr/config
config:fix handle include other.conf
2017-03-05 22:41:45 +08:00
1e5051e112 Merge pull request #2381 from chesedo/OrmStrongRelationships
Add strong relationship support to orm
2017-03-05 22:39:45 +08:00
fa44ff54bb Merge pull request #2479 from marianofevola/develop
Fix typo
2017-03-05 22:07:08 +08:00
4c6de379e0 Merge pull request #2480 from ysqi/fix
Fixed #2456 and strengthen bind
2017-03-05 22:06:46 +08:00
6d997366ed Fixed 2456 and strengthen bind 2017-03-04 20:23:55 +08:00
e0250e2871 Fix typo 2017-03-03 16:24:02 +00:00
3d629e7320 Merge pull request #2468 from antony66/ssdb_cache_fix_is_exist
Fixes issue #2467 with ssdb cache IsExist
2017-02-27 18:58:53 +08:00
74045090cc This fixes issue #2467 with ssdb cache IsExist 2017-02-27 14:14:16 +05:00
49fffe3ebe Parse form time by its length
Fix #2451

Signed-off-by: Guohua Ouyang <guohuaouyang@gmail.com>
2017-02-27 14:43:16 +08:00
50e294be32 fix the broken test 2017-02-27 09:41:15 +08:00
b235b48de4 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2017-02-26 22:21:37 +08:00
28011a5835 fix #2462 2017-02-26 22:20:11 +08:00
b03b0779dc Merge pull request #2455 from jyk1987/develop
Improve json coding performance
2017-02-25 19:01:12 +08:00
393e4c4969 Improve json coding performance 2017-02-22 17:38:26 +08:00
1d49a4bcbd Merge pull request #2417 from eyalpost/develop
support for multiple view paths
2017-02-13 12:37:17 +08:00
fc2c0f4fba Don't allow AddViewPath after beego run 2017-02-11 22:00:30 +02:00
2117aecf65 Merge pull request #2428 from awengo/master
Add http methods
2017-02-11 00:31:43 +08:00
8a2b697625 Add http methods 2017-02-10 17:45:47 +09:00
be586572e0 Merge pull request #2423 from ansiz/master
Add config field EnableErrorsRender
2017-02-10 13:19:20 +08:00
4e047bd483 Merge pull request #2427 from code1986/develop
Develop
2017-02-10 13:17:21 +08:00
db67ffbb94 1.simplify reading and writing file code
2.add apiauth test
2017-02-10 09:35:23 +08:00
90b03d34cc Merge pull request #2421 from code1986/develop
close mysql connection
2017-02-09 14:36:39 +08:00
872a964145 1.add "defer f.close()" in SessionRead to fix file handle leak if DecodeGob failed
2.rewrite SessionRegenerate
2017-02-09 14:18:30 +08:00
dade92d98b close mysql connection 2017-02-09 14:16:23 +08:00
dfa74faf43 support for multiple view paths 2017-02-07 22:18:33 +02:00
95562cff41 Merge pull request #2406 from xqbumu/patch-1
fix the bug to prevent rewrite t
2017-02-07 11:07:37 +08:00
9b714a7518 Add config field EnableErrorsRender
Add config field EnableErrorsRender to disable errors output
  with the template data, sometimes we do not want errors output
  with it even in dev mode, especially in API projects.
2017-02-06 12:33:15 +08:00
2a660820c9 Merge pull request #2389 from amrfaissal/feature-env-support
Package env for working with environment variables inside Beego
2017-01-23 21:15:06 +08:00
b55e20ac60 Merge pull request #2395 from duyazhe/fix_bug_orm_ne
fix filter with __ne bug
2017-01-23 21:12:58 +08:00
b0dcb5b91d Merge pull request #2400 from kerwin/master
Add GetCond func to querySet
2017-01-23 21:12:29 +08:00
5c76f62103 Add GetCond func to querySet 2017-01-18 17:04:23 +08:00
126dbdae2f use BeeMap instead of a regular map 2017-01-16 10:08:53 +01:00
24d8290a3f fix filter with __ne bug 2017-01-16 10:32:33 +08:00
957c0630c0 moved the env package to config/ 2017-01-14 10:15:02 +01:00
e32d173b0d fix the bug to prevent rewrite t
the t have paresed in line 212.
2017-01-14 15:03:49 +08:00
fbc9f8e640 Package env for working with env variables inside Beego
The package env makes it trivial to work with environment variables.
It allows getting values with defaults as a fallback.
New ENV variables can be set safely on the current process environment.
2017-01-13 18:10:25 +01:00
82d2ace3bd Add strong relationship support to orm 2017-01-11 20:16:38 +02:00
3fa7fc6e41 config:fix handle include other.conf
When include other.conf,other.conf is either absolute directory or under beego in default temporary directory(/tmp/beego).
maybe replace by current directory is better.
2017-01-11 18:55:53 +08:00
d1b58a00ce Merge pull request #2373 from fugr/config
avoid creating tmp files to read/parse config
2017-01-11 09:34:57 +01:00
6a2ee371a5 avoid creating new file to implements Config
There is no need to create new file in ParseData(data []byte) (Configer, error).Tet's make code simply.
2017-01-09 21:04:11 +08:00
a8a2dffc59 Have Required validator trim strings to fix #2361
This will cause the Required validator not to consider fields that has
only spaces or new lines to be regarded as valid. This is done by
checking if the trimmed version of the string is valid.
2017-01-06 10:12:22 +02:00
9266ece7a4 fix the retried 2017-01-05 18:27:23 +08:00
09c405990c Add Aliyun Logger 2017-01-04 15:53:20 +08:00
61e694f388 add retry 2017-01-03 22:50:45 +08:00
195c9b24eb Merge pull request #2359 from kbynd/patch-1
content-length not set in case EnableGZIP=true
2017-01-02 11:49:11 +08:00
2f6da122fd Update output.go 2017-01-02 09:17:17 +05:30
f0d1d7149b Update output.go 2016-12-31 16:14:38 +05:30
96387e9a9b EnableGZip=true,then content-length header missing
This results in responses with Content-Type as gzip as opposed to original content type.
This affects ServeJSON() function.
2016-12-31 16:04:34 +05:30
86f6470fb2 Merge pull request #2353 from skariuki/master
Fixed typo in orm/models_boot.go
2016-12-29 22:50:41 +01:00
d77160dafe ignore .vscode folder 2016-12-29 22:30:56 +01:00
caca5e37ba fixed typo in models_boot 2016-12-29 12:26:20 -05:00
189c73986b Merge pull request #2351 from amrfaissal/add-safemap-count
Add Count method to BeeMap struct
2016-12-29 11:42:47 +01:00
fe21305bb3 Removes redundant check if key exists in BeeMap 2016-12-29 11:11:39 +01:00
75ec8d33a2 Rewrite safemap_test suite 2016-12-28 12:44:35 +01:00
d736d0ca87 Adds Count method to BeeMap struct
This adds a Count() method to BeeMap struct that returns the number of
items within the safe map.
2016-12-28 12:44:35 +01:00
99093693c8 Merge pull request #2346 from legendtkl/master
Modify func camelString() to be more robust
2016-12-26 20:24:49 +08:00
c9c284be27 Modify func camelString to be more robust
1. In previous edition, for case "pic_url_1", the func will return
"PicUrl_1", but "PicUrl1" seems to be more reasonable.
2. More test cases please refer to utils_test.go
2016-12-25 21:09:06 +08:00
fa12dcf792 Merge pull request #2341 from kabab/content_type
Changing content type for template
2016-12-23 23:06:52 +08:00
b93f5c6f9c Merge pull request #2311 from amrfaissal/fix-2310
Ability to register pre/post signal handlers
2016-12-23 20:06:25 +08:00
f9791c1221 Merge pull request #2319 from mlgd/patch-1
Remove a regression on AppPath
2016-12-23 20:03:32 +08:00
8fac2d8d58 Don't rewrite content-type 2016-12-14 17:19:31 +00:00
e90f4bee1a Remove a regression on AppPath
The application path is incorrect on Windows with the command line "go run". AppPath is assigned to the temp directory instead the folder project
2016-12-09 09:37:10 +01:00
eb50221a15 Added method to register Pre/Post signal handlers 2016-12-06 13:48:31 +01:00
fc4801494d Added hookable signals 2016-12-06 13:48:31 +01:00
eba6afd6fb Merge pull request #2307 from CodeJuan/master
set perm of rotated log to 440
2016-12-06 15:10:00 +08:00
81328b72fa Merge pull request #2309 from mengskysama/patch-1
statistics lock
2016-12-06 15:03:10 +08:00
c0c113036b statistics lock 2016-12-06 14:57:15 +08:00
b788d74fd1 set perm of rotated log to 440 2016-12-06 12:44:00 +08:00
90999717dd Merge branch 'develop' 2016-12-05 23:14:26 +08:00
a20ccde90d beego 1.7.2 2016-12-05 22:58:29 +08:00
d548ddeb5b Merge pull request #2267 from centos-ren/develop
Fix :supervisor work dir
2016-12-05 22:57:38 +08:00
de99ac5da5 Merge pull request #2197 from OlegFX/master
policies implementation
2016-12-05 22:45:07 +08:00
e2d9d34c75 Merge pull request #2272 from szyhf/Fix#2263
Another Fix to #2263
2016-12-05 22:40:54 +08:00
bdb525831d Merge pull request #2293 from DusanKasan/develop
resolves #2291, introduces AndNotCond/OrNotCond to orm.Condition
2016-12-05 22:40:35 +08:00
22dba90ec4 Merge pull request #2305 from songtianyi/fixtypo-Getfiles
typo fix in comments, Getfiles-->GetFiles
2016-12-05 15:09:57 +08:00
7af6dad58e typo fix in comments, Getfiles-->GetFiles 2016-12-05 12:49:21 +08:00
5af26446ec Merge pull request #2299 from amrfaissal/fix-2294
Fix xml.GetSection() function which causes a panic
2016-11-30 14:25:14 +08:00
39d40ba8fa This fixes #2294 2016-11-29 14:55:57 +01:00
5bc3e30653 Added ToString method which converts values of any type to string 2016-11-29 14:55:56 +01:00
34e2b26b99 resolves #2291, introduces AndNotCond/OrNotCond to orm.Condition 2016-11-28 09:49:06 +01:00
24015e9ace Merge pull request #2285 from cat2neat/fix-bodyclose
Fix http body may not be closed
2016-11-20 19:48:09 +08:00
9ff88f0b35 Fix http body may not be closed 2016-11-20 05:16:52 +00:00
27c59a8017 Merge pull request #2278 from mgenov/err_fix
beego/session: return proper error when session is not found
2016-11-13 16:03:55 +08:00
a74ebaa1eb beego/session: return proper error when session is not found
Parent errs was returned instead of err which is returned from the last
statement.
2016-11-13 10:01:29 +02:00
b5c29d6143 Fix #2263
Update db_mysql.go instead of db.go, in order to avoid affect other database.
2016-11-08 13:39:31 +08:00
0a822209c8 Fix :supervisor work dir 2016-11-08 11:14:48 +08:00
3baac14095 Merge pull request #2257 from xiaoqiang0/develop
swagger: add 'Default' for Parameter
2016-11-07 22:48:06 +08:00
ef3655877a swagger: add 'Default' for Parameter 2016-11-03 22:59:23 +08:00
5a8c40710c Merge pull request #2228 from Hepri/develop
Rework getFlatParams for time.Time
2016-10-30 10:48:49 +08:00
b635af5a8c Merge pull request #2248 from smacker/RouterPattern-in-ctx
Add RouterPattern to context.Input
2016-10-30 10:48:15 +08:00
683e6856ef Add RouterPattern to context.Input
Right now beego adds this param only in dev mode, but I noticed that it's very useful to have in prod environment to.
My current use case - filter that sends logs in newrelic. Pattern there will help a lot to generate correct transaction name.
2016-10-28 10:44:16 +07:00
8beefc8bfd Fixed bug when all "time.Time" params in raw sql queries formatted as time 2016-10-17 21:51:31 +05:00
e430de3307 Merge pull request #2223 from tailnode/develop
修复windows上app.conf中include其他配置文件时找不到文件的BUG
2016-10-14 21:11:25 +08:00
2b442e842e fix path issue in windows 2016-10-14 16:52:03 +08:00
41633900da Merge pull request #2218 from WatchtowerSecurity/NameFix
Name fix
2016-10-13 21:24:11 +08:00
aaf6e775d6 Merge pull request #2216 from WatchtowerSecurity/httponlyfix
HTTPOnly Configurable
2016-10-13 21:19:28 +08:00
2f6fc3f62b Merge pull request #2213 from axyu/develop
fix log func call depth bug
2016-10-13 21:18:54 +08:00
84310b1652 Merge pull request #2205 from jirfag/master
add GetUint(8|16|32|64) to controller
2016-10-13 21:17:54 +08:00
5ceac1dd04 string convert int fail use math/big fix #756 2016-10-12 15:04:31 +08:00
51b31c6cb0 Changed the name to match. 2016-10-11 11:06:52 -05:00
5488a5bbd7 Forgot to fix it here 2016-10-11 11:06:22 -05:00
33f7f46670 Updated the name 2016-10-11 10:49:19 -05:00
3c05eafbc4 HTTP Only Configurable 2016-10-10 09:50:34 -05:00
dfa9e03980 fix log func call depth bug 2016-10-09 15:19:21 +08:00
53e996d4c3 Merge pull request #2211 from ihippik/patch-2
Default values
2016-10-08 17:52:07 +08:00
b151a9616e Default values 2016-10-08 11:28:47 +03:00
1effb6ce30 add GetUint(8|16|32|64) to controller 2016-10-02 07:42:06 +00:00
0be05eb47c policies implementation 2016-09-28 21:21:07 +03:00
1090ca0154 Merge pull request #2190 from szyhf/develop
fix to advice in #2187
2016-09-28 20:17:41 +08:00
a328584238 Merge pull request #2193 from LyricTian/develop
httplib add CheckRedirect
2016-09-28 20:16:48 +08:00
f19ad3fdd3 httplib add CheckRedirect 2016-09-28 18:04:51 +08:00
836be7ab9a fix to advice in #2187
Clear BConfig.Log.Outputs's default "console" while user has set "LogOutputs" in config file.
2016-09-28 16:20:41 +08:00
bba04dd864 Merge pull request #2184 from rahal/master
Emailer : Should use config Username only if no From is provided.
2016-09-28 07:56:12 +08:00
9499b3eb90 Emailer : Should use config Username only if no From is provided.
Should fix the case where Username is not an email.
2016-09-27 16:21:41 +01:00
9f6bbe3c51 add foundation link 2016-09-23 14:16:16 +08:00
2d87d4feaf Merge branch 'master' into develop 2016-09-22 23:18:45 +08:00
15a45ccc7b change to 1.7.1 2016-09-22 23:18:22 +08:00
e0c59fcf0b add more comments 2016-09-22 23:17:41 +08:00
083f697c59 Merge pull request #2173 from axyu/develop
fix a spelling mistake
2016-09-21 19:45:46 +08:00
a5a6546b91 fix a spelling mistake 2016-09-21 19:33:12 +08:00
9cafbf6a21 Merge pull request #2170 from ysqi/develop
Support load app config before test Beego
2016-09-19 20:55:20 +08:00
faba0d7273 Support load app config before test Beego 2016-09-19 18:38:56 +08:00
c3116d3601 Merge branch 'astaxie/develop' into develop 2016-09-19 18:16:47 +08:00
868e14b8ba fix #2017 2016-09-15 20:04:45 +08:00
421bf97b84 Support custome recover func fix #2004 2016-09-15 12:16:24 +08:00
c16507607c fix #2161 2016-09-15 11:11:34 +08:00
2b7dd85b92 access log add client request ip 2016-09-15 10:58:46 +08:00
a58115fed2 orm log delete repetition time 2016-09-15 10:54:21 +08:00
f9b5b0f551 Merge pull request #2162 from sergeylanzman/develop
improve Swagger
2016-09-15 08:56:27 +08:00
e53c147129 improve Swagger
1. Add yaml
2. Fix typo scurity => security
3. Make license optional
2016-09-15 00:15:02 +03:00
da0e6e790d Update swagger.go 2016-09-14 23:36:38 +03:00
58ffc6f5f8 fix #1877 2016-09-13 22:43:40 +08:00
d5fb74aa94 Merge pull request #2158 from simpleelegant/develop
Add support "SELECT FOR UPDATE" to orm. Resolve issue #2157
2016-09-12 21:48:14 +08:00
11247d41a7 Add support "SELECT FOR UPDATE" to orm. Resolve issue #2157 2016-09-12 20:07:30 +00:00
5b21c7cd71 fix #1802 2016-09-12 21:13:21 +08:00
dd0f05b1f1 fix the method color 2016-09-11 22:00:14 +08:00
a32241e7d3 fix #2142 2016-09-11 21:27:27 +08:00
0ef357ebd7 session:output error 2016-09-11 21:02:11 +08:00
32dd976620 Merge pull request #2146 from philchia/develop
Fix the typo
2016-09-08 17:42:10 +08:00
fcd8a2024e Add jianliao and slack log adapter 2016-09-08 17:21:11 +08:00
30661472c8 Fix the typo 2016-09-07 13:33:11 +08:00
6ced26660e Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-09-06 23:05:54 +08:00
7d6c45d4c9 add RegisterModelWithSuffix #2140 2016-09-06 23:05:41 +08:00
98740fddac Merge pull request #2138 from kbynd/patch-1
RequestURI captures the signature field as well.
2016-09-04 16:52:59 +08:00
6d3042f5e5 RequestURI captures the signature field as well.
This in turn results is failure of signature based validation. So what is need is only "/api/resource/action". which is given by ctx.Input.URL()
2016-09-04 11:36:17 +05:30
8b9d6eee1a Merge pull request #2132 from Zaaksam/master
beego.ParseForm() improvement
2016-09-02 16:23:14 +08:00
11ef5929aa update TestParseForm 2016-09-02 16:08:04 +08:00
c697b98006 enhancement 2016-09-01 23:28:34 +08:00
7c2e563879 beego.ParseForm() improvement 2016-09-01 15:04:57 +08:00
56aa224a6e simplfy the code 2016-08-31 22:47:31 +08:00
8c37a07adb optimize the ORM 2016-08-31 00:07:19 +08:00
161c061376 fix cache/memcache test 2016-08-30 23:24:30 +08:00
aa091cea42 improvement the error if use &&Struct 2016-08-30 22:02:11 +08:00
7df74c0a30 fix #1521 2016-08-30 21:24:56 +08:00
1e1e900278 fix #2126 2016-08-30 21:00:27 +08:00
fb2343567b fix #2125 2016-08-30 20:40:46 +08:00
3f67c62dd8 revert the snakeString 2016-08-30 00:15:02 +08:00
bb860d2752 Merge pull request #2124 from astaxie/revert-2071-issue_accept_encoding
Revert "route variables should not have underline"
2016-08-29 13:42:53 +08:00
f280dab880 Revert "route variables should not have underline" 2016-08-29 13:42:40 +08:00
7283aead42 Merge pull request #2116 from raphael10241024/self
fix#2039 & test
2016-08-24 23:15:53 +08:00
0ad4038d9f fix#2039 & test 2016-08-24 16:04:22 +08:00
227678c2ef Set SetLogFuncCallDepth default to 4 2016-08-23 23:48:47 +08:00
c611da2e3c Merge pull request #2112 from lday0321/master
log output format improvement
2016-08-23 23:18:10 +08:00
00e986cd3b log output format improvement
move log level info ahead to filename info, better readability
2016-08-23 16:16:57 +08:00
bed907653e Merge pull request #2102 from tnextday/develop
update swagger ParameterItems
2016-08-22 11:42:22 +08:00
7253ff2f8c update schema define 2016-08-20 15:03:41 +08:00
715c2c4312 Merge commit 'efbde1ee77517486eac03e814e01d724ddad18e6' into develop 2016-08-20 11:22:17 +08:00
9224cd3ef7 add ParameterItems in Parameter 2016-08-20 11:22:03 +08:00
efbde1ee77 add *Item into Schema 2016-08-19 23:52:19 +08:00
8b525b1aa5 fix #1656 2016-08-19 00:31:46 +08:00
86b3162aff fix #1695 update docs 2016-08-19 00:11:19 +08:00
3c016a0b2d Merge pull request #2100 from tnextday/develop
update swagger define
2016-08-18 23:29:06 +08:00
ffd748bf75 update swagger 2016-08-18 22:26:15 +08:00
1c54ff27c4 update swagger define 2016-08-18 21:24:54 +08:00
7760d24761 fix the typo 2016-08-17 23:52:34 +08:00
3672f96a9d fix the typo 2016-08-17 22:56:21 +08:00
68311b286e gofmt -s -w . 2016-08-17 22:49:30 +08:00
bed1d9bd27 update the performance 2016-08-17 22:33:36 +08:00
44a57e86dd fix #2090 2016-08-17 22:05:54 +08:00
3362f83662 change to v1.7.0 2016-08-16 23:54:52 +08:00
7813cb5783 Merge pull request #2096 from Maxgis/feature_session
session.NewManager second params shoube be a object not a string
2016-08-16 23:51:35 +08:00
ef0d3d80dc set session.managerconfig public 2016-08-13 21:07:27 +08:00
47b238728d Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-08-13 14:44:22 +08:00
1b4f30e11e update swagger 2016-08-13 14:43:56 +08:00
61c9387edd Merge pull request #2085 from danielscottt/reset-params
adds ability to reset params after a filter runs
2016-08-09 07:24:08 +08:00
957db1362f update swagger definistion 2016-08-08 16:45:11 +08:00
0e786fa4af adds ability to reset params after a filter runs
When a filter is run _after_ the router completes, it's input params,
such as `":splat"` will have been overwritten by the filter's router pass.
This commit adds the ability to tell the router to revert to the previous input
params after running a filter.
2016-08-07 07:44:30 -07:00
01c3812520 Merge pull request #2086 from Maxgis/issue_accept_encoding
Refactoring
2016-08-07 16:25:51 +08:00
ce6f19871c Refactoring 2016-08-06 21:13:58 +08:00
74778bb9d4 Merge pull request #1900 from redfoxli/patch-1
close socket when http client request over
2016-08-02 10:01:53 +08:00
7b542e612f Merge pull request #1964 from qAison/master
fix fk field null value
2016-08-02 10:00:24 +08:00
3ca68f9e30 Merge pull request #1976 from ysqi/develop
Fxied bug and Optimized code
2016-08-02 09:58:58 +08:00
1a52a34544 Merge pull request #2003 from GuyCheung/develop
add os.Chmod when create log file
2016-08-02 09:57:51 +08:00
86528c7b3c Merge pull request #2030 from saturn4er/feature/add_template_prefix_field
Add template prefix field to controller
2016-08-02 09:54:01 +08:00
ce6d673933 Merge pull request #2045 from Maxgis/master
avoid  error when the  callback function not exisit
2016-08-02 09:50:52 +08:00
c2aeab78aa Merge pull request #2053 from fudali113/develop
orm insert or update
2016-08-02 09:40:43 +08:00
0cad8207ec Merge pull request #2071 from Maxgis/issue_accept_encoding
route variables should not have underline
2016-08-01 14:28:25 +08:00
6f0a985755 update test 2016-07-30 23:14:29 +08:00
15c048d6ca update test 2016-07-30 22:07:35 +08:00
d5c339530a remove debug 2016-07-30 22:05:59 +08:00
b89bfe76d0 update route variables should not have underline 2016-07-30 21:57:23 +08:00
125030800b Merge pull request #1997 from amrfaissal/newfeature-enhanced-logs
Enhanced logging during DEV mode
2016-07-29 21:37:22 +08:00
e4fe54f6cd Merge pull request #2067 from Maxgis/issue_accept_encoding
reflection
2016-07-29 09:59:59 +08:00
d85293b7c0 Fixed bug and added more tests 2016-07-28 11:37:28 +02:00
5d1e60b468 reflection 2016-07-28 11:56:55 +08:00
2b867f8152 Removed external dependency 2016-07-27 17:42:28 +02:00
909afa9352 Merge pull request #2065 from Maxgis/issue_accept_encoding
remove not support encoding
2016-07-27 14:13:13 +08:00
d08e3d1b11 Merge pull request #2064 from Maxgis/feature_static
redirect path should add  query params
2016-07-27 12:55:21 +08:00
5485e1334f remove not support encoding 2016-07-27 09:31:53 +08:00
4b3ed53158 redirect should add query params 2016-07-26 19:54:10 +08:00
cacf6cde19 update db.go 2016-07-26 14:27:22 +08:00
4e10100575 update orm_test 2016-07-26 12:44:16 +08:00
f471ee9025 update orm_test 2016-07-26 12:19:06 +08:00
182a21172f Optimize the code logic 2016-07-26 11:15:59 +08:00
02330c6085 Merge pull request #2062 from Maxgis/feature_static
减少没有必要的代码以及静态前缀前面有/
2016-07-25 22:19:38 +08:00
e951c555e4 Merge branch 'astaxie-develop' into feature_static 2016-07-24 18:01:49 +08:00
6a4ebc67ac merge 2016-07-24 18:01:19 +08:00
33ef34b95d 减少没有必要的代码以及静态前缀前面有/ 2016-07-24 15:29:34 +08:00
bf17558d06 update “modification hardcode 2 2016-07-22 12:25:30 +08:00
e0e888ab8f update “modification hardcode 2016-07-22 12:10:37 +08:00
3583ad8cc0 update annotation 2016-07-21 15:49:55 +08:00
e2316c4b9e update 2016-07-20 17:28:26 +08:00
6d1b203bca update 2016-07-20 16:52:14 +08:00
50c5df32b1 update 2016-07-20 16:26:02 +08:00
530c32017c update 2016-07-20 15:33:30 +08:00
ec521ad166 update 2016-07-20 15:13:18 +08:00
4b8ecced83 orm insert or update 2016-07-20 14:37:05 +08:00
d11823548b Merge pull request #2050 from simpleton/bug/original_scheme
fix(context): retrieve scheme from X-Forwarded-Proto when it isn't none
2016-07-19 11:13:14 +08:00
ee26279311 fix(context): retrieve scheme from X-Forwarded-Proto when it isn't none 2016-07-19 00:36:51 +08:00
8099a81b7a avoid error when the callback function not exisit 2016-07-15 19:13:35 +08:00
0943ef9e74 Add TplPrefix to TplName also. 2016-07-14 11:48:49 +03:00
a2e63a3820 Merge pull request #1993 from NerdsvilleCEO/develop
Add meta fields with required flag on RenderForm
2016-07-14 10:47:21 +08:00
a08e937cf0 Merge pull request #2032 from ShevYan/make-go-vet-pass
use keyed fields to pass go vet
2016-07-14 10:38:05 +08:00
9ab5f6d808 use keyed fields to pass go vet 2016-07-06 12:53:47 +08:00
fee06a23bd Add template prefix field to controller 2016-07-03 14:44:11 +03:00
e0393b721c Change meta to required, and refactor a bit to cover edge cases 2016-06-30 10:32:53 -07:00
84b6bef7d0 Required field useful for not only input 2016-06-28 16:39:09 -07:00
8917fe44a9 Add test functions 2016-06-28 16:31:45 -07:00
21c7821692 Add test function 2016-06-28 16:24:32 -07:00
f9f92b4f61 Merge meta tag into parseFormField 2016-06-28 15:19:58 -07:00
c893b3472c added dep to .travis.yml 2016-06-24 15:51:59 +02:00
479dfdbd40 added support for Windows terminals 2016-06-24 15:38:18 +02:00
1f68e5a705 Merge pull request #2006 from victorpopkov/develop
Add support for time.Time pointer in struct types
2016-06-24 12:33:37 +08:00
415b9cf310 add support for time.Time pointer in struct types
Allow to use pointer *time.Time as a type in combination with orm tags in struct. This enables to treat them as "empty" in JSON marshaling/unmarshaling when using 'json:"null,omitempty'.
2016-06-22 16:57:05 +03:00
ed474b517d Merge pull request #1979 from ysqi/ormfix
ignore case of tag and fixed bug for columName
2016-06-22 12:00:37 +08:00
9572fdcf9a update error on type of w.Perm; change unit test perm value 2016-06-22 09:57:16 +08:00
cb3f240f44 add os.Chmod when create log file 2016-06-21 15:52:31 +08:00
844a3b0ffd removed unused import 2016-06-17 17:47:12 +02:00
448be6e58c added compatibility for go1.4 2016-06-17 17:39:32 +02:00
2bd743fcff Enhanced logging during DEV mode 2016-06-17 15:56:52 +02:00
0d3a806c23 Add meta fields with required flag 2016-06-15 17:17:50 -07:00
2c1cea08dd New func to find router info for context 2016-06-05 14:03:20 +08:00
3f016840db fixed test error 2016-06-04 10:41:55 +08:00
d528fafd43 ignore case of tag and fixed bug for columName 2016-06-03 22:06:43 +08:00
b7e3402995 Sport Error exeception for outside 2016-06-01 21:30:04 +08:00
b807362c39 Reset 2016-06-01 20:33:10 +08:00
d9b05e6b3f Print complete URL after running 2016-06-01 20:18:11 +08:00
e9f967102c Fixed parese ini file with empty space line 2016-06-01 19:58:35 +08:00
2e0bcf611c go fmt 2016-06-01 19:57:08 +08:00
2ebf3cd450 Merge branch 'astaxie/develop' into develop 2016-06-01 19:54:35 +08:00
1fe2226c11 Merge pull request #1968 from wy65701436/develop
modify the error log for registerModel.
2016-05-30 10:41:46 +08:00
d4d7621942 modify the error log for registerModel to tell user the default hard code PK is 'id'. 2016-05-27 02:03:58 -07:00
761b6c129c count func add support group by 2016-05-27 14:34:45 +08:00
8f0749ddee fix fk field null value 2016-05-27 13:53:28 +08:00
7b051e7ad1 Merge pull request #1940 from MachineShop-IOT/develop
More flexible support for template engines
2016-05-24 11:54:39 +08:00
24b8870637 move paren to new line 2016-05-23 21:43:18 -06:00
cef91db28e Merge pull request #1956 from gitchs/master
Ctx.Redirect patch
2016-05-23 13:50:59 +08:00
2165fb6e67 Merge pull request #1938 from wincss/develop
fix #1936
2016-05-22 21:29:32 +08:00
05e929ed8c Merge pull request #1948 from nullne/develop
fix bug with file permission in log module
2016-05-22 21:25:17 +08:00
f32392e956 net/http will do it better 2016-05-21 15:19:21 +08:00
e21b425957 Merge pull request #1953 from lcbluestorm/master
add ssdb session provider
2016-05-20 22:53:23 +08:00
e77a591a6c delete test file 2016-05-20 17:25:22 +08:00
4890dd708c clear code 2016-05-20 10:27:18 +08:00
6234b50111 test done 2016-05-19 21:00:04 +08:00
2c12383263 remove attribute perm to make it more brief 2016-05-17 10:29:05 +08:00
e50f4f5631 complete sess_ssdb.go 2016-05-15 12:15:40 +08:00
d679a4b865 fix bug with file permission in log module 2016-05-14 10:54:09 +08:00
153d76e200 More flexible support for template engines 2016-05-10 22:54:33 -06:00
0e4b9563ae add test file 2016-05-10 20:08:15 +08:00
27be1e7ca3 add ssdb-session interface 2016-05-10 19:56:45 +08:00
a4d4b8de77 fix #1936 2016-05-10 17:45:06 +08:00
dae2a36eb5 Merge pull request #1924 from ysqi/develop
implement some features
2016-05-06 13:58:29 +08:00
7ceff43db6 Fixed error in window os 2016-05-06 13:26:48 +08:00
85a8c5c4f4 Merge pull request #1927 from JessonChan/log_daily_rotate
file rotate by day
2016-05-06 12:55:21 +08:00
b28581a463 make daily rotate 2016-05-06 12:11:14 +08:00
fa8d94fa69 file rotate by day test 2016-05-06 12:09:00 +08:00
3c8ed9adfc Merge branch 'astaxie/develop' into develop
# Conflicts:
#	parser.go
2016-05-05 19:30:31 +08:00
8210fd12d1 Fixed router fileName error in window 2016-05-05 19:28:09 +08:00
77ff15ee33 Implement Error interface for validation error 2016-05-05 19:26:03 +08:00
4d8e1f93ff Merge pull request #1909 from albertma/master
Start timer task Multiple times
2016-04-29 11:34:52 +08:00
e607be6fa6 gofmt the code 2016-04-29 10:28:10 +08:00
73f499948a Merge pull request #1906 from Maxgis/issue_redundancy
remove redundancy code and add port confict tip
2016-04-28 09:59:47 +08:00
a7452388d9 Merge pull request #1912 from ysqi/issue02
Fixed some bug
2016-04-28 09:44:08 +08:00
2a2b433e19 go fmt 2016-04-27 23:57:36 +08:00
272271f588 Change comment router file info 2016-04-27 23:57:22 +08:00
fa7416452e Change set test mode way 2016-04-27 22:26:32 +08:00
245664010c Go Vet 2016-04-27 22:18:22 +08:00
9e17f518b8 Fixed print format error info 2016-04-27 22:17:53 +08:00
830985b90b QueryEscape Download File Name 2016-04-27 22:05:31 +08:00
a271d67ba4 1.fix blank issue 2016-04-26 18:13:52 +08:00
710c7c79d4 1.fix start task twice issue 2016-04-26 18:11:49 +08:00
5402c753fb remove redundancy code and add port confict tip 2016-04-26 10:16:53 +08:00
520a417cca Merge pull request #1874 from Maxgis/master
change limit 1000 to 1,reduce the amount the data
2016-04-26 09:56:44 +08:00
56dc9bf622 add return ErrMultiRows 2016-04-25 15:51:12 +08:00
b36afadbdc close socket when http client request over
To avoid a large number of  TIME_WAIT in server which http client talk with
2016-04-22 13:54:55 +08:00
e89f562396 Merge pull request #1897 from yuyongsheng/develop
add/get session id into/from http header, check the session name in http header
2016-04-21 13:04:28 +08:00
5aa085bf41 1. remove the invalid comments.
2. allow the user to config "Enable" store/get sessionId into/from http header
3. allow the user to config "Enable" get sessionId from Url query
4. when enable sessionId in http header, check the sessionName format as CanonicalMIMRHeaderKey, then panic if not.
2016-04-21 09:57:44 +08:00
70f3f6b8b1 Merge pull request #1883 from JessonChan/config_improve
Config improve
2016-04-20 13:19:47 +08:00
86e18bf6f9 Merge pull request #1882 from miraclesu/fix/orm_multi_insert
orm: fix multi insert panic
2016-04-20 13:06:47 +08:00
14159eaa7e Merge pull request #1891 from gitchs/develop
fix spell error
2016-04-20 09:49:11 +08:00
df27c96102 fix spell error 2016-04-18 19:37:38 +08:00
5ac254bf61 ut bug fixed 2016-04-18 19:18:46 +08:00
423f2dad35 list the config to map 2016-04-18 19:16:39 +08:00
203ab3eba8 ut fix 2016-04-18 18:41:40 +08:00
0c32255d14 config test 2016-04-18 17:45:39 +08:00
9ce6dc4cdf remove test ; because rows are returned in an unspecified order 2016-04-13 21:04:46 +08:00
903e21bef2 orm: add test case for InsertMulti 2016-04-13 20:22:27 +08:00
3a3f70027c orm: fix panic multi insert when slice lenght is 1 & the value is pointer 2016-04-13 20:14:02 +08:00
4cd2408248 log to Stderr 2016-04-13 19:41:07 +08:00
cb0c006cfa add session config 2016-04-13 19:37:55 +08:00
ce4fc7bfcd simplify the value assign 2016-04-13 17:51:54 +08:00
81c6c898cf remove orm one function thorw ErrMultiRows error 2016-04-13 10:36:12 +08:00
002dcaab23 Merge pull request #1880 from JessonChan/log_rotate_fix
Log rotate fix
2016-04-13 09:54:41 +08:00
abaa1bbcac file rotate file test 2016-04-13 09:05:16 +08:00
314a447d57 Merge pull request #1879 from miraclesu/feature/orm_text
orm: use `text` as postgres default type
2016-04-12 23:19:22 +08:00
9679f5e22a reduce the data transmission 2016-04-12 21:28:29 +08:00
5185816942 orm: use text as postgres default type 2016-04-12 21:19:43 +08:00
22617aeb13 file rotate name fixed 2016-04-12 15:05:35 +08:00
9c400778d3 Merge pull request #1863 from JessonChan/xsrf_fix
Xsrf fix
2016-04-12 14:26:20 +08:00
f6ad2cf848 Merge pull request #1875 from miraclesu/feature/orm_json
orm: add json & jsonb type support
2016-04-12 14:25:54 +08:00
7906b18d89 Merge pull request #1864 from yoki123/patch-2
Update README.md
2016-04-12 12:02:04 +08:00
99f1e6c8b5 orm: fix golint 2016-04-12 11:00:31 +08:00
e95bef1331 orm: add test case for json & jsonb type support 2016-04-12 11:00:31 +08:00
657744efb1 orm: add json & jsonb type support 2016-04-12 11:00:31 +08:00
6da765c465 Using a different PostgreSQL Version 2016-04-11 23:12:35 +08:00
1cac38b664 show postgres versionn 2016-04-11 21:19:10 +08:00
ba3a1f8457 update go vet 2016-04-11 13:15:14 +08:00
d7f41ccd0c update vet 2016-04-11 12:51:44 +08:00
881d010c01 upgrade swagger from 1.2 to 2.0 2016-04-11 11:56:43 +08:00
553078d956 change limit 1000 to 1,reduce the amount the data 2016-04-11 09:02:22 +05:30
528f273e58 Update README.md
fix url
2016-04-08 14:28:45 +08:00
53d680a493 rand func modify 2016-04-08 14:24:23 +08:00
ed0e6419f0 context xsrf test 2016-04-08 14:07:39 +08:00
a99c0d4025 context xsrf test 2016-04-08 14:04:25 +08:00
301dcfb626 context xsrf bug fixed 2016-04-08 14:04:10 +08:00
6362dc397a Merge pull request #1856 from b055/develop
added functionality for column type time
2016-04-06 09:25:46 +08:00
813f47fd41 gofmt test files 2016-04-05 15:38:42 +08:00
933ac0f369 Merge pull request #1858 from ysqi/issue
fix the issue #1850,the source of the problem is PR #1805
2016-04-05 09:06:14 +08:00
885d45db05 fix the issue #1850,the source of the problem is PR #1805 2016-04-04 21:32:43 +08:00
d49c7f96cb added functionality for column type time
updated the model_fields to cater for the time field type
2016-04-03 16:58:19 +02:00
ebdf4412b3 Merge pull request #1848 from JessonChan/template_fix
make template execution be expected
2016-04-01 21:03:39 +08:00
8ec6dd93cf make template execution be expected 2016-04-01 18:10:00 +08:00
fe4fa6a095 Merge pull request #1636 from ysqi/environmentVar
Support get environment variables in config
2016-04-01 13:50:38 +08:00
ccc84dd8eb Merge pull request #1762 from saturn4er/htmlEngines
Implemented possibility to add custom template engines
2016-03-30 16:43:39 +08:00
734bbb3337 remove some space 2016-03-30 15:48:38 +08:00
caa404cec1 Merge pull request #1840 from youngsterxyf/develop
To support `go run`
2016-03-30 15:46:47 +08:00
52fbab329d Merge pull request #1844 from mishudark/master
delete not used variable (status int) in output.go functions
2016-03-30 15:44:32 +08:00
8ce9f69b4d Merge pull request #1843 from JessonChan/beelog_bug_fix
Beelog bug fix
2016-03-30 15:44:20 +08:00
96a5d09ef0 add format header test 2016-03-30 15:13:01 +08:00
814b673e3c add a comment to the future bug 2016-03-30 14:51:46 +08:00
99436a75b1 format time header 5% faster than before 2016-03-30 14:31:28 +08:00
8e82ed319b beelog bug fixed 2016-03-30 14:31:16 +08:00
eae2147735 chore(output.go): delete not used variable (status int) in check status functions 2016-03-29 23:28:53 -06:00
e281b6e82a improve 2016-03-30 10:49:39 +08:00
adaa4ab929 Fix index out of range if there is no file extension 2016-03-29 17:15:43 +03:00
7e65338c87 Change key format
key format : ${ENV_PART||defaultValue} or  ${ENV_PART}
2016-03-29 21:47:33 +08:00
5bd7d8c43f Merge branch 'astaxie/develop' into environmentVar 2016-03-29 20:55:29 +08:00
561e7115f3 To support go run 2016-03-29 18:16:38 +08:00
220cf91180 Merge pull request #1837 from JessonChan/develop
add function of beego/logs
2016-03-29 11:37:09 +08:00
cbd6f31b66 Merge pull request #1839 from JessonChan/log_rotate_fix
file rotate bug
2016-03-29 11:35:44 +08:00
221306fff4 file rotate bug 2016-03-29 10:05:56 +08:00
f05bb2ecd3 add function of beego/logs 2016-03-28 15:18:51 +08:00
699de2ae75 Merge pull request #1826 from miraclesu/feature/orm_auto
orm: support insert a specified value to auto field
2016-03-28 12:04:31 +08:00
fb77464d69 golink: map range only key stlye 2016-03-27 15:07:51 +08:00
1794c52d65 orm: fix postgres sequence value 2016-03-27 15:06:57 +08:00
3ca44071e6 orm: insert specified values for insertMulti 2016-03-26 21:51:05 +08:00
e0a36fb61e Merge branch 'develop' into feature/orm_auto 2016-03-26 21:16:52 +08:00
85a9b05495 Merge pull request #1833 from youngsterxyf/develop
in `session` package, add some helpful tools to help subpackage logging information
2016-03-25 21:15:23 +08:00
70108131e6 Merge pull request #1832 from JessonChan/log_enhancement
Log enhancement
2016-03-25 21:12:06 +08:00
45f2390128 logger changed 2016-03-25 15:13:28 +08:00
826f81f479 remove from init method 2016-03-25 15:04:52 +08:00
4dbbae61e0 Merge pull request #1828 from miraclesu/fix/orm_read_or_create
orm: fix painc when pk is uint on ReadOrCreate
2016-03-25 14:44:41 +08:00
e59271662c fix bee fix 2016-03-25 13:25:29 +08:00
fa4a231cd4 duration change to second 2016-03-25 11:46:19 +08:00
850dc59b6e should remove when 2.0 is released 2016-03-25 11:13:39 +08:00
6d0fe8c4f4 go fmt cache file 2016-03-25 11:05:20 +08:00
2db8c753fd bee fix 2016-03-25 10:56:15 +08:00
56860d1fea not just export a variable 2016-03-25 10:48:59 +08:00
94bde3a777 change to logs 2016-03-25 10:31:48 +08:00
3300db832b in session package, add a helpful variable SLogger to help subpackage logging information 2016-03-24 22:43:57 +08:00
52a0b657b7 for better performance 2016-03-24 20:27:00 +08:00
f02ff0420d no need to call Sprintf when no args 2016-03-24 20:22:42 +08:00
3e2ffa545f orm: fix postgres returning id error 2016-03-24 20:03:45 +08:00
06299fa47b makes console as default logger 2016-03-24 19:32:29 +08:00
d8bed89c44 set console as default logger 2016-03-24 19:15:14 +08:00
0814eefa62 refactor writeMsg function 2016-03-24 18:21:52 +08:00
8344a60552 add to upper case 2016-03-24 17:49:39 +08:00
0fb4a8af24 function change 2016-03-24 17:46:52 +08:00
a6c1377f91 change to 0 logger 2016-03-24 17:43:45 +08:00
cdfd830f65 rename log format 2016-03-24 17:43:16 +08:00
98dfecfd8a change beego log function to logs function 2016-03-24 17:39:29 +08:00
03840f3fe8 give each of the adapter a neme 2016-03-24 17:38:26 +08:00
2e6a23743b refactor logs package 2016-03-24 17:37:56 +08:00
2362ca00b5 Merge pull request #1827 from ysqi/issue
Check file before download
2016-03-24 13:33:44 +08:00
b7d1afbf86 Remote empty line 2016-03-24 08:35:42 +08:00
eaf38bb096 orm: add test case for uint pk read or create 2016-03-23 21:59:09 +08:00
3be6688cd1 orm: fix painc when pk is uint on ReadOrCreate 2016-03-23 21:57:57 +08:00
1eab11ca90 fixed #1815 check file before download 2016-03-23 21:27:28 +08:00
c4276d31c5 Merge branch 'astaxie/develop' into issue 2016-03-23 21:26:55 +08:00
8f70df6c7b orm: add test case for insert specified value to auto field 2016-03-23 20:28:22 +08:00
1786b16e61 orm: support insert a specified value to auto field 2016-03-23 20:16:18 +08:00
9f18813c2b Merge branch 'master' into develop 2016-03-23 17:05:50 +08:00
88c5dfa6ea update issue template 2016-03-23 17:05:40 +08:00
0a86926522 Merge branch 'master' into develop 2016-03-23 16:56:53 +08:00
b78de2b440 add ISSUE_TEMPLATE 2016-03-23 16:56:40 +08:00
6c0979c314 Merge pull request #1805 from JessonChan/abort_panic_bug
Abort panic bug
2016-03-23 10:22:32 +08:00
5858607f49 go fmt error_test.go 2016-03-22 18:32:14 +08:00
1a401af23b copyright 2016-03-22 18:28:44 +08:00
b2098266a3 add error test 2016-03-22 18:27:29 +08:00
3ac90df5fa Merge pull request #1794 from youngsterxyf/issue1789
fix issue1789: when testing, load config explicitly and forcibly
2016-03-22 17:21:57 +08:00
9e9671d8cd Merge pull request #1799 from JessonChan/router_develop
Router Filter Improve
2016-03-22 17:15:28 +08:00
d3b54c46e3 Merge pull request #1808 from JessonChan/gzip_improve
Gzip improve
2016-03-22 17:13:20 +08:00
7bad3d1c67 change the compress leve to [0~9] 2016-03-22 16:47:11 +08:00
4db78f243e change the function args of init gzip method 2016-03-22 16:42:42 +08:00
ba7a809de8 Merge pull request #1810 from miraclesu/fix/orm_miss_pk
orm: fix miss pk when pk is negative
2016-03-22 10:09:35 +08:00
630f77bca3 update travis 2016-03-21 11:18:38 +08:00
f2ed27cc8f make sure works for travis 2016-03-21 11:10:57 +08:00
959b9a5a58 config index out of range bug fixed 2016-03-21 09:32:41 +08:00
142f4c9f42 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-03-21 09:15:47 +08:00
33ae75b251 golint check only works on Go 1.5 2016-03-21 08:50:56 +08:00
84ae930c64 orm: Add test case for integer pk 2016-03-18 21:58:11 +08:00
99c0b1e338 Merge pull request #1803 from JessonChan/log_develop
fix rotate  read-write lock race
2016-03-18 15:43:46 +08:00
4caf044be2 getMethodOnly assign fixed 2016-03-18 15:18:00 +08:00
a3d4218d9d orm: fix miss pk when pk is negative 2016-03-17 21:41:35 +08:00
9f21928a90 some typo fixed 2016-03-17 20:07:24 +08:00
0b401481ef go fmt the comment 2016-03-17 19:59:48 +08:00
57eace07a7 comment update 2016-03-17 19:52:09 +08:00
35e34261ab gzip method support 2016-03-17 19:40:29 +08:00
5a9bff2000 init gzip level 2016-03-17 19:09:38 +08:00
48147f50d8 add some gzip future 2016-03-17 19:09:21 +08:00
0859ec570c refactor of error response and fix err code bug 2016-03-17 09:46:34 +08:00
443d71397c write error to response 2016-03-17 09:35:14 +08:00
ec35bd0c28 orm log header flag 2016-03-16 18:04:27 +08:00
2b1316c738 data race bug fixed 2016-03-16 18:04:07 +08:00
94599013fc url to lower case 2016-03-16 07:53:36 +08:00
565c4a4d59 make the code run more fast 2016-03-15 18:50:18 +08:00
34615ee8fc add router filter enable flag 2016-03-15 18:37:54 +08:00
c51bc86d3f goto bug fixed 2016-03-15 16:51:21 +08:00
8660a54fac make router fast 2016-03-15 11:49:23 +08:00
1b04571c0b test the env use GOPATH not GOROOT 2016-03-14 19:22:00 +08:00
9c7d95b071 go vet 2016-03-14 19:21:09 +08:00
c8bbfb75f0 Merge pull request #1782 from JessonChan/some_wip
BeeLogger can be the writer of  http server's log
2016-03-14 14:47:29 +08:00
549a39c478 fix issue1789: when testing, load config explicitly and forcibly 2016-03-14 11:26:26 +08:00
e4066d820d Merge pull request #1790 from miraclesu/feature/orm_inline_struct
orm: inline struct relate test case
2016-03-14 10:35:00 +08:00
cc2b5f5b62 Merge pull request #1792 from youngsterxyf/issue1787
fix issue#1787: if `/m` is a static path mapping to a static dir,and we set `beego.BConfig.WebConfig.DirectoryIndex = true`, then it should redirect to `/m/`
2016-03-14 10:33:47 +08:00
c92c3fc8b5 make the BeegoLogger a adapter of http server ErrorLog 2016-03-14 10:21:07 +08:00
9aa2e5b575 fix issue#1787: The cause is that if the url is /m,and we set beego.BConfig.WebConfig.DirectoryIndex = true, then it should redirect to /m/ 2016-03-13 21:39:26 +08:00
dcfcb2789e orm: inline struct relate test case 2016-03-13 21:04:39 +08:00
d90195061f fix #1783 2016-03-13 11:16:19 +08:00
474bdd2e6b Merge pull request #1785 from KilledKenny/pathError
Fixed infinite loop in ini config adapter
2016-03-12 21:11:04 +08:00
1642cbd420 Merge branch 'astaxie/develop' into develop 2016-03-12 14:51:24 +08:00
b2a06c5fa0 Update config suport environment variable logic 2016-03-12 14:32:39 +08:00
cfef97175e change import sort 2016-03-12 12:34:54 +08:00
8b0957cf2e Fixed infinite loop in ini config adapter
If parseFile recived a directory it would go into a infinit loop
2016-03-12 00:20:19 +01:00
88816348b9 window console can't output colorful 2016-03-11 15:29:52 +08:00
66423f6935 Fix formatting with gofmt
Rename BeeTemplateEngines->beeTemplateEngines.  Create templateHandler function type
Fix var name in comment BeeTemplatePreprocessors -> beeTemplatePreprocessors
Rename TemplateI -> TemplateRenderer
2016-03-11 08:40:54 +02:00
9872041f12 timeDur is used only when need 2016-03-11 14:14:58 +08:00
83fe43f331 gofmt -s -w 2016-03-11 13:00:58 +08:00
40b41cc121 fix the misspell99 2016-03-11 12:14:18 +08:00
1aeb3d9051 release 1.6.1 2016-03-11 11:35:24 +08:00
778a5a11ac Merge pull request #1781 from JessonChan/develop
duplicate adapter logger  bug fixed
2016-03-11 11:19:07 +08:00
4801099675 duplicate adapter logger bug fixed 2016-03-11 10:12:17 +08:00
420cd507b2 update output information 2016-03-11 10:07:44 +08:00
22196d7841 add mis function NSHandler 2016-03-11 09:21:13 +08:00
571f9b4b65 Merge pull request #1780 from goodloop/develop
fix static pattern match for leaf
2016-03-11 09:07:53 +08:00
1f0a65f0a2 fix the orm test 2016-03-10 22:21:21 +08:00
90e7d252a7 fix static pattern match for leaf 2016-03-10 22:16:41 +08:00
31f7524dae fix the golint travis 2016-03-10 21:47:50 +08:00
3a12e238cc support oracle 2016-03-10 21:23:13 +08:00
86c7f1db9e Merge branch 'astaxie/develop' into environmentVar
# Conflicts:
#	config/fake.go
#	config/xml/xml_test.go
#	config/yaml/yaml_test.go
2016-03-10 19:57:16 +08:00
f45b271b96 Merge pull request #1723 from miraclesu/feature/orm_inline_struct
orm: inline struct support
2016-03-10 14:31:44 +08:00
589616b303 Merge pull request #1768 from aolu11/master
fix json extra newline
2016-03-09 21:11:20 +08:00
65b13eddad Merge pull request #1719 from JessonChan/err_ctrler
multiple response.WriteHeader calls
2016-03-09 19:18:09 +08:00
686d2e834e Merge pull request #1765 from saturn4er/fix_layout_rebuild_in_dev
Add layout rebuilding on each request in dev mode
2016-03-09 19:02:46 +08:00
adbae18e8c Fix formatting with gofmt 2016-03-09 10:47:09 +02:00
f21cff0166 some typo fixed 2016-03-09 16:00:52 +08:00
3dd9020249 Merge remote-tracking branch 'remotes/upstream/develop' into err_ctrler 2016-03-09 15:59:13 +08:00
9a2696d216 accept asta's idea see the talk
https://github.com/astaxie/beego/pull/1719
2016-03-09 15:56:18 +08:00
64e0858d44 orm: add inline struct test case 2016-03-08 22:24:38 +08:00
d86ab2ed31 Merge pull request #1721 from JessonChan/log_enhancement
Log enhancement
2016-03-08 21:35:31 +08:00
b2f071395b rename files to mulitfile 2016-03-08 18:44:39 +08:00
54b5120a64 rename files to mulitfile 2016-03-08 18:43:09 +08:00
5e2384e95a fix json extra newline 2016-03-08 17:04:14 +08:00
adb41eb299 Merge pull request #1761 from lcbluestorm/develop
add ssdb cache adapter
2016-03-08 15:47:45 +08:00
bd04be4470 move time to the top 2016-03-08 14:44:37 +08:00
ef59a0ed63 fix travis.yml 2016-03-08 14:03:33 +08:00
14be252d2a fix travis.yml 2016-03-08 14:01:33 +08:00
5698b5dc92 Merge pull request #1709 from mlgd/develop
Fix cookies in accordance with the "net / http" and Flash usage
2016-03-08 13:53:43 +08:00
0a0fc351e7 fix ssdb_test 2016-03-08 12:59:19 +08:00
662bea352f modify travis 2016-03-08 12:45:54 +08:00
2f18b9103b Merge pull request #1679 from ysqi/emptybodyfix
fix #1669 and return IO error
2016-03-08 09:48:17 +08:00
2c5ef8ccc8 Add layout rebuilding on each request in dev mode 2016-03-07 23:24:52 +02:00
1ddb1ce2fe add ssdb travis 2016-03-07 15:50:13 +08:00
9ee9f81861 Add functions passing to template engine callback 2016-03-07 09:37:47 +02:00
9ddc2f5474 fix panic err 2016-03-07 15:00:03 +08:00
e29f4b57a3 fix travis.yml 2016-03-07 14:53:36 +08:00
10ddb06782 Implemented possibility to add custom template engines 2016-03-07 08:45:49 +02:00
0caadb9b66 rename vars 2016-03-07 14:45:45 +08:00
22e3900403 add .travis.yml 2016-03-07 14:34:40 +08:00
b39830dff3 add .travis.yml 2016-03-07 10:31:56 +08:00
be23c42674 Merge branches 'master' and 'develop' of lcbluestorm.github.com:lcbluestorm/beego into develop 2016-03-07 10:19:55 +08:00
90344a7b8f fix conflicts 2016-03-06 21:25:43 +08:00
920862884d Merge branch 'astaxie/develop' into emptybodyfix
# Conflicts:
#	config.go
2016-03-06 21:19:04 +08:00
48ec7f736e fix GetMulti bug 2016-03-06 14:46:13 +08:00
292d8f2c00 add ssdb cache adapter 2016-03-06 13:17:16 +08:00
f6f34306ee Merge pull request #1740 from ysqi/configer
Fixed #1735 Return nil if config value does not exist or is empty
2016-03-05 22:05:43 +08:00
a40c0dd156 Merge pull request #1750 from JessonChan/staticfile_map_race
static file map race bug fixed
2016-03-05 20:43:00 +08:00
795092bdd2 Merge pull request #1751 from FlamingTree/develop
Update phone regexp
2016-03-05 20:41:52 +08:00
524446c857 Merge pull request #1752 from JessonChan/ab_lock_race
fix template  read-write lock race
2016-03-05 20:40:14 +08:00
f5adec31c6 improve the template reader function 2016-03-04 14:49:16 +08:00
6747c55a81 remove unused cache 2016-03-04 12:01:04 +08:00
1f46c1d231 add template read lock when dev mode 2016-03-04 12:00:43 +08:00
8bd1be8e29 Update validators.go
增加178号段
2016-03-04 11:16:47 +08:00
226e54e0d8 static file map race bug fixed 2016-03-04 10:54:54 +08:00
3379a2b7ed remove file bug fixed
remove file by filename and file suffix
2016-03-04 10:43:57 +08:00
19d921d3f5 Return nil not empty []string{}
Return nil if config value does not exist or is empty
2016-03-03 20:03:23 +08:00
4b99e41880 Merge pull request #1688 from ysqi/configIssue
fixed handle config issue
2016-03-03 09:50:14 +08:00
8ff74e71cb Fixed #1735 Return empty []string
Need return empty []string  if config value is empty.

split `“”` ==> []string{}, Not []string{“”}
2016-03-02 22:44:20 +08:00
2a148473e9 Merge remote-tracking branch 'remotes/upstream/develop' into log_enhancement 2016-03-02 13:34:37 +08:00
b30ce768f8 Merge remote-tracking branch 'remotes/upstream/develop' into err_ctrler 2016-03-02 13:34:00 +08:00
70e63570f5 Merge pull request #1731 from math345/develop
fix bug: session id undecoded when destroy and sesssion memory provider push wrong
2016-03-02 13:26:57 +08:00
36e3160904 add go1.6.0 and remove 1.3.3 2016-03-01 21:41:44 +08:00
ca3c57fbc6 add a line of comment 2016-03-01 17:13:50 +08:00
387dd6ec0e add a line of comment 2016-03-01 17:12:21 +08:00
26cc040f9a daily log name dot fixed 2016-03-01 17:00:24 +08:00
d81a768802 change couchbase to beego/go-couchbase 2016-03-01 16:54:37 +08:00
f0dcaa7f84 remove couchbase dependence 2016-03-01 16:43:56 +08:00
9da4d1d847 Merge branch 'develop' into log_enhancement 2016-03-01 13:59:27 +08:00
a144f117a3 remove comment 2016-03-01 13:39:36 +08:00
477de9a3f3 fix bug: session id undecoded when destroy and sesssion memory provider push wrong 2016-03-01 10:51:47 +08:00
ffbb45e567 Revert "ignore parse include config file error"
This reverts commit 891016a0a2.
2016-02-27 20:18:59 +08:00
67fbafb380 Merge pull request #1680 from ysqi/fix-router-error
fix #1595
2016-02-26 16:17:53 +08:00
6eaa5537f5 Merge pull request #1652 from JessonChan/develop
colorful console and go fmt
2016-02-26 16:10:11 +08:00
62cc987620 Merge pull request #1639 from youngsterxyf/logger-flush-close
try to fix the little bug when calling Close or Flush in async mode
2016-02-26 16:04:29 +08:00
f0a41f978f Merge pull request #1727 from JessonChan/templates_bug_fix
lock the templates map when goroutie update the map
2016-02-26 15:56:47 +08:00
3da28535fe lock the templates map when goroutie update the map 2016-02-25 17:37:28 +08:00
85f55fcb41 orm: inline struct support 2016-02-24 18:46:14 +08:00
8c37e76503 the net/http should set header first,the set http status code and then write the content 2016-02-24 14:14:16 +08:00
76d69b6e51 prevent auto detect of content-type
https://golang.org/src/net/http/server.go#L1031
2016-02-24 10:34:20 +08:00
20301bc212 multiple response.WriteHeader calls 2016-02-24 10:31:44 +08:00
9119f766d2 Fix cookies in accordance with the "net / http" and Flash usage
Fixed issue of Flash cookies that are deleted before being read
Max-age parameter conform to "net/http" Cookie
2016-02-22 13:35:54 +01:00
891016a0a2 ignore parse include config file error 2016-02-14 18:55:42 +08:00
d5f07d65bb panic parse config error 2016-02-14 18:54:40 +08:00
9411063574 fix #1595 2016-02-12 14:45:45 +08:00
23860e6807 go fmt 2016-02-12 11:36:59 +08:00
d35c50a8e0 return write body error 2016-02-12 11:36:25 +08:00
810f6db8d2 fix #1669 write empty body panic error 2016-02-12 11:27:59 +08:00
36f69a04a9 remove interfaceToStr function to package config 2016-02-04 20:15:37 +08:00
1f716dda3e add test files and bug fixed 2016-02-03 17:54:58 +08:00
f8c4b3aa4c add files logger to separate different logs 2016-02-03 17:11:53 +08:00
51b1095e73 add files logger 2016-02-03 16:32:59 +08:00
68cc53e92b when rotate by date ,there's no num after log file 2016-02-03 15:43:15 +08:00
6caa3ecd91 when rotate by date ,there's no num after log file 2016-02-03 15:31:59 +08:00
304a5ccea0 comment fix 2016-02-03 15:06:53 +08:00
9806a43783 make more fast 2016-02-03 15:03:37 +08:00
a1cb000701 remove log package 2016-02-03 14:42:38 +08:00
2b23764ee0 Merge pull request #1657 from lei-cao/slack
Added slack
2016-02-03 08:58:24 +08:00
2301633d42 Added slack 2016-02-02 23:34:32 +08:00
2efe7c4c89 merge multi commit 2016-02-02 17:12:47 +08:00
c71ac7431d Merge branch 'develop' into logger-flush-close 2016-02-02 17:11:41 +08:00
360220161b remove useless var , name style fixed 2016-02-02 16:52:53 +08:00
5dec3d127c colorful console only the terminal supports 2016-02-02 16:37:09 +08:00
16b01c362a Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-02-02 12:45:01 +08:00
441f795a1a Merge pull request #1651 from thanhtranjs/develop
Add GroupBy to QuerySeter
2016-02-02 12:44:49 +08:00
4906b600e3 fix the static url with / problem 2016-02-02 12:43:58 +08:00
bb50383aa9 Add GroupBy to QuerySeter 2016-02-02 11:28:43 +07:00
631b4d36f9 Merge pull request #1647 from youngsterxyf/fix-issue1641
fix issue #1641
2016-02-02 09:23:12 +08:00
da38cbfe41 fix issue #1641 2016-02-01 22:40:34 +08:00
09193213a0 add travis hooks 2016-01-31 23:28:56 +08:00
0382146c60 fix the go vet for go tip 2016-01-29 13:11:11 +08:00
1bf52e8922 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-01-29 10:26:40 +08:00
5cd1ed8106 add test for tip 2016-01-29 00:01:04 +08:00
bd79972d85 Merge pull request #1638 from pjoe/log_console_nocolor
Add noColor option for console logger
2016-01-28 22:39:02 +08:00
ecab397073 try to fix the little bug when calling Close or Flush in async mode 2016-01-28 21:53:44 +08:00
a043432398 Change option name from noColor to color
Still same default behavior (with color)
2016-01-28 07:50:07 +01:00
1222c87be3 optimization code 2016-01-28 14:49:44 +08:00
7f888e3d18 Add noColor option for console logger
- Also added simple test
2016-01-27 19:20:58 +01:00
85c0fcd335 Merge pull request #1637 from pjoe/input_param_fix
Fix Context.Input.SetParam not overwriting existing value
2016-01-27 23:01:10 +08:00
f769016126 Merge pull request #1632 from youngsterxyf/config-logic
Config logic
2016-01-27 22:25:00 +08:00
453d744db9 Fix Context.Input.SetParam not overwriting existing value
- Also added tests for Context.Input.Param handling
2016-01-27 14:58:50 +01:00
484ca3a643 fixed test code error 2016-01-27 21:13:11 +08:00
cd31c816cc Config support get environment variable
get environment variable if config item  has prefix "$ENV_" .
e.g.
```ini
[demo]
password = $ENV_MyPWD
```
2016-01-27 20:46:30 +08:00
31ef4ae507 rename AppConfigPath, AppConfigProvider to appConfigPath, appConfigProvider, make public to private 2016-01-27 16:43:01 +08:00
ccce566ba7 accept @astaxie suggestion: change the sequence adapterName and configPath 2016-01-27 16:19:10 +08:00
e357f6846b accept @ysqi suggestion 2016-01-27 13:30:34 +08:00
321bcc606a fix bug of test case 2016-01-27 12:26:37 +08:00
e549d0fd9c move some code piece 2016-01-27 12:13:26 +08:00
c59a029ce7 Merge branch 'develop' into config-logic 2016-01-27 10:58:38 +08:00
4ce094a29a Merge branch 'master' into develop 2016-01-27 10:14:34 +08:00
fbb98fbe1f Merge pull request #1631 from yunkai/issue1
Fix regression caused by commit ad65479
2016-01-27 10:13:30 +08:00
20efd5236e fix bug 2016-01-27 00:42:07 +08:00
330b3b1931 enhancement code 2016-01-27 00:17:56 +08:00
d9e6250d08 fix config logic 2016-01-27 00:10:21 +08:00
e3810b599d Fix regression caused by commit ad65479
Commit ad65479 will cause "Method Not Allow" in preflight response
when enable CORS plugin.

The root cause is that CORS plugin didn't generate http output after applied
commit ad65479, so the value of `ctx.ResponseWriter.Started` will be keep
`false`, and then later filter chains will be go on to run when CORS filter
finished.

This path will both fix "Method Not Allow" and the original bug
"multiple response.WriteHeader calls".

Signed-off-by: Yunkai Zhang <qiushu.zyk@taobao.com>
2016-01-26 23:27:26 +08:00
e1f9491aed Merge pull request #1608 from ysqi/iniSaveErrorFix
Fixed #1607
2016-01-26 21:46:31 +08:00
6aeff53d8c Merge pull request #1625 from miraclesu/fix/mail_from
Fix utils mail some bugs
2016-01-26 21:42:21 +08:00
bf870eb9a2 mv mime.QEncoding.Encode logic to mail
it is named qEncode
2016-01-26 20:50:03 +08:00
f26d360ec9 Fix vet fail 2016-01-26 14:54:36 +08:00
f73eaf6393 Merge pull request #1626 from JessonChan/develop
log file name bug fixed
2016-01-26 13:42:47 +08:00
e11d150e8b replace \t with space 2016-01-26 09:35:39 +08:00
f2567bc114 some typo fixed 2016-01-26 09:29:04 +08:00
b5a07c6ba8 log file name bug fixed
this bug happens when daily rotate. ex,when it is 2016-01-22 23:59:59 and need a rotate,the file name should named with 2016-01-22 but named with 2016-01-23(next day)
2016-01-26 09:20:49 +08:00
01ccc75d6b Merge pull request #1615 from ysqi/routerErrorFix
Fixed #1586
2016-01-26 00:31:01 +08:00
b19f9bf88c Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-01-26 00:27:44 +08:00
6cc3d4470a Merge pull request #1616 from coseyo/path_patch
fix path issue #1613
2016-01-26 00:27:34 +08:00
61e9dc74c9 make sure the memcache testing success 2016-01-26 00:27:02 +08:00
8611862fd7 Merge pull request #1609 from youngsterxyf/fix-issue1566
fix issue #1566
2016-01-26 00:07:43 +08:00
d1481ea659 move assignment to init 2016-01-25 23:00:09 +08:00
5930f27da7 Fix mail Chinese subject garbled bug 2016-01-25 22:55:40 +08:00
4de91f675d show from when Config from is empty 2016-01-25 22:29:45 +08:00
15e9ba19c0 fix the range only used in Go 1.4 fix #1623 2016-01-25 21:39:44 +08:00
f8004b69ad fix the go vet 2016-01-25 21:33:57 +08:00
3dac344ff6 fix the vet url 2016-01-25 21:20:10 +08:00
e7d4452af0 add golint and go test 2016-01-25 21:13:56 +08:00
7e3ad5bcb0 fix #1585 2016-01-25 21:08:29 +08:00
87650ce8bc make golint happy 2016-01-25 20:57:41 +08:00
fdce4af9c8 fix #1619 2016-01-25 20:53:52 +08:00
bcac4bb8e3 accept @JessonChan suggestion 2016-01-25 20:53:25 +08:00
0e17e2a3d2 accept @JessonChan suggestion 2016-01-25 20:20:53 +08:00
a80feb00b8 Fix utils mail from field can't including Chinese bug 2016-01-25 18:15:08 +08:00
cf055c9db2 Merge branch 'astaxie/develop' into iniSaveErrorFix
# Conflicts:
#	config/ini_test.go
2016-01-24 11:37:43 +08:00
3d7354b9d2 import reset 2016-01-24 11:10:04 +08:00
09d3d89c6f fix test error again 2016-01-24 00:47:37 +08:00
3031bdd176 fix test error 2016-01-24 00:40:03 +08:00
4c1cfc1386 fix path issue 2016-01-24 00:18:16 +08:00
57d522a96a Merge pull request #1606 from ysqi/configWork
Support Parse Bool with more diffrent values
2016-01-23 23:03:03 +08:00
fd7473466b Merge pull request #1581 from hbejgel/patch-2
Checks if index is greater than the length of the wildcards. #1580
2016-01-23 23:01:22 +08:00
007af6224e Fixed #1586 2016-01-23 19:13:19 +08:00
cbc7f43e88 fix issue #1601 2016-01-23 17:12:46 +08:00
ecf24640fd fix issue #1566 2016-01-23 16:56:54 +08:00
51ae45a799 Fixed #1607 2016-01-23 14:53:52 +08:00
be544f963e Support Parse Bool with more diffrent values
ParseBool returns the boolean value represented by the string.
It accepts 1, 1.0, t, T, TRUE, true, True, YES, yes, Yes,Y, y, ON, on,
On,
 0, 0.0, f, F, FALSE, false, False, NO, no, No, N,n, OFF, off, Off.
Any other value returns an error.
2016-01-23 11:02:40 +08:00
af346e871b Merge pull request #1603 from coseyo/remote_develop
fix conf load bug
2016-01-22 20:34:46 +08:00
cb5fd49612 fix conf load bug 2016-01-22 18:03:02 +08:00
0f85c82a21 Merge pull request #1594 from nemtsevp/patch-2
Exceptions in controller methods
2016-01-21 14:57:02 +08:00
93b04e8a3b Exceptions in controller methods
Exceptions in methods names should be changed according to controller.go
2016-01-21 09:44:17 +03:00
07937dea9a Merge pull request #1588 from Kavin-Cao/master
template.go 的beegoTplFuncMap注释有误
2016-01-20 14:18:35 +08:00
5757e6548e template.go 的urlfor Func注释有误
template.go 的urlfor Func注释有误
2016-01-19 10:14:16 +08:00
b48f251043 Merge remote-tracking branch 'refs/remotes/astaxie/master' 2016-01-19 09:43:43 +08:00
35e340b937 Checks if index is greater than the length of the wildcards. #1580 2016-01-18 21:35:14 -02:00
befeac5b61 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-01-18 23:30:12 +08:00
23bb36d35c fix the issue #1573 2016-01-18 23:29:56 +08:00
4b52a38183 Merge pull request #1575 from youngsterxyf/develop
simplify the implementation of splitPath in tree.go
2016-01-18 16:33:23 +08:00
30e5634bdb simplify the implementation of splitPath in tree.go 2016-01-18 16:13:31 +08:00
fa8f6e5a53 session destroy 2016-01-18 16:11:27 +08:00
6e987bfdaf Merge branch 'develop' of https://github.com/astaxie/beego into develop 2016-01-18 15:28:18 +08:00
918b9e510f fix the add tempfunc 2016-01-18 15:27:33 +08:00
12e5584c01 Merge pull request #1574 from youngsterxyf/develop
DRY
2016-01-18 15:24:53 +08:00
ac3b013de7 DRY 2016-01-18 15:17:42 +08:00
089242eda0 memcache test mulit return map has no sequence 2016-01-18 00:36:05 +08:00
92d0b9ae95 golint the config.go 2016-01-18 00:22:31 +08:00
6f786e1dea golint config.go 2016-01-18 00:22:11 +08:00
eb0bc084ec make the code mode readable
golint all the files
2016-01-18 00:18:52 +08:00
f925bb9058 golint all the files 2016-01-18 00:18:21 +08:00
da36d1d0e7 fix the wrong io.Writer 2016-01-18 00:03:39 +08:00
48f19b4191 Merge pull request #1571 from astaxie/develop
beego 1.6.0 released
2016-01-17 23:58:34 +08:00
9adf20d72e gofmt -s 2016-01-17 23:57:07 +08:00
90d1349665 fix typo 2016-01-17 23:48:17 +08:00
9b2597be68 fix the mail send empty subject 2016-01-17 23:48:09 +08:00
895748d632 beego 1.6.0 released 2016-01-17 22:55:09 +08:00
566aab4354 mail send support Address format 2016-01-17 22:49:02 +08:00
a304bb9c25 Revert "add test case for tidb"
This reverts commit f70d2cc373.
2016-01-17 18:35:11 +08:00
f70d2cc373 add test case for tidb 2016-01-17 18:24:29 +08:00
897cf57840 use travis-ci.org as build-status 2016-01-15 14:59:16 +08:00
8e6b0a6d7b Merge pull request #1567 from JessonChan/develop
some typo fixed
2016-01-15 14:40:14 +08:00
797571c85f fix the ORM test case 2016-01-15 14:36:45 +08:00
814e4ac031 rename the docsSepc to docs_spec 2016-01-15 14:14:09 +08:00
52083de720 typo fixed
seperator => separator
2016-01-15 14:07:37 +08:00
a069c73b3a test case bool default value is true 2016-01-15 14:02:08 +08:00
7dbeb2c39a fix the default value 2016-01-15 08:43:02 +08:00
4375ca84d1 fix the sqlite m2m 2016-01-14 23:49:28 +08:00
0eaf923a27 Merge pull request #1560 from JessonChan/log_enhancement
Log enhancement
2016-01-13 22:57:39 +08:00
9c55985915 update readme 2016-01-13 22:20:34 +08:00
6976c0f51d add CONTRIBUTING.md 2016-01-13 22:02:36 +08:00
5befc67389 Merge remote-tracking branch 'remotes/upstream/develop' into log_enhancement 2016-01-13 10:15:00 +08:00
fb5b04506a code refactor and format 2016-01-13 09:24:27 +08:00
7663d50c97 remove the lock writer 2016-01-13 09:21:55 +08:00
58730e3528 test file modify 2016-01-13 09:21:32 +08:00
e1b73b33d0 improve code 2016-01-13 08:21:44 +08:00
c535dc386e fast format 2016-01-12 22:54:39 +08:00
69804afc1b use pool to logMsg 2016-01-12 22:39:40 +08:00
164366ae0d return error 2016-01-12 22:33:52 +08:00
2b9d7ff714 remove log package 2016-01-12 22:32:36 +08:00
bd0f3c29fa decr malloc new object 2016-01-12 22:32:20 +08:00
6660720ce6 update some config name 2016-01-12 21:55:02 +08:00
12e7f0f94a extract a func to write to every logger 2016-01-12 21:15:25 +08:00
482b7a62bd use array not map 2016-01-12 21:05:06 +08:00
b90a28bafb Merge pull request #1546 from youngsterxyf/develop
fix #1530
2016-01-12 20:01:51 +08:00
baa2e9d64a code format 2016-01-12 19:44:28 +08:00
5511e03b52 embedding file writer 2016-01-12 19:25:33 +08:00
9507e59c2f camel name fixed 2016-01-12 19:10:08 +08:00
2479e61db9 add asynchronous and call depth benchmark 2016-01-12 19:09:00 +08:00
c9b890b10e add asynchronous benchmark 2016-01-12 17:59:23 +08:00
e32e3a759c console type no need to bench 2016-01-12 17:46:10 +08:00
391f897eb1 simplify sessionID 2016-01-11 16:49:56 +08:00
dc278da17c fix the sqlite3 & cache sleep 11 second 2016-01-08 23:30:19 +08:00
c7146d22f4 add all dependence 2016-01-08 23:20:25 +08:00
1aff26cc31 add dependence database 2016-01-08 23:10:50 +08:00
c59bc431e3 mulit variable 2016-01-08 23:00:22 +08:00
d0dd68351a update travis 2016-01-08 22:34:23 +08:00
0c48738841 for issue #1530, fix incompatible bug 2016-01-08 21:29:12 +08:00
0b0904db13 for issue #1530, accept @JessonChan's suggestion 2016-01-08 20:16:58 +08:00
fd608d2bf6 disable tidb testing 2016-01-08 19:59:20 +08:00
5b028796b8 fix the test case for input 2016-01-08 16:24:59 +08:00
d2de71d8ab update the dependence 2016-01-08 16:01:07 +08:00
302b1ef7df fix the data 2016-01-08 15:52:57 +08:00
77fa891499 update dependence 2016-01-08 15:47:13 +08:00
69bcbcdb31 add travis 2016-01-08 15:34:02 +08:00
bb43d3a78c fix #1530 2016-01-08 13:47:14 +08:00
01012fa898 admin configure 2016-01-08 01:40:19 +08:00
9167587929 add Params for input 2016-01-08 01:20:34 +08:00
c68505e451 read config from app.conf for session 2016-01-07 23:55:55 +08:00
98f3fecc03 fix the typo 2016-01-07 23:35:01 +08:00
c6141f5d94 add httpsaddr 2016-01-07 23:31:33 +08:00
43ca13b516 Merge pull request #1543 from miraclesu/validation
Add validation custom function
2016-01-07 23:24:31 +08:00
687266fb64 Add 179 to valid Phone number 2016-01-07 23:03:32 +08:00
21f767784b Add custom validation function doc 2016-01-07 22:55:12 +08:00
103ac3ee5b Add custom validation function 2016-01-07 22:42:04 +08:00
db2918b0aa Merge pull request #1542 from ysqi/develop
fix issues  #1473, #1502
2016-01-07 21:02:42 +08:00
6eff2e433f fix #1502,Notes error repair 2016-01-07 20:55:28 +08:00
58e2a7c099 fix #1473,Only update redis session if it already exist 2016-01-07 20:42:26 +08:00
434544060a Merge pull request #1540 from ysqi/develop
TplNames renamed TplName ,fix #1229,Remember modify bee tool.
2016-01-07 17:03:22 +08:00
4c0c0ec2a7 TplNames renamed TplName ,fix #1229,Remember modify bee tool. 2016-01-07 16:16:39 +08:00
ecc6bcba3f Merge pull request #1539 from ysqi/develop
change get sessionID logic from cookie
2016-01-07 13:49:33 +08:00
80912b6210 change get sessionID logic from cookie 2016-01-07 13:15:40 +08:00
3fdf72f14c Merge pull request #1532 from JessonChan/develop
mem cache put function fixed
2016-01-07 12:56:47 +08:00
3821b2cb26 createdTime typo fixed 2016-01-07 09:37:50 +08:00
8aed4c13d7 isExist func will check if the value is expired 2016-01-07 09:36:23 +08:00
6465dbd703 no more goroutine ,i will be GCed at a gc goroutine 2016-01-07 09:28:40 +08:00
98e0626f0c rename vals 2016-01-07 09:25:06 +08:00
b0b9812de6 extract a expire fun 2016-01-07 09:13:47 +08:00
eff200e014 modify as xuxiaohei suggest
https://github.com/astaxie/beego/issues/1259
2016-01-07 09:08:00 +08:00
8832334d6a tiny fix for error description and comment 2016-01-06 15:12:25 +08:00
0b39091292 mem cache put function fixed
when a expire duration==0,it means forever
https://github.com/astaxie/beego/issues/1260
2016-01-06 15:05:29 +08:00
a411042416 fix the init parse for config 2016-01-06 14:55:18 +08:00
8929814126 fix the log carsh before init 2016-01-06 11:48:23 +08:00
bef6bca397 Add function to set validation default messages 2016-01-05 21:14:35 +08:00
f7ef4aa7e5 recover for conn.Close fix #1333 2016-01-04 23:34:45 +08:00
5c18d02b17 fix #1268 2016-01-04 22:41:25 +08:00
3bb22d149e add the comments 2016-01-04 22:22:42 +08:00
f0be45dfff fix the comments and json tag 2016-01-04 22:18:59 +08:00
7fbaf82897 fix #1424 2016-01-04 22:10:18 +08:00
73168d2f7d Merge pull request #1527 from JessonChan/develop
reuse compress writer
2016-01-04 14:36:40 +08:00
a03fa0fb73 improve cache modules. support mulit instances 2016-01-04 10:50:04 +08:00
fd2ded190b EnableGzip bug fixed 2016-01-04 09:27:58 +08:00
d23291ccc7 remove a dump err 2016-01-04 08:50:59 +08:00
92d157736b add testing to test #1511 2016-01-03 21:06:35 +08:00
6585e66f97 all the browser should support delete and put now 2016-01-03 20:36:16 +08:00
3ebf275157 fixed camel style name 2016-01-03 15:40:44 +08:00
ee2322e83b add any level compress 2016-01-03 15:35:32 +08:00
59fa248292 use sync.Pool to decrease new compression writer 2015-12-31 18:50:52 +08:00
9519fc6c96 Merge pull request #1519 from vvelikodny/develop
Refactoring: Move dev & prod runmodes to const
2015-12-30 21:03:54 +08:00
4b368d9f5e Refactoring: keep config package beego independent 2015-12-30 11:22:09 +03:00
48fd9675ad Refactoring: Move dev & prod runmodes to const 2015-12-29 21:32:37 +03:00
ac3a447479 fix the session update issues 2015-12-27 14:09:20 +08:00
37dff6be28 Merge pull request #1507 from yydzero/develop
Retrieve session identifier from cookie and query parameters
2015-12-27 11:01:04 +08:00
cdde5bdc62 Merge pull request #1516 from johndoejdg/patch-2
Add link to russian
2015-12-27 11:00:24 +08:00
2d4cc6e33d Add link to russian
Add link to russian
2015-12-26 16:43:49 +03:00
5336e83469 Merge pull request #1506 from fuxiaohei/develop
clean code in docs.go, error.go, filter.go and hooks.go
2015-12-23 12:12:08 +08:00
da39082d4f Retrieve session identifier from cookie and query parameters 2015-12-22 10:30:44 +08:00
fud
cd514803a4 simplify filter.go hooks.go 2015-12-22 10:02:59 +08:00
fud
2ddda59605 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-12-22 09:57:47 +08:00
25337aec27 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-12-21 22:54:22 +08:00
351dfac653 context.Response should implement Hijack/Flush/CloseNotify 2015-12-21 22:51:18 +08:00
9105fee453 Merge pull request #1503 from fuxiaohei/develop
simplfy config.go and controller.go
2015-12-21 19:49:22 +08:00
fud
bbd42ce152 simplify docs.go and error.go, use http.StatusText instead of string codes 2015-12-21 17:16:58 +08:00
fud
92711e80a3 refactor controller.go 2015-12-21 16:23:31 +08:00
fud
c43e3d6684 fix type mismatch error 2015-12-21 16:05:26 +08:00
fud
f6c508f138 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-12-21 15:49:23 +08:00
130ce7eb1f Merge pull request #1501 from nkbai/develop
cors test benchmark doesn't use b.N
2015-12-19 13:45:04 +08:00
083c155079 cors test benchmark doesn't use b.N 2015-12-19 10:29:12 +08:00
a71c4283e8 Merge pull request #1498 from JessonChan/develop
compress level test fixed
2015-12-18 10:18:42 +08:00
80ac8aa40e compress level test fixed 2015-12-18 09:28:40 +08:00
5e249772d5 reduce loop 2015-12-18 00:14:28 +08:00
a4f674e7f4 Merge pull request #1483 from nkbai/develop
为orm接口添加注释
2015-12-17 22:23:32 +08:00
ae52d4aa18 improve the splitPath 2015-12-17 21:31:44 +08:00
f9138c5a99 simplify config.go 2015-12-17 20:05:00 +08:00
e5096be32b Merge pull request #1490 from pjoe/orm_pk_rel_many
Fix joins for reverse(many) with custom pk
2015-12-17 14:56:06 +08:00
9b87f528ec Merge pull request #1494 from astaxie/revert-1489-develop
Revert "go test fixed"
2015-12-17 14:45:17 +08:00
c3d1e4d088 Revert "go test fixed" 2015-12-17 14:45:10 +08:00
77113e843c Merge pull request #1489 from JessonChan/develop
go test fixed
2015-12-17 14:44:29 +08:00
46aa340b1d Merge pull request #1478 from fuxiaohei/develop
clean compliated codes, refactor if sections in app.go
2015-12-17 14:44:14 +08:00
8771634fe4 Merge remote-tracking branch 'remotes/upstream/develop' into develop 2015-12-17 09:25:15 +08:00
2aa50c240f Merge pull request #1486 from KilledKenny/oomDos
Added MaxMemory limit to CopyBody() Supersedes #1484
2015-12-16 23:44:42 +08:00
dbc4ac6945 reduce the slicegrow 2015-12-16 23:43:32 +08:00
29752e2575 refactor router 2015-12-16 23:11:03 +08:00
52c4c1fb98 Added MaxMemory limit to CopyBody()
Beego only uses the MaxMemory flag when using go's built in functions
for parsing forms. However the CopyBody() function have no limit an will
coppy anny amount of data into memory using ioutil.ReedAll() on the
request body whitout anny size validation or limit.

This fix wrapps input.Requst.Body in a LimitedReader using the same
memory limit as ParseFormOrMulitForm()
2015-12-16 10:37:21 +01:00
906637ae8b Fix issue with reverse(many) for models with custom pk
- Also add test covering the issue
2015-12-15 17:39:08 +01:00
3daaaeb32b add commit for orm/types.go 2015-12-15 19:48:28 +08:00
ccc008c257 compress fixed 2015-12-15 14:29:07 +08:00
fd9a6ff7bb Merge remote-tracking branch 'remotes/upstream/develop' into develop 2015-12-15 14:27:43 +08:00
e63d24637d go test fixed 2015-12-15 14:08:58 +08:00
7dcbcf0748 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-12-15 14:05:58 +08:00
1576add9a2 Merge pull request #1488 from astaxie/revert-1487-develop
Revert "compress method fixed"
2015-12-15 14:05:43 +08:00
58aa0545b6 Revert "compress method fixed" 2015-12-15 14:05:33 +08:00
10cbe7a867 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-12-15 13:18:09 +08:00
d6f23afdbb Merge pull request #1487 from JessonChan/develop
compress method fixed
2015-12-15 11:49:19 +08:00
499e2b59e4 compress method fixed
in http,the deflate is zlib compress method accoding to the sec
http://tools.ietf.org/html/rfc2616#section-3.5
The "zlib" format defined in RFC 1950 [31] in combination with
        the "deflate" compression mechanism described in RFC 1951 [29].
2015-12-15 11:34:26 +08:00
d99c62df1f Merge remote-tracking branch 'upstream/develop' into develop 2015-12-14 15:09:06 +08:00
b079456fcf add comments for orm/types.go 2015-12-14 15:04:17 +08:00
a06022f75c clean compliated codes, refactor if sections in app.go 2015-12-12 14:10:02 +08:00
2b651fbae2 reuse map in tree.Match 2015-12-11 13:51:01 +08:00
80bc372f17 pool.Put 2015-12-11 00:20:17 +08:00
f70f338025 use sync.Pool to reuse Context 2015-12-10 21:59:54 +08:00
f2edfbe7ae make the other three beauty 2015-12-10 00:12:52 +08:00
4f829af7aa gofmt the config default 2015-12-10 00:11:24 +08:00
9f2a2507fd fmt it and remove the init var 2015-12-09 23:47:44 +08:00
be60f47488 Merge pull request #1455 from nkbai/develop
windows下静态文件映射找不到问题以及 grace init延后
2015-12-09 23:44:45 +08:00
d1bba02958 refact beego config 2015-12-09 23:35:04 +08:00
e8fe859a58 格式调整 2015-12-09 09:03:10 +08:00
82e0105d22 Revert "windows下静态文件映射找不到问题,"
windows下路径需要filepath.ToSlash

This reverts commit 2c8cb5693e.
2015-12-04 23:15:06 +08:00
ff0762cc19 Merge remote-tracking branch 'upstream/develop' into develop 2015-12-03 15:50:21 +08:00
3d4ad560f8 Merge pull request #1423 from JessonChan/fargo
fix the  accept encoding
2015-12-02 21:08:34 +08:00
36664634f9 Merge pull request #1467 from astaxie/revert-1464-master
Revert "Update orm_querym2m.go"
2015-12-02 16:35:44 +08:00
ed99c013a6 Revert "Update orm_querym2m.go" 2015-12-02 16:35:36 +08:00
a1d5f958c5 Merge pull request #1464 from gobenon/master
Update orm_querym2m.go
2015-12-02 16:35:05 +08:00
5d902264e5 Merge pull request #1459 from ryanchapman/develop
Log config parsing errors
2015-12-02 16:34:35 +08:00
50f8f3bd20 Update orm_querym2m.go 2015-11-30 18:23:58 +02:00
74ebcd28b2 grace init中的工作可以延后进行
实际上如果没有使用graceful启动,这些init的工作完全没用
当然其他模块也应该存在这样的工作,比如session中的sess_utils.go中的init工作
2015-11-30 16:15:35 +08:00
7151b96465 Log config parsing errors
Beego currently handles the case of "conf/app.conf"
not existing, but all other errors are not logged.
This fixes that.

I ran into an issue where beego was not listening on the
correct port, and it turned out that the conf/app.conf file
had a colon ":" instead of an equal sign "=" (confusion of
INI vs YAML formats).  When there was a parsing error, beego
would give up on parsing app.conf and not log anything to the
console.
2015-11-29 15:09:28 -07:00
2c8cb5693e windows下静态文件映射找不到问题,
path.Clean和filepath.Clean是有区别的
2015-11-27 12:10:39 +08:00
d693ecf046 Revert "这种if型的初始化是有问题的"
This reverts commit 50132df809.
2015-11-26 20:37:36 +08:00
6aaca2eca8 router.go Header 毫无用处
context/output.go 简化一下代码,更清晰
2015-11-26 14:56:39 +08:00
f0474214fe GetInt等函数稍微简化一下,这样看上去更合理一些 2015-11-25 23:39:26 +08:00
2c94d9eab2 Merge pull request #1451 from gobenon/master
fix issue 1438 opened by Ayelet Regev
2015-11-25 09:29:28 +08:00
40700a8532 Merge remote-tracking branch 'remotes/upstream/develop' into fargo
# Conflicts:
#	memzipfile.go
2015-11-25 09:11:32 +08:00
fb7314f8ac Merge pull request #1450 from astaxie/revert-1439-master
Revert "Adding support for junction tables with other fields which arent FK and PK."
2015-11-24 23:00:15 +08:00
b7fcd4f0b9 Revert "Adding support for junction tables with other fields which arent FK and PK." 2015-11-24 23:00:07 +08:00
e48e09a4ab Merge pull request #1439 from gobenon/master
Adding support for junction tables with other fields which arent FK and PK.
2015-11-24 23:00:04 +08:00
235b58504a Merge pull request #1449 from nkbai/master
controller_test.go 既然叫test,那就按照go的规则进行test吧
2015-11-24 15:54:46 +08:00
5e915cb614 controller_test.go 既然叫test,那就按照go的规则进行test吧 2015-11-24 14:55:59 +08:00
9170b91075 go style format (remove the blank after comments) 2015-11-21 08:46:19 +08:00
25320bf86a Merge pull request #1441 from nkbai/master
fix #1433
2015-11-20 21:50:55 +08:00
50132df809 这种if型的初始化是有问题的 2015-11-20 21:34:01 +08:00
83696a40f6 fix #1433 2015-11-20 11:18:45 +08:00
efd30bdba7 Update orm_querym2m.go 2015-11-19 16:46:14 +02:00
01aa1085e0 Merge pull request #1 from gobenon/gobenon-m2mpatch-1
Update orm_querym2m.go
2015-11-19 14:32:24 +02:00
ca37557a26 Update orm_querym2m.go 2015-11-19 14:30:14 +02:00
5a1e821a42 Merge pull request #1434 from WnP/pg-fix
fix postgres syntax error during migration
2015-11-19 12:25:21 +08:00
29ac961c10 fix postgres syntax error during migration 2015-11-18 06:46:44 -06:00
5d01afe3a6 isOk to check whether the file is latest 2015-11-16 14:05:05 +08:00
d963bb79bd avoid map-lock delete 2015-11-16 10:31:27 +08:00
bc2195b07f code simplify 2015-11-12 16:59:07 +08:00
46fbeaadad refactor accept encoder ,simplify the struct 2015-11-12 12:03:53 +08:00
214030fad4 bytes reader replace string reader 2015-11-12 11:44:29 +08:00
f8db8ae9c3 add some comments 2015-11-12 10:48:36 +08:00
a9881388f7 accept encoder header setting fixed 2015-11-12 10:08:57 +08:00
1200b7c347 method refactor 2015-11-11 18:06:18 +08:00
b25a1355f9 remove old code 2015-11-11 16:27:41 +08:00
d2c60619fa new static file support code 2015-11-11 16:22:40 +08:00
82c50b972d new test file 2015-11-11 16:22:05 +08:00
15b0b9b66d delete old static file code 2015-11-11 16:21:04 +08:00
e4c6e5d2e1 change package 2015-11-11 13:47:47 +08:00
f457ea0fe9 refactor encoder package 2015-11-11 13:47:36 +08:00
7ef9b3d55b runnable typo fixed 2015-11-10 14:07:26 +08:00
39e29caf9b refactor to fix encoder type bug 2015-11-10 13:42:10 +08:00
7ccf049a50 bug fixed 2015-11-10 13:27:33 +08:00
7964f7f163 test bug fixed 2015-11-10 13:16:16 +08:00
8603127c81 beego package file path rewrite 2015-11-10 13:10:42 +08:00
07c93cd32c mem zip file test ,add license 2015-11-10 11:59:32 +08:00
83ec39d02e refactor max age cookies setting 2015-11-10 11:47:10 +08:00
8f42193610 better compress func design 2015-11-10 11:32:18 +08:00
891be34fc6 encoding should be specify 2015-11-10 11:20:13 +08:00
0bc70e88f0 ignore the other compress method 2015-11-10 11:00:29 +08:00
3872c48349 accept encoding refactor and bug fixed 2015-11-10 10:55:47 +08:00
dc28e37606 Merge branch 'develop' into fargo 2015-11-09 17:18:00 +08:00
821b2f832e fix the type assert 2015-11-09 11:03:57 +08:00
9b725c73c3 Merge pull request #1376 from JessonChan/develop
static file code refactor and bug fixed
2015-11-08 23:21:16 +08:00
860568cb6c modified as astaxie reviews
https://github.com/astaxie/beego/pull/1376
2015-11-06 18:51:53 +08:00
dc3e324f38 Merge pull request #1418 from ElvizLai/patch-1
Update context.go
2015-11-05 22:39:34 +08:00
b8fc42d38d Update context.go
all this status was setting in error.go, this line will cause multi-resp
2015-11-05 21:20:57 +08:00
a26dee556d fix #1335 2015-11-05 00:19:09 +08:00
fd4630c6dd impove the ResponseWriter. fix #1410 2015-11-04 23:52:42 +08:00
e3120226fa Merge pull request #1414 from FlamingTree/develop
bugfix: graceful failed when both enable http and https
2015-11-04 23:27:27 +08:00
25bec8bbe9 Merge pull request #1381 from ADone/m2m_reverse_bug
fix #671
2015-11-04 23:20:22 +08:00
a257a924a1 Merge pull request #1379 from pjoe/non_int_fk
orm: Fix handling of rel(fk) to model with string pk
2015-11-04 22:26:33 +08:00
c7e9a86b00 Merge pull request #1415 from johndeng/develop
Fixed typos
2015-11-04 13:08:37 +08:00
205de8418d Fixed typos 2015-11-03 23:43:34 +08:00
f81929c28c bugfix: graceful failed when both enable http and https 2015-11-03 14:53:26 +08:00
58ed1436cc Merge pull request #1409 from superhacker777/patch-2
XSRFFormHtml() should also generate XSRF token.
2015-10-28 15:54:07 +08:00
5d18a7466c XSRFFormHtml() should also generate XSRF token. 2015-10-27 20:16:47 +03:00
912abe3272 fix #1388 2015-10-12 21:26:18 +08:00
4ba50e5df5 fix #1385 2015-10-12 20:50:58 +08:00
332fa44231 Merge pull request #1384 from pjoe/update_err_fix
Fix dbBase.Update not returning error on failure
2015-10-12 20:43:22 +08:00
174e758d19 Fix dbBase.Update not returning error 2015-09-28 14:07:35 +02:00
1f2f0b30f4 mem zip file refactor and test 2015-09-22 22:02:56 +08:00
cfcce4f5dc Fix handling of rel(fk) to model with string pk 2015-09-22 12:23:51 +02:00
1abf85ed2a simplify the switch code 2015-09-22 15:18:24 +08:00
d4f3dfd527 return when find static path 2015-09-22 14:15:41 +08:00
6ad215a9bb mem zip file var refactor 2015-09-22 14:11:02 +08:00
9c17f73489 code refactor 2015-09-22 13:48:34 +08:00
4995f91547 code refactor 2015-09-22 13:46:20 +08:00
936cb735e1 file extensions bug fixed 2015-09-22 13:27:35 +08:00
f708ce0299 当有设置的压缩类型时,丢弃默认类型(css,js) 2015-09-22 12:24:52 +08:00
dc38b324e0 code bug fixed 2015-09-22 12:19:31 +08:00
b9fb3a62f5 static file name default lower case 2015-09-22 11:59:48 +08:00
95ef4c7136 server index.html in beego with ServeContent 2015-09-21 23:56:24 +08:00
eb85e8e328 path.Clean can't clean window separate .."
"
2015-09-20 19:59:30 +08:00
e26720496f remove the dupl 2015-09-19 20:05:57 +08:00
8af8936ee0 Merge pull request #1368 from JessonChan/fargo
error bug fixed and clean code
2015-09-19 15:10:22 +08:00
07a424581d // beego.Run("localhost") 2015-09-19 05:53:28 +08:00
69bee9ef3c // beego.Run("localhost") 2015-09-19 05:52:52 +08:00
caf3714495 revert exceptMethod 2015-09-19 05:41:10 +08:00
983bac986a runFunction camel name 2015-09-18 18:34:07 +08:00
56032c67af runFunction camel name 2015-09-18 18:31:06 +08:00
40cb8e0cf1 use reflect to ensure all methods been except 2015-09-18 18:18:12 +08:00
0ac690d2c8 method name refactor 2015-09-18 17:59:28 +08:00
cc5abc6b30 default atoi func to handle exception 2015-09-18 17:03:00 +08:00
cb0400dcd4 file add the config for Perm 2015-09-18 12:12:02 +08:00
fda28fa2ff fix the conv test case 2015-09-18 12:11:48 +08:00
2a96f33543 more clean code 2015-09-18 10:36:16 +08:00
8df2cca627 add comment 2015-09-18 10:32:21 +08:00
ead635e62f default exception handler 2015-09-18 10:31:10 +08:00
4823a0f114 remove the dead code 2015-09-17 23:47:26 +08:00
e665a7dd32 Merge pull request #1367 from dvwallin/develop
added a check to parser to not panic (in develop)
2015-09-17 23:41:59 +08:00
6e24b78b62 fix the wrong response 2015-09-17 23:27:34 +08:00
edbad60782 Merge branch 'develop' of github.com:dvwallin/beego into develop 2015-09-17 17:07:06 +02:00
bb6062857b fix the error refactor 2015-09-17 23:05:45 +08:00
0d100fef7d Merge pull request #1364 from JessonChan/fargo
error and hook refactor
2015-09-17 23:02:32 +08:00
eac09e6fb6 Merge pull request #1349 from ElvizLai/patch-4
Update tree.go
2015-09-17 23:01:32 +08:00
3df0fa462d golint tidb 2015-09-17 23:00:05 +08:00
dfbb1b5ee5 Merge pull request #1366 from ngaut/master
Add support for TiDB
2015-09-17 21:25:12 +08:00
09b7457ac6 orm_test: Skip relation test 2015-09-17 17:05:40 +08:00
c841a77ad6 Orm: Add tidb for query builder 2015-09-17 17:04:23 +08:00
c73e0395ed Orm: Support TiDB 2015-09-17 17:04:23 +08:00
de20960458 error map refactor 2015-09-17 10:36:29 +08:00
bb776cc4cb error map refactor 2015-09-17 10:33:12 +08:00
cce8d1e934 refactor hooks function code 2015-09-17 10:31:53 +08:00
c6448727de golint utils 2015-09-14 23:35:13 +08:00
5015614fdc golint pagination 2015-09-14 23:17:33 +08:00
7b81617a95 golint captcha 2015-09-14 23:13:51 +08:00
2389bc72f9 golint validation 2015-09-13 00:13:19 +08:00
1d200da472 golint toolbox 2015-09-12 23:28:24 +08:00
be7accc94c golint testing 2015-09-12 23:19:18 +08:00
a289b08e64 golint swagger 2015-09-12 23:15:23 +08:00
172894efe8 golint session 2015-09-12 22:53:55 +08:00
ea2039c1dc golint plugins 2015-09-12 22:03:45 +08:00
68ec133aa8 golint orm 2015-09-12 21:46:43 +08:00
542e143e55 golint migration 2015-09-11 23:16:05 +08:00
0a5fa04062 remove i18n.go 2015-09-11 23:09:37 +08:00
34877c52a9 golint logs 2015-09-11 23:08:24 +08:00
657995092a golint httplib 2015-09-11 22:28:28 +08:00
f6d4629103 added a check to parser to not panic 2015-09-10 11:35:57 +02:00
65fb7ce391 golint grace 2015-09-10 16:35:40 +08:00
01a5e54264 delete example from the source code 2015-09-10 15:40:46 +08:00
ff5b09fc19 golint context 2015-09-10 15:31:09 +08:00
bdd6a6ae40 golint config 2015-09-10 14:53:19 +08:00
d7aaf2ebeb golint cache package 2015-09-09 00:15:03 +08:00
62e528ca4c golint tree.go 2015-09-08 23:49:24 +08:00
bcb1db256d golint templatefunc 2015-09-08 23:41:41 +08:00
44bd3beb5e golint happy with template 2015-09-08 23:29:58 +08:00
8615f875f8 make golint happy staticfile.go 2015-09-08 22:07:44 +08:00
b2048e8653 make router test passed 2015-09-08 22:05:38 +08:00
c11740b647 make golint happy router.go 2015-09-08 22:01:13 +08:00
21fffc446b make golint happy parser.go 2015-09-08 21:45:45 +08:00
67b36d7c48 make golint happy 2015-09-08 21:41:38 +08:00
61570ac2f7 make golint happy with controller.go 2015-09-08 10:43:42 +08:00
f28a941e26 make golint happy and also make the config readable 2015-09-07 23:19:42 +08:00
152127c2af make golint happy 2015-09-07 21:38:53 +08:00
919675e793 update the comments 2015-09-07 19:29:52 +08:00
fe9c52fb69 optimize init admin 2015-09-07 19:27:53 +08:00
284dfc0843 move the template related fun to template.go 2015-09-07 19:21:55 +08:00
85d8ec5ca6 optimize the beego structure 2015-09-07 19:18:04 +08:00
eb3479b753 optimize the app structure 2015-09-06 23:00:42 +08:00
a2a6ec954b Update tree.go
go fmt
2015-09-06 22:13:58 +08:00
45b72b0674 Merge pull request #1334 from ElvizLai/patch-2
Update beego.go
2015-09-06 22:12:13 +08:00
9e969957de Merge pull request #1348 from sidbusy/develop
allows custom the TableName of Session
2015-09-06 21:22:05 +08:00
7b0f3a83dc Merge pull request #1351 from leekchan/cache
Fix a wrong test name & update a outdated information in README
2015-09-06 18:46:59 +08:00
fe1ec1675f Fix a wrong url (http 404). 2015-09-06 17:22:33 +09:00
4ad743fc8b Update a outdated information in README. 2015-09-06 17:20:18 +09:00
06ec3a931d Fix a wrong test name. 2015-09-06 17:13:55 +09:00
1377d16559 Update tree_test.go 2015-09-06 12:17:16 +08:00
ddd9bf1305 Update tree.go 2015-09-06 12:16:05 +08:00
508a57be1e Update tree_test.go 2015-09-06 12:07:12 +08:00
5ad999a3d1 Update tree.go
fix routers for:
```
/topic/:id/?:auth
/topic/:id/?:auth:int
```
2015-09-06 12:01:50 +08:00
f55bbbdff4 allows custom the TableName of Session 2015-09-05 10:31:31 +08:00
34aa9002bb fix the httplib test case timeout 2015-09-04 23:03:10 +08:00
f9fe89fff0 fix the file rotate test case issues 2015-09-04 22:33:03 +08:00
9ab7466d5c fix the cappital 2015-09-04 22:20:55 +08:00
2e75c04ffb Merge pull request #1345 from f0r/develop
为querySeter添加GroupBy方法
2015-09-04 21:48:47 +08:00
9038cdfaae Merge pull request #1343 from onealtang/oneal-dev
always use server's locale to parse date
2015-09-04 21:32:18 +08:00
f0r
a074df9c2e 为querySeter添加GroupBy方法 2015-09-03 00:45:09 +08:00
adca455804 always use server's locale to parse date
When parsing the date without time, it's always using UTC date, which is
unexpected. If we want to use UTC date, it's recommend to set the
server's timezone as UTC, and keep the code flexible.
2015-09-02 15:50:40 +08:00
9fd571830d Update beego.go
Maybe the `Hard Coding` should have a higher priority
2015-09-01 17:52:44 +08:00
dd4cbdda66 update the gitignore 2015-08-31 11:58:11 +08:00
ad6547936e fix the http: multiple response.WriteHeader calls 2015-08-28 23:08:00 +08:00
306effa300 Merge pull request #1329 from ElvizLai/patch-1
Update error.go
2015-08-28 22:33:20 +08:00
c516819c56 Update error.go
this caused `http: multiple response.WriteHeader calls` when using method `CustomAbort` or `Abort` when status is already in errMap like 404.
2015-08-28 16:54:49 +08:00
4202fe8fe0 Merge pull request #941 from lei-cao/develop
Added JWT plugin
2015-08-27 22:57:04 +08:00
0c5f4b48d4 Merge pull request #1276 from pjoe/orm_distinct
Fix issue #1274: Add QuerySeter.Distinct()
2015-08-27 22:54:39 +08:00
7aa893612e Merge pull request #1308 from zhangshuai/master
httplib请求参数支持[]string
2015-08-27 22:50:44 +08:00
cfaae5ab8c Merge pull request #1326 from hvnsweeting/patch-1
fix typo
2015-08-27 22:49:38 +08:00
cbb6591bdb fix typo 2015-08-26 15:57:28 +07:00
0c33673197 Revert spaces > tabs change 2015-08-24 09:41:10 +02:00
862ea226e5 优化设置参数 2015-08-24 00:16:56 +08:00
437349f776 Merge pull request #1247 from Skycrab/develop
fix example/chat i/o timeout
2015-08-23 22:18:38 +08:00
bc1f0ac6fd Merge pull request #1298 from wulove/develop
全局变量AutoRender为false时,run时不再编译模版;针对开发模式下,每个请求渲染模版时支持单独编译当前请求相关模版
2015-08-23 22:13:15 +08:00
db2b1ee54f Merge pull request #1318 from tabalt/patch-1
fixed mux1 to mux
2015-08-21 10:57:42 +08:00
99b1c5c54b fixed mux1 to mux 2015-08-21 10:53:59 +08:00
38ddb61199 files is []string, use len(files)==0 2015-08-21 10:32:53 +08:00
d9e4836715 Merge pull request #1305 from Hepri/develop
Added MapGet template func
2015-08-20 22:33:07 +08:00
0e3fe64c69 Added TestMapGet 2015-08-20 19:04:43 +05:00
4081311a37 Merge pull request #1309 from smallfish/develop
Update router.go, add Flush for responseWriter
2015-08-19 15:25:24 +08:00
506f54a080 Update router.go, add Flush for responseWriter 2015-08-19 15:23:50 +08:00
ff92f22d84 删除Param中的断言 2015-08-18 23:19:24 +08:00
860006bfda httplib请求参数支持[]string 2015-08-18 19:28:17 +08:00
9107fd8898 remove the default timeout setting 2015-08-17 22:33:28 +08:00
d91840779a Update templatefunc.go 2015-08-17 01:18:29 +05:00
d4e15c0bd0 Added MapGet template func 2015-08-17 00:08:02 +05:00
877b5c233e 增加编译模版函数BuildTemplate可变参数,使之支持单个或多个模版的编译,同时针对开发模式,每个请求只编译当前请求相关模版
增加编译模版函数BuildTemplate可变参数,使之支持单个或多个模版的编译,同时针对开发模式,每个请求只编译当前请求相关模版,不再每次请求都编译全部模版
2015-08-06 10:09:34 +08:00
57fdc308e3 AutoRender为空时,不再编译模版
AutoRender为空,Controller.Render()不再执行,故无需编译模版
2015-08-06 09:36:43 +08:00
4857e38471 Merge pull request #1284 from wallclockbuilder/develop
Fix #1269 extract godoc to own file.
2015-07-28 11:57:27 +08:00
42fab96cd4 Merge pull request #1285 from JessonChan/beego_develop
typo fixed
2015-07-28 11:56:45 +08:00
b26ef5b2e5 typo fixed
registor==>register
innner ==> inner
2015-07-27 08:44:58 +08:00
b622d5d369 Fix #1269 extract documentation
Fix #1271 Add description from docs on beego.me to README
and also add same description to godoc
2015-07-26 17:06:55 +00:00
19d82ab62c Fix #1274: Add QuerySeter.Distinct() 2015-07-22 18:12:57 +02:00
9775e3e3a4 Merge pull request #1265 from fugr/develop
set DoRotate fname like xx.2013-01-01.2.log
2015-07-17 01:56:48 +08:00
160d82d1d2 Merge pull request #1267 from wallclockbuilder/develop
Fix for #1256. Indent the code sample lines properly.
2015-07-17 01:50:09 +08:00
45d693e6d6 Add quick start example from website to README 2015-07-16 04:32:07 +00:00
0564956fd6 Fix for #1256. Indent the code sample lines properly. 2015-07-15 12:04:18 +00:00
59b903d557 set DoRotate fname like xx.2013-01-01.2.log
fix fname,by extension to identify the file type on mac and windows.
2015-07-15 17:00:48 +08:00
5612f61a93 fix #671 2015-07-08 17:42:00 +03:00
3becd2e0d8 Merge pull request #1249 from wallclockbuilder/patch-1
Fix #1237
2015-07-08 12:38:48 +08:00
8c0ad5ef88 fix example/chat i/o timeout 2015-07-06 21:12:03 +08:00
079993b9f7 fix #1245 2015-07-06 13:54:14 +08:00
c15aaad85b Merge pull request #1244 from simman/develop
Update validators.go
2015-07-04 20:48:47 +08:00
06b25deab2 Update validators.go
Support virtual operators paragraph 170!
2015-07-04 17:55:01 +08:00
002302818d Fix #1237
Package description uses same text as the README.
2015-07-01 04:17:53 +00:00
a89f14d80d Merge pull request #1227 from oiooj/develop
fix FilterHandler crash issue
2015-06-19 11:43:15 +08:00
87e8bcc9be fix FilterHandler crash issue
Filter Handler will crash with error assignment to entry in nil map , params from function Tree.Match() maybe nil.
2015-06-19 11:19:35 +08:00
31e5edbdcf Merge pull request #2 from astaxie/develop
pull from stable
2015-06-19 11:09:11 +08:00
f7f390dfec fix #1221 2015-06-16 14:53:38 +08:00
8f7246e17b change to version 1.5.0 2015-06-15 23:49:13 +08:00
c8f6e0f156 remove the hardcode in runtime.Caller 2015-06-15 20:53:49 +08:00
0207caab6f keep the shortname for logs info/warn/debug 2015-06-15 20:44:14 +08:00
d629c1d3d0 change the comments 2015-06-15 20:22:05 +08:00
817650aa33 keep the short name for logs 2015-06-15 20:20:37 +08:00
ba1232dfaf filter should be always the same 2015-06-14 18:35:46 +08:00
64d4f6518b fix #1213 2015-06-14 18:10:10 +08:00
9f05db8475 Merge pull request #1212 from astaxie/revert-1211-revert-1210-develop
Revert "Revert "fix multiple filters execute issue""
2015-06-14 01:14:42 +08:00
b275d7c6f5 Revert "Revert "fix multiple filters execute issue"" 2015-06-14 01:14:33 +08:00
73770fbe22 Merge pull request #1211 from astaxie/revert-1210-develop
Revert "fix multiple filters execute issue"
2015-06-14 01:13:42 +08:00
fc11169ee3 Revert "fix multiple filters execute issue" 2015-06-14 01:13:34 +08:00
b54589fa9d Merge pull request #1210 from oiooj/develop
fix multiple filters execute issue
2015-06-14 01:08:51 +08:00
2af0c569a5 The last filterFunc with returnOnOutput=ture won't be executed
ex:
	beego.InsertFilter("/*", beego.BeforeExec, FilterLoginCheck1,false)
	beego.InsertFilter("/*", beego.BeforeExec, FilterLoginCheck2)

In function  FilterLoginCheck1 , I'll write data via ResponseWriter, and w.started = true
FilterLoginCheck2 won't be executed, it should be.
2015-06-14 01:02:41 +08:00
27b7a8f743 Merge pull request #1 from astaxie/develop
Develop
2015-06-14 00:35:38 +08:00
c143a6ec19 fix #1090 add Getfiles to support mulit file upload 2015-06-13 16:20:26 +08:00
e619d83990 fix the filter router issues 2015-06-13 12:47:01 +08:00
27b452cd95 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-06-13 11:15:44 +08:00
b776e43962 merge bat/httplib to httplib 2015-06-13 11:15:13 +08:00
cb89cd577d Merge pull request #1201 from kongjian/develop
support eq&ne for orm
2015-06-13 10:54:47 +08:00
6b777f0c5e Merge pull request #1207 from oiooj/develop
Don't overwrite the params from function  ValidRouter
2015-06-13 09:16:07 +08:00
491238ce7d Don't overwrite the params from function ValidRouter
just add new params to context.Input.Params
2015-06-13 01:04:46 +08:00
d9bb1a3592 logs support elasticsearch adapter 2015-06-13 00:25:48 +08:00
9c6775c22c log default use synchro, and support async 2015-06-13 00:25:21 +08:00
4d70b22f96 Merge pull request #1157 from ziyel/master
Let filter function get more params info from ctx.Input.Params
2015-06-11 14:38:19 +08:00
d943d16d52 gofmt 2015-06-10 21:26:04 +08:00
bbb6f31f16 support eq&ne for orm 2015-06-09 10:18:21 +08:00
364cacf659 record the critical logs in Prod 2015-06-08 22:00:28 +08:00
21586586ba Merge pull request #1198 from kongjian/develop
remove space after int()& add sort for commentsRouter file
2015-06-08 20:20:40 +08:00
e1d7bc8826 remove space after int()& add sort for commentsRouter file 2015-06-08 17:25:46 +08:00
499ee09d4b Merge pull request #1194 from zieckey/GetMulti
Add GetMulti method for Cache interface
2015-06-08 08:36:20 +08:00
970f0b460c Add GetMulti method for Cache interface 2015-06-07 21:33:01 +08:00
9280683935 Merge pull request #1193 from zieckey/auth
Execute AUTH command when the "password" is configured
2015-06-07 20:34:32 +08:00
a58c8180e8 Execute AUTH command when the "password" is configured 2015-06-07 16:26:23 +08:00
b9852df51c Merge pull request #1190 from xboston/patch-1
fix session table
2015-06-04 22:09:26 +08:00
8e71d31dbe fix session table 2015-06-04 18:40:10 +05:00
db06e954b5 fix the session memcache bug 2015-05-28 12:04:19 +08:00
3abd01799d split into small files 2015-05-27 23:46:45 +08:00
ae37689314 fix #1176 grace support windows 2015-05-27 23:22:05 +08:00
40974365e6 Merge branch 'develop' of https://github.com/astaxie/beego into develop 2015-05-25 09:10:59 +08:00
edbaa080f1 update the string 2015-05-25 09:10:38 +08:00
d56491ab3a sync beeApp.Server to graceful 2015-05-25 09:10:38 +08:00
9fd7acf663 fix #1152 2015-05-25 09:10:37 +08:00
2dca48f26e fix sesseion redis db error 2015-05-25 09:10:37 +08:00
4138fe0217 beego suppot graceful restart application 2015-05-25 09:10:37 +08:00
245762f7d9 add apk mime 2015-05-25 09:10:37 +08:00
18bdec951d fix #1143 2015-05-25 09:10:37 +08:00
9252301fa0 Fix save config ini file 2015-05-25 09:10:37 +08:00
1053b63bbc Improve documentation of filter.go. 2015-05-25 09:10:37 +08:00
3bd6caae0a set default timeout 2015-05-25 09:10:37 +08:00
d8734cf58d set default timeout 2015-05-25 09:10:37 +08:00
51161361db more fixed 2015-05-25 09:10:37 +08:00
6da0cdb9e2 no need lock here 2015-05-25 09:10:37 +08:00
9f070c622b no need defer here 2015-05-25 09:10:37 +08:00
738e22e389 zero timeout means wait until resp 2015-05-25 09:10:37 +08:00
69fc22f0df typo fixed 2015-05-25 09:10:37 +08:00
4cd7177ece typo fixed 2015-05-25 09:10:37 +08:00
8e618192c2 better code and fixed 2015-05-25 09:10:37 +08:00
3415a5b091 better go style 2015-05-25 09:10:37 +08:00
dfe055c47c remove useless comments 2015-05-25 09:10:36 +08:00
74b22649c8 remove the double isStruct/isStructPtr check 2015-05-25 09:10:36 +08:00
4255630564 add Recursively validation 2015-05-25 09:10:36 +08:00
7e3b5e5307 remove unreached code 2015-05-25 09:10:36 +08:00
0222b8d693 fixed: when RelatedSel have multi string/relation, it only get last string 2015-05-25 09:10:36 +08:00
23268b788a *feature) 增加logcalldepth接口,使得能简单再次封装log系列函数。 2015-05-25 09:10:36 +08:00
ee4fd60e4d no output the dump 2015-05-25 09:10:36 +08:00
4414659df4 fix the init struct 2015-05-25 09:10:36 +08:00
68ccd8e5a4 fix the dump has no body 2015-05-25 09:10:36 +08:00
6f802b0a05 fix the params 2015-05-25 09:10:36 +08:00
743628a946 add DumpRequest 2015-05-25 09:10:36 +08:00
d90ce15707 httplib support gzip 2015-05-25 09:10:36 +08:00
23457ed2a0 add sethost 2015-05-25 09:10:36 +08:00
d7791ba837 Update validators.go
//176 中国联通
//177 中国电信
//145 中国联通
//147 中国移动
//149 中国电信
2015-05-25 09:10:36 +08:00
676595213f fix a comment error. 2015-05-25 09:10:36 +08:00
d446b5b011 improve the defaultval 2015-05-25 09:10:36 +08:00
2ba12ad1e1 config read and set support Runmode 2015-05-25 09:10:35 +08:00
8cc57e2fc8 fix #1112 2015-05-25 09:10:35 +08:00
322b208566 Update session.go
remove = in if statement
2015-05-25 09:10:35 +08:00
fd610d6777 Update session.go
move expire in line 154 to 247, because it will cause session_cookie not writen to explorer
2015-05-25 09:10:35 +08:00
1148359570 session cookie support IE 2015-05-25 09:10:35 +08:00
55b1d6a897 Update validators.go
edit mobile regular expression ; add 184 Section No.
2015-05-25 09:10:35 +08:00
c4c9a50c42 fix #1081 2015-05-25 09:10:35 +08:00
a311d712a5 Update output.go 2015-05-25 09:10:35 +08:00
bb5351bb9f Update output.go
fix cookie not work in IE
2015-05-25 09:10:35 +08:00
26130a5df6 fix #1073 2015-05-25 09:10:35 +08:00
2c9363d29b add tests to ensure bool value require test always return true. 2015-05-25 09:10:35 +08:00
91886a4547 bugfix: if a form field type is bool, valid Required should always return true instead of return its value. 2015-05-25 09:10:35 +08:00
a7e60c93dc Set ErrorsMap to nil in Validation.Clear function 2015-05-25 09:10:35 +08:00
5b1705b2d6 Do not check log level in writerMsg() because the check is already done outside. 2015-05-25 09:10:35 +08:00
34940d00c0 Remove unnecessary optional group flag '?' since has to match one of comma or end of string 2015-05-25 09:10:35 +08:00
1a6ea693b5 Added to input.go: AcceptHtml, AcceptsXml and AcceptsJson functions which check the header agains a regex for simpler mult-content-type handling. 2015-05-25 09:10:35 +08:00
2e51c124f1 For enhancing performance, check log level before fmt.Sprintf() 2015-05-25 09:10:35 +08:00
1d8afdc9c9 gofmt -s & go_vet 2015-05-25 09:10:34 +08:00
1592e9c04d 验证码reload问题
当页面放置一段时间,验证码将从缓存中失效。当用户再来刷新验证码将出现验证码404。对于reload操作应该直接生成验证码。
2015-05-25 09:10:34 +08:00
bf6b0d3e1f add JsonBody 2015-05-25 09:10:34 +08:00
af71289c25 Merge pull request #1171 from astaxie/add-license
add missed LICENSE of captcha
2015-05-25 09:09:21 +08:00
b1efae6ff8 add missed LICENSE of captcha 2015-05-24 23:59:39 +08:00
92f3de4027 update the string 2015-05-20 11:09:30 +08:00
185089299c sync beeApp.Server to graceful 2015-05-20 11:07:23 +08:00
59c1e74e13 Merge pull request #1158 from mlgd/master
Fix save config ini file
2015-05-18 22:38:59 +08:00
9bb9855153 Let filter function get more params info from ctx.Input.Params 2015-05-18 14:42:18 +08:00
519602a553 fix #1152 2015-05-15 15:04:08 +08:00
740a526105 fix sesseion redis db error 2015-05-13 21:20:50 +08:00
98289cd8de beego suppot graceful restart application 2015-05-13 21:17:47 +08:00
56e2143630 add apk mime 2015-05-09 14:54:30 +08:00
c0cfb5277c Merge pull request #1127 from vanthanh2305/RelatedSel-multi-string/relation
RelatedSel multi string/relation
2015-05-07 23:12:29 +08:00
b29700c3c3 Merge pull request #1131 from JessonChan/develop
httplib more fixed
2015-05-07 22:59:41 +08:00
47be2fadb5 fix #1143 2015-05-05 21:36:31 +08:00
1d72629334 Fix save config ini file 2015-05-04 15:54:03 +02:00
b4880c5e1d Merge pull request #1140 from cr7pt0gr4ph7/doc-pull-request
Improve documentation of filter.go.
2015-05-04 09:47:25 +08:00
c0bb5b9237 Improve documentation of filter.go. 2015-05-03 23:21:32 +02:00
1e1068e81c Merge pull request #1132 from dafang/master
Recursively validations
2015-04-28 11:53:45 +08:00
6c3e274b6e set default timeout 2015-04-26 16:10:18 +08:00
f56bdb6284 set default timeout 2015-04-26 16:08:25 +08:00
d8fa118727 more fixed 2015-04-26 15:42:10 +08:00
0afd04ec6f no need lock here 2015-04-26 15:24:04 +08:00
973306b28d no need defer here 2015-04-26 02:19:38 +08:00
da8c3c3910 zero timeout means wait until resp 2015-04-26 02:17:46 +08:00
0c1bb6409a typo fixed 2015-04-26 02:06:19 +08:00
cddb4fdb60 typo fixed 2015-04-26 02:05:50 +08:00
e1d20aea5d better code and fixed 2015-04-26 02:04:34 +08:00
4498a02c15 better go style 2015-04-26 01:23:18 +08:00
5534258e22 remove useless comments 2015-04-24 11:17:12 +08:00
73650e1f2b remove the double isStruct/isStructPtr check 2015-04-24 11:14:49 +08:00
d0e7dd686b add Recursively validation 2015-04-24 10:58:46 +08:00
dc58ec8316 remove unreached code 2015-04-19 15:40:23 +08:00
6d72fc63ab fixed: when RelatedSel have multi string/relation, it only get last string 2015-04-15 17:41:41 +07:00
dd4afac5dc Merge pull request #1125 from wuranbo/dev_track
*feature) add BeeLogger.GetLogFuncCallDepth make simple wrapper log method aviable.
2015-04-13 12:49:51 +08:00
e229a4762f *feature) 增加logcalldepth接口,使得能简单再次封装log系列函数。 2015-04-13 12:17:44 +08:00
ecb27f34e6 no output the dump 2015-04-09 00:18:02 +08:00
d55997e520 fix the init struct 2015-04-09 00:12:41 +08:00
44c8534477 fix the dump has no body 2015-04-09 00:11:25 +08:00
44a39a6b3e fix the params 2015-04-08 23:00:08 +08:00
cc5ca458ab add DumpRequest 2015-04-08 22:58:37 +08:00
6f6b412709 httplib support gzip 2015-04-08 21:45:00 +08:00
642a69de02 add sethost 2015-04-08 20:12:10 +08:00
466f3c49c1 Merge pull request #1120 from peeped/develop
Update validators.go
2015-04-07 18:48:44 +08:00
d1c9cb2281 Update validators.go
//176 中国联通
//177 中国电信
//145 中国联通
//147 中国移动
//149 中国电信
2015-04-07 17:48:51 +08:00
9c9ffa202a Merge pull request #1119 from lionel0806/develop
fix a comment error.
2015-04-07 11:12:54 +08:00
56dfe418dd fix a comment error. 2015-04-07 10:35:18 +08:00
7caeb91f9b improve the defaultval 2015-04-05 23:23:35 +08:00
47848fa77b config read and set support Runmode 2015-04-05 23:21:13 +08:00
e0e8b98622 fix #1112 2015-04-05 23:12:29 +08:00
5c84ada389 Merge pull request #1106 from peeped/develop
Update validators.go
2015-04-04 20:46:43 +08:00
ac6203b81b Merge pull request #1114 from ElvizLai/patch-2
Patch 2
2015-04-04 13:03:44 +08:00
5e1e618d0f Update session.go
remove = in if statement
2015-04-04 00:44:22 +08:00
a5124a1d45 Update session.go
move expire in line 154 to 247, because it will cause session_cookie not writen to explorer
2015-04-03 17:41:09 +08:00
e675594e46 session cookie support IE 2015-04-02 14:02:39 +08:00
d02e32fa51 Merge pull request #1103 from ElvizLai/patch-1
Update output.go
2015-04-02 13:35:08 +08:00
8a82e25e85 Update validators.go
edit mobile regular expression ; add 184 Section No.
2015-04-02 12:07:12 +08:00
49c0f8906f fix #1081 2015-04-01 23:31:40 +08:00
9261c80509 Update output.go 2015-03-31 12:36:39 +08:00
217e24815b Update output.go
fix cookie not work in IE
2015-03-31 12:30:47 +08:00
840fd3b64f Merge pull request #1083 from supiyun/patch-1
验证码reload问题
2015-03-30 21:40:57 +08:00
eedaea2fea fix #1073 2015-03-30 20:35:57 +08:00
a002f78443 Merge pull request #1097 from pylemon/develop
form required validate for bool field bugfix
2015-03-27 23:04:07 +08:00
cdf9ff401f Merge pull request #1096 from byrnedo/develop
Set ErrorsMap to nil in Validation.Clear function
2015-03-27 14:46:45 +08:00
caa260f053 add tests to ensure bool value require test always return true. 2015-03-27 13:43:20 +08:00
5fa55ca2d3 bugfix: if a form field type is bool, valid Required should always return true instead of return its value. 2015-03-27 13:30:59 +08:00
260b5b1951 Set ErrorsMap to nil in Validation.Clear function 2015-03-26 20:23:00 +01:00
54ae4bc25b Merge pull request #1094 from toalexjin/check_log_level
For enhancing performance, check log level before fmt.Sprintf()
2015-03-26 21:51:23 +08:00
162bee1b43 Merge pull request #1095 from byrnedo/develop
Added AcceptHtml/Json/Xml function to input
2015-03-26 21:50:41 +08:00
533b00ae56 Merge branch 'master' into develop 2015-03-26 08:40:28 +01:00
d3cdebbee2 Do not check log level in writerMsg() because the check is already done outside. 2015-03-26 14:40:12 +08:00
06b5c7f644 Remove unnecessary optional group flag '?' since has to match one of comma or end of string 2015-03-25 14:54:39 +01:00
185ee872c4 Added to input.go: AcceptHtml, AcceptsXml and AcceptsJson functions which check the header agains a regex for simpler mult-content-type handling. 2015-03-25 14:47:20 +01:00
74e0af4a9a For enhancing performance, check log level before fmt.Sprintf() 2015-03-25 15:14:57 +08:00
8aa9455900 gofmt -s & go_vet 2015-03-19 22:29:01 -07:00
2d26f7df2f 验证码reload问题
当页面放置一段时间,验证码将从缓存中失效。当用户再来刷新验证码将出现验证码404。对于reload操作应该直接生成验证码。
2015-03-16 17:40:55 +08:00
3d6408cfc2 Merge pull request #1070 from fugr/patch-5
add JsonBody
2015-03-13 23:16:18 +08:00
223f57bb4c add JsonBody 2015-03-06 14:12:24 +08:00
c4aa33fb1b Merge pull request #1052 from dockercn/develop
Fix the wrong parameter bug in ledis session support cause build failure
2015-03-01 13:58:21 +08:00
20cc5b261e Reform the ledis_session.go 2015-03-01 12:59:34 +08:00
7ec2a077d9 Fix the wrong parameter bug in ledis session. 2015-03-01 12:03:03 +08:00
9f70561f21 Merge remote-tracking branch 'upstream/master' into develop 2015-03-01 11:47:02 +08:00
1c9898dee5 Merge branch 'develop' 2015-02-27 22:52:42 +08:00
2cf7c6a58a change the jQuery URL 2015-02-27 22:51:20 +08:00
2cee46ab2b change the jQuery URL 2015-02-27 22:50:25 +08:00
020bfbcc9c Merge branch 'develop' 2015-02-27 22:47:59 +08:00
3f8252bffd change the version from 1.4.2 to 1.4.3 2015-02-27 22:47:21 +08:00
6d313aa15f fix #985 2015-02-27 22:37:41 +08:00
2a4e2d4a71 delete the group route, because we already has namespace 2015-02-27 22:37:07 +08:00
f96a6285bf fix #978 2015-02-27 22:21:58 +08:00
e938876c4a fix the cycle import 2015-02-27 00:12:10 +08:00
6e9d2dc965 add more error functions 2015-02-26 23:49:24 +08:00
3aceaf8838 error support controller 2015-02-26 23:34:43 +08:00
71b9854f48 Merge pull request #1044 from fuxiaohei/develop
code style simplify
2015-02-23 22:25:34 +08:00
f59ccd3a35 Merge pull request #1043 from Hepri/develop
Added support to parse slices of ints and strings in ParseForm func
2015-02-23 21:58:32 +08:00
181a7c35fe code simplify for package middleware 2015-02-23 11:50:45 +08:00
2ed272aeb2 code simplify for package middleware 2015-02-23 11:50:13 +08:00
77c1109134 code simplify for package logs 2015-02-23 11:42:46 +08:00
29d4823866 code simplify for package httplib 2015-02-23 11:30:59 +08:00
24cf06d288 code style simplify for context package 2015-02-23 11:15:55 +08:00
0c31c2d689 Added support to parse slices of ints and strings in ParseForm func 2015-02-22 22:13:06 +05:00
f988f035e5 redis provider for session and cache support select db 2015-02-16 21:56:32 +08:00
1b4158c15b Merge pull request #1039 from astaxie/revert-1000-group_by_queryseter
Revert "Add GroupBy to QuerySeter"
2015-02-14 20:40:52 +08:00
433e8f2ce3 Revert "Add GroupBy to QuerySeter" 2015-02-14 20:40:43 +08:00
22ba7fdce4 Merge pull request #1000 from pdf/group_by_queryseter
Add GroupBy to QuerySeter
2015-02-14 20:33:06 +08:00
2a0f87e810 Merge pull request #1010 from BlackLee/master
add compare_not/not_nil methods for template
2015-02-14 20:31:18 +08:00
19db4b67f6 Merge pull request #1025 from kongjian/develop
Update task tpl
2015-02-14 20:29:28 +08:00
b1baf4503d beego task list update for task spec list and task run url error 2015-02-04 18:07:31 +08:00
d536f5b8dc Merge pull request #1021 from kmulvey/readme-typo
typos in the readme
2015-02-03 09:07:00 +08:00
1cc1d57f55 development 2015-02-02 09:33:59 -05:00
73370ade90 modular 2015-02-02 09:33:27 -05:00
0d3b7dcd07 Merge pull request #911 from supar/add-column-default-attribute
Add attribute default to the column on create or alter commands. Skip co...
2015-01-16 10:40:11 -08:00
d7fe5ef435 Merge pull request #1004 from fugr/patch-2
Transaction
2015-01-13 11:19:03 -08:00
8bd902814f Transaction
err处理写反了
2015-01-13 11:09:43 +08:00
378356a65e Merge pull request #1001 from johndeng/develop
Fixed the status code issue at error handler.
2015-01-12 09:54:26 -08:00
30871e2617 Fixed the status issue at error handler. 2015-01-10 17:35:35 +08:00
3731088b4a Add GroupBy to QuerySeter
Adds support for GroupBy to QuerySeter SELECT operations.
2015-01-10 15:26:41 +11:00
d46833c6d8 Merge pull request #997 from dockercn/master
增加session模块中的ledisdb的动态配置
2015-01-09 13:58:13 +08:00
18659e16ba add compare_not/not_nil methods for template 2015-01-05 16:38:57 +08:00
5d8187d005 Merge pull request #977 from athurg/patch-1
Fix RequestURI nil caused template parse failed
2014-12-25 11:40:26 +08:00
d961ae4cd8 Fix RequestURI nil caused template parse failed
Sometime RequestURI is not set, e.g. running after a front proxy server.

We should always follow the document's directive, to use Request.URL instead of RequestURI.

Refer: http://golang.org/pkg/net/http/#Request
2014-12-25 11:23:04 +08:00
0e1a0049d1 Merge pull request #971 from athurg/get_request_params_with_default
Support default value for controller’s params get
2014-12-19 16:03:10 +08:00
0c933643e2 improve the empty router 2014-12-19 15:33:51 +08:00
d2c5daa5ee Update comments for controller's GetXXX functions 2014-12-19 15:28:18 +08:00
d3ab157915 fix the cache test 2014-12-19 14:40:16 +08:00
75d28d49c5 Merge pull request #965 from shuoli84/develop
Fix subdomain, add test, space and comment fix
2014-12-19 13:22:36 +08:00
76bb4827d0 Merge pull request #953 from kristen1980/patch-2
Allow absolute path for filesystem cache
2014-12-18 21:24:17 +08:00
3caba06189 Merge pull request #967 from athurg/support_all_type_on_urlfor
Add all type support for UrlFor’s params
2014-12-18 21:14:44 +08:00
572508ddd8 Clean json config. Fix DefaultStrings 2014-12-17 17:02:46 +08:00
e34f8479bb Add all type support for UrlFor’s params 2014-12-17 15:52:48 +08:00
daf85f06f8 Support default value for controller’s params get 2014-12-17 15:23:11 +08:00
22671c524e Fix subdomain, add test, space and comment fix 2014-12-17 12:06:53 +08:00
ab99d5f1e2 Merge pull request #957 from athurg/patch-2
Fix paginator attributes cannot be modified bug
2014-12-11 19:59:50 +08:00
c52f634d9c Fix paginator attributes cannot be modified bug
We can only use SetPaginator to create a pagination.

After that, we always need to modify something, like the totalNum, perPageNum.

These change should be seen in the view.

So we should give the view a pointer than a object.
2014-12-11 16:42:50 +08:00
9c665afc04 improve the error tips 2014-12-08 14:57:45 +08:00
77ed151243 Allow absolute path for filesystem cache
Gives more flexibility by making it an absolute path. A relative path can easily be created by the user.
2014-12-07 10:00:35 -07:00
29d98731c6 add sess_ledis select db config 2014-11-25 14:41:51 -08:00
934dd2e8d2 Merge branch 'master' of https://github.com/astaxie/beego 2014-11-25 14:27:13 -08:00
e65d87974a Merge pull request #940 from hilyjiang/develop
make Content-Type header more human-readable
2014-11-24 23:26:15 +08:00
647e6ae1c4 Added JWT plugin 2014-11-24 23:21:03 +08:00
db04c3cbb4 make Content-Type header more human-readable 2014-11-24 23:12:09 +08:00
802aa16136 Merge pull request #935 from mnhkahn/master
beego1.4.2,beego.AppConfig.Strings与老版本代码不兼容问题
2014-11-24 21:47:12 +08:00
f2df07f630 Merge pull request #933 from rbastic/develop
Reword message about reloading packages..
2014-11-24 13:18:05 +08:00
dc89f844f3 Reword message about reloading packages.. 2014-11-23 18:22:45 +01:00
b80cdef20f Merge pull request #932 from DeanThompson/master
count log file lines
2014-11-23 23:57:27 +08:00
98dcee0643 Merge pull request #926 from xuewuhen/master
SubDomains function bugfixed
2014-11-23 22:57:40 +08:00
0ad75cb5fa Merge pull request #928 from lei-cao/develop
Return the response directly if it's a options PreflightHeader request
2014-11-21 23:22:59 +08:00
6a9d04c269 count log file lines 2014-11-21 18:12:39 +08:00
93ca11f83d Return the response directly if it's a options PreflightHeader request 2014-11-21 01:35:30 +08:00
git
d0b43ef4f5 beego.AppConfig.Strings bug 2014-11-20 16:35:04 +08:00
c9bb9d6a09 SubDomains function bugfixed 2014-11-18 22:54:48 +08:00
f96245786a fix #912 2014-11-08 15:10:47 +08:00
1a1b0c14b9 Add attribute default to the column on create or alter commands. Skip columns which are keys and date or time data type 2014-11-06 17:43:53 +03:00
07c628c7e9 fix the commentsRouter init sequence 2014-11-06 17:30:50 +08:00
1e92d17605 fix the repeat commentsRouters 2014-11-06 16:25:47 +08:00
bb795847da fix the not exist config file application 2014-11-06 11:12:00 +08:00
54ba307f7f change this to short name 2014-11-05 22:40:31 +08:00
950ff91d87 hotfix for parsefiel 2014-11-05 22:23:54 +08:00
b43401b9f6 Merge pull request #907 from astaxie/develop
1.4.1 released
2014-11-04 22:39:03 +08:00
fe50269b3f change 1.4.1 to 1.4.2 2014-11-04 22:38:40 +08:00
000033e2a7 update the test case 2014-11-04 22:07:38 +08:00
15242d89ce simple the session init 2014-11-04 19:08:06 +08:00
76522d43af simple the session 2014-11-04 19:07:49 +08:00
52df1234bd Merge branch 'develop' of https://github.com/astaxie/beego into develop 2014-11-04 19:04:43 +08:00
fc6b9ce009 fix #620 simple the sessionID generate 2014-11-04 19:04:26 +08:00
b9fdd67519 add test case fot date & stringbool 2014-11-04 16:39:17 +08:00
7743eecfd4 support #761
type Test struct {
    Date    time.Time    `form:"Date, 2006-01-02"`
    Save    bool            `form:"Save"`
}
2014-11-04 16:19:46 +08:00
c4d8e4a244 fix #759 2014-11-04 15:29:33 +08:00
9d4ec508bb parse for github.com replace the . to _ 2014-11-04 10:19:30 +08:00
8b747f54bc fix #770 2014-11-03 23:33:11 +08:00
a2428af8a7 compatibility for warn & info function add one more depth 2014-11-03 16:48:45 +08:00
90a7ce5c6a split the file for logs 2014-11-03 16:45:42 +08:00
ef3c7c127b fix the variable 2014-11-03 16:44:05 +08:00
88caf1ed70 if read the log.go then calldepth add 1 2014-11-03 16:43:07 +08:00
304beaf89f update the log call deep 2014-11-03 16:40:08 +08:00
2288ac868c remove the deep Caller 2014-11-03 16:34:36 +08:00
8d797a4a5e file the static filter 2014-11-03 16:14:40 +08:00
10db97b193 add some tips for the admin server start 2014-11-03 15:08:51 +08:00
716962672f fix #751
add config ListenTCP4

when user want to listen on the TCP4, because now almost use the ipv4.
but default lister on the ipv6
2014-11-03 15:06:25 +08:00
90cff5f042 fix #824 2014-11-02 21:01:51 +08:00
da127bbc22 fix #855 #859 2014-10-31 16:31:23 +08:00
945b1da3a8 fix the gofmt 2014-10-31 15:48:57 +08:00
94c84b846f fix the init logger 2014-10-31 09:02:16 +08:00
db43892fe6 improve the Put #896 2014-10-31 00:28:51 +08:00
71149218d1 fix the log level 2014-10-30 17:43:32 +08:00
1636a7271c Revert "fix the log test"
This reverts commit ddbfc25e56.
2014-10-30 16:57:55 +08:00
68c3bdfdd4 Revert "logs:default support fileline"
This reverts commit 1f26852610.
2014-10-30 16:57:48 +08:00
ecd0a5487e fix the import cycle not allowed 2014-10-30 16:12:54 +08:00
fda841208d fix #893 2014-10-30 16:05:48 +08:00
57e62e5e57 update the file upload to io.Pipe 2014-10-30 11:16:09 +08:00
824e3f8f5b fix the only file upload param 2014-10-29 16:00:08 +08:00
1822dd95ac Merge pull request #892 from dockercn/master
Add a beego session backend using LedisDB
2014-10-29 14:18:20 +08:00
ddbfc25e56 fix the log test 2014-10-28 19:34:11 +08:00
1f26852610 logs:default support fileline 2014-10-28 19:33:14 +08:00
0188fb3711 Merge pull request #1 from chliang2030598/master
add session store in ledis
2014-10-27 06:02:19 +00:00
0bcd828d73 add session store in ledis 2014-10-26 22:56:00 -07:00
e11a27f1d1 Merge pull request #888 from astaxie/revert-887-add-column-default-attribute
Revert "Add column default attribute"
2014-10-26 10:41:34 +08:00
90caeb4cf7 Revert "Add column default attribute" 2014-10-26 10:41:22 +08:00
6c9249034d Merge pull request #887 from supar/add-column-default-attribute
Add column default attribute
2014-10-26 10:28:56 +08:00
14114018ea config ini support include 2014-10-24 19:03:27 +08:00
6f5162461e Add column DEFAULT attribute. Do not add if field is key or in
relations.
2014-10-24 14:51:35 +04:00
c34c514bba Skip add DEFAULT if the field is in relations (rel or reverse) 2014-10-24 14:37:46 +04:00
8ac2b9bf66 Merge branch 'master' into develop 2014-10-24 15:10:11 +08:00
2a85c79ce5 Merge pull request #881 from astaxie/revert-870-add-column-default-attribute
Revert "Add column default attribute"
2014-10-24 14:58:27 +08:00
767083bd56 Revert "Add column default attribute" 2014-10-24 14:58:17 +08:00
1a79513293 Merge branch 'master' into develop 2014-10-24 14:50:53 +08:00
c6cb1f92e8 Merge pull request #870 from supar/add-column-default-attribute
Add column default attribute
2014-10-24 14:49:53 +08:00
9c0aad06c5 Merge pull request #880 from chenghuama/patch-3
Update ini.go
2014-10-24 14:15:49 +08:00
180c6aafac Update ini.go
支持BOM格式的ini文件
2014-10-24 13:45:00 +08:00
710f5b6234 fix the test fun for pull request 873 2014-10-20 22:23:29 +08:00
dbf944adce Merge pull request #873 from WithGJR/develop
add new feature to 'renderform' function, user could add HTML id and class now
2014-10-20 22:03:52 +08:00
6c9ff81fc1 fix: if user didn't set id or class, then it won't be displayed in HTML code 2014-10-20 18:59:46 +08:00
ec6383c07d Merge pull request #858 from bsingr/develop
Allow to use fastcgi via standard io.
2014-10-20 18:30:10 +08:00
76db5cded4 fix the init mime 2014-10-20 18:21:17 +08:00
1b3e7de463 add new feature to 'renderform' function, user could add HTML id and class now 2014-10-20 17:49:16 +08:00
ab28edaf25 Fix comma in the switch, fix wronf function name 2014-10-17 13:02:18 +04:00
04431a7a15 Fix function name fmt.Stprintf -> fmt.Sprintf 2014-10-17 12:59:24 +04:00
b00c42b3df Fix undefind variable fieldType 2014-10-17 12:56:44 +04:00
4cae7af3f9 Add attribute DEFAULT '' to the CREAT, ALTER constructors 2014-10-17 12:53:59 +04:00
e4988b714e Add property colDefault to fieldInfo object, set its true if there is
orm configuration default `orm:"default(1)"`
2014-10-17 12:27:53 +04:00
24489df63d Merge pull request #867 from WithGJR/develop
fix router bug: when the request is PUT or DELETE, router can't find the...
2014-10-16 23:07:20 +08:00
fb8e9ae1a3 Merge pull request #868 from reterVision/patch-2
Use SETEX command to set session
2014-10-16 21:42:23 +08:00
1eb9aef687 Use SETEX command to set session
In order to be compatible with older version Redis, use `SETEX` command instead of `SET x y EX 360`.
2014-10-16 20:16:17 +08:00
efc14a1e8d fix router bug with more better way 2014-10-16 18:58:12 +08:00
fa1281002e fix router bug: when the request is PUT or DELETE, router can't find the actual route and will throw 404 page to user 2014-10-16 18:26:01 +08:00
812950b60d Allow to use fastcgi via standard io. 2014-10-13 13:47:44 +02:00
f9e991b538 Merge pull request #853 from tossp/email
支持发送邮件内嵌附件
2014-10-12 11:02:53 +08:00
fc07419938 Update mail.go 2014-10-11 00:42:01 +08:00
d69eee23f0 添加错误返回
不知道英文区的人能否看懂Cnglish。。。
2014-10-11 00:38:31 +08:00
41de7c7db6 fix
修改一个错误。
看到text/template包的写法,和你的想法是一致的。
2014-10-11 00:02:36 +08:00
6a33647f30 修改参数类型
为了保持向后兼容,
2014-10-10 23:40:02 +08:00
e5134873be 支持发送邮件内嵌附件
为*Email.AttachFile和Email.Attach增加了一个参数"id".
当id不为空时,设置头部信息Content-Disposition为inline,并添加Content-ID头的值为id
2014-10-10 14:40:07 +08:00
8d20ea04b0 Merge pull request #852 from pabdavis/statistics-json
[Proposal] Ability to get statistics data unformatted
2014-10-10 10:59:30 +08:00
5c1e8e42b9 Reworked implementation to not return encoded json 2014-10-09 17:07:28 -04:00
ca3e7568a1 Add ability to get statistics in json format 2014-10-09 16:32:56 -04:00
2823167848 Merge pull request #849 from pabdavis/runmode-env
Support run mode set by environment variable
2014-10-10 00:50:16 +08:00
a27f5c0dc0 Remove dependency of third party lib 2014-10-09 09:17:10 -04:00
8af0475251 fix #833 2014-10-09 18:47:22 +08:00
9c07332cfc Update README.md 2014-10-09 09:34:22 +08:00
a06e0f27ad Support run mode set by env var BEEGO_RUNMODE 2014-10-08 15:00:07 -04:00
a760e46f98 Merge pull request #837 from bsingr/develop
Insert pagination utilities from beego/wetalk. Refs #835.
2014-10-08 23:00:46 +08:00
262665f4e5 Remove PaginationController interface and pass context instead. Refs #835. 2014-10-08 16:01:42 +02:00
0b3763cc67 Cleanup pagination documentation. Refs #835. 2014-10-08 16:00:00 +02:00
c147f26cd1 Merge pull request #847 from pabdavis/multifilter-fix2
Changes to handle multi filters on execution pt
2014-10-08 21:24:28 +08:00
1ba7847913 Changing check from nil to len based on slice 2014-10-08 09:21:34 -04:00
52df979aca update the godocs 2014-10-08 14:02:57 +08:00
b6f789c497 Changes to handle multi filters on execution pt 2014-10-07 16:35:30 -04:00
fa6cbc08d9 Document usage of utils/pagination. Refs #835. 2014-10-07 11:23:08 +02:00
c4f8f45da4 Move pagination to utils/pagination. Refs #837, #835. 2014-10-06 11:37:08 +02:00
6fca4a8218 Insert pagination utilities from beego/wetalk. Refs #835. 2014-10-02 11:40:46 +02:00
aae89576c6 fix #814 2014-10-01 22:31:44 +08:00
a907a86476 fix #814 2014-10-01 22:28:49 +08:00
8716185de8 fix #794 2014-10-01 22:10:33 +08:00
31e6133413 beego: improve static file index.html simple code 2014-10-01 08:57:10 +08:00
3a5de83ec2 beego: support router case sensitive 2014-09-28 22:10:43 +08:00
f5f3395560 update the isdir 2014-09-24 14:48:08 +08:00
8164367762 beego: flash add success & Set 2014-09-23 23:54:38 +08:00
e1475b72b9 Merge pull request #826 from SnailKnows/patch-2
Update beego.go
2014-09-23 00:31:21 +08:00
f267ee8a12 fix the same name controller for UrlFor 2014-09-23 00:26:07 +08:00
7e060e6e5c fix the static file dir 2014-09-23 00:03:47 +08:00
727d2f9ea1 fix not found when has mulit static dir
robot &robots
2014-09-22 23:44:50 +08:00
67c0c232a1 Update beego.go 2014-09-20 18:56:46 +08:00
6c62198b59 remove the go style 2014-09-15 23:01:12 +08:00
e48e1ddaa9 Merge pull request #812 from ZhengYang/develop
More SQL keywords added and code cleanup
2014-09-11 20:48:18 +08:00
1f9281c830 minor code refactor 2014-09-11 15:17:48 +08:00
ccab9a7044 add more sql keywords 2014-09-11 13:48:39 +08:00
9013f5c6c7 Merge pull request #808 from ZhengYang/develop
more complete support for sql language
2014-09-09 14:21:49 +08:00
29b7ff84e1 more complete support for sql language 2014-09-09 14:17:12 +08:00
fb0cc55822 update the orm read me 2014-09-09 11:55:28 +08:00
0820e21738 Merge pull request #804 from ZhengYang/develop
QueryBuilder for building SQL queries quickly
2014-09-08 19:24:39 +08:00
38eb29fa7b err msg spell correction 2014-09-08 18:41:42 +08:00
cca0a3f76d name correction: QueryBuilder instead of QueryWriter 2014-09-08 18:31:32 +08:00
f9a9b5a905 new query builder based on driver 2014-09-08 17:56:55 +08:00
c667895ce5 added new querybuilder 2014-09-08 17:47:15 +08:00
b2cdabb8a0 added query builder for orm 2014-09-08 17:37:01 +08:00
647a47517d httplib: fix the header function for User-Agent 2014-09-05 23:21:41 +08:00
f7cd1479ba beego: improve the log debug for running server 2014-09-05 17:04:02 +08:00
fcc359af11 beego: fix the Upper for the _method value 2014-09-04 22:13:03 +08:00
08b3e4191e Merge branch 'master' into develop 2014-09-04 21:58:45 +08:00
4f4f7ce257 beego: fix the router for *.* with other regexp 2014-09-04 21:58:17 +08:00
d06e02474f Merge pull request #795 from mvpmvh/context_params
Context params
2014-09-04 09:11:35 +08:00
4d65330ca1 changing my package namespace to astaxie 2014-09-03 19:47:09 -05:00
2dfe1fc61c Merge pull request #792 from haowang1013/develop
fixed uninitialized return error if StartAndGC fails
2014-09-03 23:21:17 +08:00
29b60d6058 fixed uninitialized return error if StartAndGC fails 2014-09-03 22:43:06 +08:00
6eee223352 beego: fix the Upper for the _method value 2014-09-03 09:25:34 +08:00
db51ddab96 GetInt(), GetInt8(), GetInt16(), GetInt32(), GetInt64() and Example tests 2014-08-23 20:24:29 -05:00
baf2c63d5c Merge branch 'astaxie-master' 2014-08-23 10:09:37 -05:00
507 changed files with 57979 additions and 15367 deletions

17
.github/ISSUE_TEMPLATE vendored Normal file
View File

@ -0,0 +1,17 @@
Please answer these questions before submitting your issue. Thanks!
1. What version of Go and beego are you using (`bee version`)?
2. What operating system and processor architecture are you using (`go env`)?
3. What did you do?
If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
4. What did you expect to see?
5. What did you see instead?

19
.github/workflows/stale.yml vendored Normal file
View File

@ -0,0 +1,19 @@
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'

8
.gitignore vendored
View File

@ -1,4 +1,12 @@
.idea
.vscode
.DS_Store
*.swp
*.swo
beego.iml
_beeTmp/
_beeTmp2/
pkg/_beeTmp/
pkg/_beeTmp2/
test/tmp/

View File

@ -1,16 +0,0 @@
{
"file_line": 500,
"func_line": 80,
"params_num":4,
"results_num":3,
"formated": true,
"pkg_name": true,
"camel_name":true,
"ignore":[
"a/*",
"b/*/c/*.go"
],
"fatal":[
"formated"
]
}

105
.travis.yml Normal file
View File

@ -0,0 +1,105 @@
language: go
go:
- "1.14.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"
install:
- go get github.com/lib/pq
- go get github.com/go-sql-driver/mysql
- go get github.com/mattn/go-sqlite3
- go get github.com/bradfitz/gomemcache/memcache
- go get github.com/gomodule/redigo/redis
- go get github.com/beego/x2j
- go get github.com/couchbase/go-couchbase
- go get github.com/beego/goyaml2
- go get gopkg.in/yaml.v2
- go get github.com/belogik/goes
- go get github.com/ledisdb/ledisdb
- go get github.com/ssdb/gossdb/ssdb
- go get github.com/cloudflare/golz4
- go get github.com/gogo/protobuf/proto
- go get github.com/Knetic/govaluate
- go get github.com/casbin/casbin
- go get github.com/elazarl/go-bindata-assetfs
- go get github.com/OwnLocal/goes
- go get github.com/shiena/ansicolor
- go get -u honnef.co/go/tools/cmd/staticcheck
- go get -u github.com/mdempsky/unconvert
- go get -u github.com/gordonklaus/ineffassign
- 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"
- sh -c "go get github.com/golang/lint/golint; golint ./...;"
- sh -c "go list ./... | grep -v vendor | xargs go vet -v"
- mkdir -p res/var
- ./ssdb/ssdb-server ./ssdb/ssdb.conf -d
after_script:
- killall -w ssdb-server
- rm -rf ./res/var/*
script:
- go test ./...
- 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"

93
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,93 @@
# Contributing to beego
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.
## 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.
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.
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.
Also when filing an issue, make sure to answer these five questions:
- What version of beego are you using (bee version)?
- What operating system and processor architecture are you using?
- What did you do?
- What did you expect to see?
- What did you see instead?
### 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.
Also, if you don't know how to use it. please make sure you have read through
the docs in http://beego.me/docs

255
README.md
View File

@ -1,16 +1,250 @@
## 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/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)
[![Build Status](https://drone.io/github.com/astaxie/beego/status.png)](https://drone.io/github.com/astaxie/beego/latest)
[![GoDoc](https://godoc.org/github.com/astaxie/beego?status.svg)](https://godoc.org/github.com/astaxie/beego)
beego is an open-source, high-performance, modularity, full-stack web framework.
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.
More info [beego.me](http://beego.me)
###### More info at [beego.me](http://beego.me).
## Installation
## 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
#### Create file `hello.go`
```go
package main
import "github.com/astaxie/beego/server/web"
func main(){
web.Run()
}
```
#### Build and run
go build hello.go
./hello
#### Go to [http://localhost:8080](http://localhost:8080)
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
@ -19,19 +253,22 @@ More info [beego.me](http://beego.me)
* Auto API documents
* Annotation router
* Namespace
* Powerful develop tools
* Powerful development tools
* Full stack for Web & API
## Documentation
* [English](http://beego.me/docs/intro/)
* [中文文档](http://beego.me/docs/intro/)
* [Русский](http://beego.me/docs/intro/)
## 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)
* QQ Group Group ID:523992905
## LICENSE
## License
beego is licensed under the Apache Licence, Version 2.0
beego source code is licensed under the Apache Licence, Version 2.0
(http://www.apache.org/licenses/LICENSE-2.0.html).

45
adapter/admin.go Normal file
View File

@ -0,0 +1,45 @@
// 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())
}

262
adapter/app.go Normal file
View File

@ -0,0 +1,262 @@
// 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...))
}

77
adapter/beego.go Normal file
View File

@ -0,0 +1,77 @@
// 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)
}

27
adapter/build_info.go Normal file
View File

@ -0,0 +1,27 @@
// 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

@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cache provide a Cache interface and some implement engine
// Usage:
//
// import(
@ -22,7 +23,7 @@
//
// Use it like this:
//
// bm.Put("astaxie", 1, 10)
// bm.Put("astaxie", 1, 10 * time.Second)
// bm.Get("astaxie")
// bm.IsExist("astaxie")
// bm.Delete("astaxie")
@ -32,13 +33,14 @@ package cache
import (
"fmt"
"time"
)
// Cache interface contains all behaviors for cache adapter.
// usage:
// cache.Register("file",cache.NewFileCache()) // this operation is run in init method of file.go.
// cache.Register("file",cache.NewFileCache) // this operation is run in init method of file.go.
// c,err := cache.NewCache("file","{....}")
// c.Put("key",value,3600)
// c.Put("key",value, 3600 * time.Second)
// v := c.Get("key")
//
// c.Incr("counter") // now is 1
@ -47,8 +49,10 @@ import (
type Cache interface {
// get cached value by key.
Get(key string) interface{}
// GetMulti is a batch version of Get.
GetMulti(keys []string) []interface{}
// set cached value with key and expire time.
Put(key string, val interface{}, timeout int64) error
Put(key string, val interface{}, timeout time.Duration) error
// delete cached value by key.
Delete(key string) error
// increase cached int value by key, as a counter.
@ -63,12 +67,15 @@ type Cache interface {
StartAndGC(config string) error
}
var adapters = make(map[string]Cache)
// Instance is a function create a new Cache Instance
type Instance func() Cache
var adapters = make(map[string]Instance)
// Register makes a cache adapter available by the adapter name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, adapter Cache) {
func Register(name string, adapter Instance) {
if adapter == nil {
panic("cache: Register adapter is nil")
}
@ -78,16 +85,17 @@ func Register(name string, adapter Cache) {
adapters[name] = adapter
}
// Create a new cache driver by adapter name and config string.
// NewCache Create a new cache driver by adapter name and config string.
// config need to be correct JSON as string: {"interval":360}.
// it will start gc automatically.
func NewCache(adapterName, config string) (adapter Cache, e error) {
adapter, ok := adapters[adapterName]
func NewCache(adapterName, config string) (adapter Cache, err error) {
instanceFunc, ok := adapters[adapterName]
if !ok {
e = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName)
err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName)
return
}
err := adapter.StartAndGC(config)
adapter = instanceFunc()
err = adapter.StartAndGC(config)
if err != nil {
adapter = nil
}

117
adapter/cache/cache_adapter.go vendored Normal file
View File

@ -0,0 +1,117 @@
// 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,
}
}

View File

@ -15,16 +15,41 @@
package cache
import (
"os"
"sync"
"testing"
"time"
)
func TestCacheIncr(t *testing.T) {
bm, err := NewCache("memory", `{"interval":20}`)
if err != nil {
t.Error("init err")
}
//timeoutDuration := 10 * time.Second
bm.Put("edwardhey", 0, time.Second*20)
wg := sync.WaitGroup{}
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
bm.Incr("edwardhey")
}()
}
wg.Wait()
if bm.Get("edwardhey").(int) != 10 {
t.Error("Incr err")
}
}
func TestCache(t *testing.T) {
bm, err := NewCache("memory", `{"interval":20}`)
if err != nil {
t.Error("init err")
}
if err = bm.Put("astaxie", 1, 10); err != nil {
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
@ -41,7 +66,7 @@ func TestCache(t *testing.T) {
t.Error("check err")
}
if err = bm.Put("astaxie", 1, 10); err != nil {
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
@ -64,14 +89,44 @@ func TestCache(t *testing.T) {
if bm.IsExist("astaxie") {
t.Error("delete err")
}
//test GetMulti
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
t.Error("check err")
}
if v := bm.Get("astaxie"); v.(string) != "author" {
t.Error("get err")
}
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie1") {
t.Error("check err")
}
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if vv[0].(string) != "author" {
t.Error("GetMulti ERROR")
}
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
}
func TestFileCache(t *testing.T) {
bm, err := NewCache("file", `{"CachePath":"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}`)
bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`)
if err != nil {
t.Error("init err")
}
if err = bm.Put("astaxie", 1, 10); err != nil {
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
@ -101,15 +156,36 @@ func TestFileCache(t *testing.T) {
if bm.IsExist("astaxie") {
t.Error("delete err")
}
//test string
if err = bm.Put("astaxie", "author", 10); err != nil {
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
t.Error("check err")
}
if v := bm.Get("astaxie"); v.(string) != "author" {
t.Error("get err")
}
//test GetMulti
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie1") {
t.Error("check err")
}
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if vv[0].(string) != "author" {
t.Error("GetMulti ERROR")
}
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
os.RemoveAll("cache")
}

44
adapter/cache/conv.go vendored Normal file
View File

@ -0,0 +1,44 @@
// 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)
}

View File

@ -27,7 +27,7 @@ func TestGetString(t *testing.T) {
if "test2" != GetString(t2) {
t.Error("get string from byte array error")
}
var t3 int = 1
var t3 = 1
if "1" != GetString(t3) {
t.Error("get string from int error")
}
@ -35,7 +35,7 @@ func TestGetString(t *testing.T) {
if "1" != GetString(t4) {
t.Error("get string from int64 error")
}
var t5 float64 = 1.1
var t5 = 1.1
if "1.1" != GetString(t5) {
t.Error("get string from float64 error")
}
@ -46,7 +46,7 @@ func TestGetString(t *testing.T) {
}
func TestGetInt(t *testing.T) {
var t1 int = 1
var t1 = 1
if 1 != GetInt(t1) {
t.Error("get int from int error")
}
@ -69,7 +69,7 @@ func TestGetInt(t *testing.T) {
func TestGetInt64(t *testing.T) {
var i int64 = 1
var t1 int = 1
var t1 = 1
if i != GetInt64(t1) {
t.Error("get int64 from int error")
}
@ -91,12 +91,12 @@ func TestGetInt64(t *testing.T) {
}
func TestGetFloat64(t *testing.T) {
var f float64 = 1.11
var f = 1.11
var t1 float32 = 1.11
if f != GetFloat64(t1) {
t.Error("get float64 from float32 error")
}
var t2 float64 = 1.11
var t2 = 1.11
if f != GetFloat64(t2) {
t.Error("get float64 from float64 error")
}
@ -106,7 +106,7 @@ func TestGetFloat64(t *testing.T) {
}
var f2 float64 = 1
var t4 int = 1
var t4 = 1
if f2 != GetFloat64(t4) {
t.Error("get float64 from int error")
}
@ -118,33 +118,18 @@ func TestGetFloat64(t *testing.T) {
func TestGetBool(t *testing.T) {
var t1 = true
if true != GetBool(t1) {
if !GetBool(t1) {
t.Error("get bool from bool error")
}
var t2 = "true"
if true != GetBool(t2) {
if !GetBool(t2) {
t.Error("get bool from string error")
}
if false != GetBool(nil) {
if GetBool(nil) {
t.Error("get bool from nil error")
}
}
func TestGetByteArray(t *testing.T) {
var b = []byte("test")
var t1 = []byte("test")
if !byteArrayEquals(b, getByteArray(t1)) {
t.Error("get byte array from byte array error")
}
var t2 = "test"
if !byteArrayEquals(b, getByteArray(t2)) {
t.Error("get byte array from string error")
}
if nil != getByteArray(nil) {
t.Error("get byte array from nil error")
}
}
func byteArrayEquals(a []byte, b []byte) bool {
if len(a) != len(b) {
return false

30
adapter/cache/file.go vendored Normal file
View File

@ -0,0 +1,30 @@
// 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)
}

44
adapter/cache/memcache/memcache.go vendored Normal file
View File

@ -0,0 +1,44 @@
// 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)
}

114
adapter/cache/memcache/memcache_test.go vendored Normal file
View File

@ -0,0 +1,114 @@
// 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
import (
"fmt"
"os"
"strconv"
"testing"
"time"
"github.com/astaxie/beego/adapter/cache"
)
func TestMemcacheCache(t *testing.T) {
addr := os.Getenv("MEMCACHE_ADDR")
if addr == "" {
addr = "127.0.0.1:11211"
}
bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr))
if err != nil {
t.Error("init err")
}
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", "1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
t.Error("check err")
}
time.Sleep(11 * time.Second)
if bm.IsExist("astaxie") {
t.Error("check err")
}
if err = bm.Put("astaxie", "1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 {
t.Error("get err")
}
if err = bm.Incr("astaxie"); err != nil {
t.Error("Incr Error", err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 2 {
t.Error("get err")
}
if err = bm.Decr("astaxie"); err != nil {
t.Error("Decr Error", err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 {
t.Error("get err")
}
bm.Delete("astaxie")
if bm.IsExist("astaxie") {
t.Error("delete err")
}
// test string
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
t.Error("check err")
}
if v := bm.Get("astaxie").([]byte); string(v) != "author" {
t.Error("get err")
}
// test GetMulti
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie1") {
t.Error("check err")
}
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if string(vv[0].([]byte)) != "author" && string(vv[0].([]byte)) != "author1" {
t.Error("GetMulti ERROR")
}
if string(vv[1].([]byte)) != "author1" && string(vv[1].([]byte)) != "author" {
t.Error("GetMulti ERROR")
}
// test clear all
if err = bm.ClearAll(); err != nil {
t.Error("clear all err")
}
}

28
adapter/cache/memory.go vendored Normal file
View File

@ -0,0 +1,28 @@
// 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)
}

49
adapter/cache/redis/redis.go vendored Normal file
View File

@ -0,0 +1,49 @@
// 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

@ -15,32 +15,40 @@
package redis
import (
"fmt"
"os"
"testing"
"time"
"github.com/garyburd/redigo/redis"
"github.com/gomodule/redigo/redis"
"github.com/astaxie/beego/cache"
"github.com/astaxie/beego/adapter/cache"
)
func TestRedisCache(t *testing.T) {
bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`)
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {
redisAddr = "127.0.0.1:6379"
}
bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, redisAddr))
if err != nil {
t.Error("init err")
}
if err = bm.Put("astaxie", 1, 10); err != nil {
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
t.Error("check err")
}
time.Sleep(10 * time.Second)
time.Sleep(11 * time.Second)
if bm.IsExist("astaxie") {
t.Error("check err")
}
if err = bm.Put("astaxie", 1, 10); err != nil {
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
@ -67,8 +75,9 @@ func TestRedisCache(t *testing.T) {
if bm.IsExist("astaxie") {
t.Error("delete err")
}
//test string
if err = bm.Put("astaxie", "author", 10); err != nil {
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie") {
@ -78,8 +87,49 @@ func TestRedisCache(t *testing.T) {
if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" {
t.Error("get err")
}
//test GetMulti
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if !bm.IsExist("astaxie1") {
t.Error("check err")
}
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if v, _ := redis.String(vv[0], nil); v != "author" {
t.Error("GetMulti ERROR")
}
if v, _ := redis.String(vv[1], nil); v != "author1" {
t.Error("GetMulti ERROR")
}
// test clear all
if err = bm.ClearAll(); err != nil {
t.Error("clear all err")
}
}
func TestCache_Scan(t *testing.T) {
timeoutDuration := 10 * time.Second
// init
bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`)
if err != nil {
t.Error("init err")
}
// insert all
for i := 0; i < 10000; i++ {
if err = bm.Put(fmt.Sprintf("astaxie%d", i), fmt.Sprintf("author%d", i), timeoutDuration); err != nil {
t.Error("set Error", err)
}
}
// clear all
if err = bm.ClearAll(); err != nil {
t.Error("clear all err")
}
}

15
adapter/cache/ssdb/ssdb.go vendored Normal file
View File

@ -0,0 +1,15 @@
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)
}

111
adapter/cache/ssdb/ssdb_test.go vendored Normal file
View File

@ -0,0 +1,111 @@
package ssdb
import (
"fmt"
"os"
"strconv"
"testing"
"time"
"github.com/astaxie/beego/adapter/cache"
)
func TestSsdbcacheCache(t *testing.T) {
ssdbAddr := os.Getenv("SSDB_ADDR")
if ssdbAddr == "" {
ssdbAddr = "127.0.0.1:8888"
}
ssdb, err := cache.NewCache("ssdb", fmt.Sprintf(`{"conn": "%s"}`, ssdbAddr))
if err != nil {
t.Error("init err")
}
// test put and exist
if ssdb.IsExist("ssdb") {
t.Error("check err")
}
timeoutDuration := 10 * time.Second
//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)
}
if !ssdb.IsExist("ssdb") {
t.Error("check err")
}
// Get test done
if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if v := ssdb.Get("ssdb"); v != "ssdb" {
t.Error("get Error")
}
//inc/dec test done
if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if err = ssdb.Incr("ssdb"); err != nil {
t.Error("incr Error", err)
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 {
t.Error("get err")
}
if err = ssdb.Decr("ssdb"); err != nil {
t.Error("decr error")
}
// test del
if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 {
t.Error("get err")
}
if err := ssdb.Delete("ssdb"); err == nil {
if ssdb.IsExist("ssdb") {
t.Error("delete err")
}
}
//test string
if err = ssdb.Put("ssdb", "ssdb", -10*time.Second); err != nil {
t.Error("set Error", err)
}
if !ssdb.IsExist("ssdb") {
t.Error("check err")
}
if v := ssdb.Get("ssdb").(string); v != "ssdb" {
t.Error("get err")
}
//test GetMulti done
if err = ssdb.Put("ssdb1", "ssdb1", -10*time.Second); err != nil {
t.Error("set Error", err)
}
if !ssdb.IsExist("ssdb1") {
t.Error("check err")
}
vv := ssdb.GetMulti([]string{"ssdb", "ssdb1"})
if len(vv) != 2 {
t.Error("getmulti error")
}
if vv[0].(string) != "ssdb" {
t.Error("getmulti error")
}
if vv[1].(string) != "ssdb1" {
t.Error("getmulti error")
}
// test clear all done
if err = ssdb.ClearAll(); err != nil {
t.Error("clear all err")
}
if ssdb.IsExist("ssdb") || ssdb.IsExist("ssdb1") {
t.Error("check err")
}
}

177
adapter/config.go Normal file
View File

@ -0,0 +1,177 @@
// 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)
}

191
adapter/config/adapter.go Normal file
View File

@ -0,0 +1,191 @@
// 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")
}
func (o *oldToNewConfigerAdapter) Sub(key string) (config.Configer, error) {
return nil, errors.New("unsupported operation, please use actual config.Configer")
}
func (o *oldToNewConfigerAdapter) OnChange(key string, fn func(value string)) {
// do nothing
}
func (o *oldToNewConfigerAdapter) SaveConfigFile(filename string) error {
return o.delegate.SaveConfigFile(filename)
}
type oldToNewConfigAdapter struct {
delegate Config
}
func (o *oldToNewConfigAdapter) Parse(key string) (config.Configer, error) {
old, err := o.delegate.Parse(key)
if err != nil {
return nil, err
}
return &oldToNewConfigerAdapter{delegate: old}, nil
}
func (o *oldToNewConfigAdapter) ParseData(data []byte) (config.Configer, error) {
old, err := o.delegate.ParseData(data)
if err != nil {
return nil, err
}
return &oldToNewConfigerAdapter{delegate: old}, nil
}

151
adapter/config/config.go Normal file
View File

@ -0,0 +1,151 @@
// 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 config is used to parse config.
// Usage:
// import "github.com/astaxie/beego/config"
// Examples.
//
// cnf, err := config.NewConfig("ini", "config.conf")
//
// cnf APIS:
//
// cnf.Set(key, val string) error
// cnf.String(key string) string
// cnf.Strings(key string) []string
// cnf.Int(key string) (int, error)
// cnf.Int64(key string) (int64, error)
// cnf.Bool(key string) (bool, error)
// cnf.Float(key string) (float64, error)
// cnf.DefaultString(key string, defaultVal string) string
// cnf.DefaultStrings(key string, defaultVal []string) []string
// cnf.DefaultInt(key string, defaultVal int) int
// cnf.DefaultInt64(key string, defaultVal int64) int64
// cnf.DefaultBool(key string, defaultVal bool) bool
// cnf.DefaultFloat(key string, defaultVal float64) float64
// cnf.DIY(key string) (interface{}, error)
// cnf.GetSection(section string) (map[string]string, error)
// cnf.SaveConfigFile(filename string) error
// More docs http://beego.me/docs/module/config.md
package config
import (
"github.com/astaxie/beego/core/config"
)
// Configer defines how to get and set value from configuration raw data.
type Configer interface {
Set(key, val string) error // support section::key type in given key when using ini type.
String(key string) string // support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same.
Strings(key string) []string // get string slice
Int(key string) (int, error)
Int64(key string) (int64, error)
Bool(key string) (bool, error)
Float(key string) (float64, error)
DefaultString(key string, defaultVal string) string // support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same.
DefaultStrings(key string, defaultVal []string) []string // get string slice
DefaultInt(key string, defaultVal int) int
DefaultInt64(key string, defaultVal int64) int64
DefaultBool(key string, defaultVal bool) bool
DefaultFloat(key string, defaultVal float64) float64
DIY(key string) (interface{}, error)
GetSection(section string) (map[string]string, error)
SaveConfigFile(filename string) error
}
// Config is the adapter interface for parsing config file to get raw data to Configer.
type Config interface {
Parse(key string) (Configer, error)
ParseData(data []byte) (Configer, error)
}
var adapters = make(map[string]Config)
// Register makes a config adapter available by the adapter name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, adapter Config) {
config.Register(name, &oldToNewConfigAdapter{delegate: adapter})
}
// NewConfig adapterName is ini/json/xml/yaml.
// filename is the config file path.
func NewConfig(adapterName, filename string) (Configer, error) {
cfg, err := config.NewConfig(adapterName, filename)
if err != nil {
return nil, err
}
// it was registered by using Register method
res, ok := cfg.(*oldToNewConfigerAdapter)
if ok {
return res.delegate, nil
}
return &newToOldConfigerAdapter{
delegate: cfg,
}, nil
}
// NewConfigData adapterName is ini/json/xml/yaml.
// data is the config data.
func NewConfigData(adapterName string, data []byte) (Configer, error) {
cfg, err := config.NewConfigData(adapterName, data)
if err != nil {
return nil, err
}
// it was registered by using Register method
res, ok := cfg.(*oldToNewConfigerAdapter)
if ok {
return res.delegate, nil
}
return &newToOldConfigerAdapter{
delegate: cfg,
}, nil
}
// ExpandValueEnvForMap convert all string value with environment variable.
func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
return config.ExpandValueEnvForMap(m)
}
// ExpandValueEnv returns value of convert with environment variable.
//
// Return environment variable if value start with "${" and end with "}".
// Return default value if environment variable is empty or not exist.
//
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples:
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie".
func ExpandValueEnv(value string) string {
return config.ExpandValueEnv(value)
}
// ParseBool returns the boolean value represented by the string.
//
// It accepts 1, 1.0, t, T, TRUE, true, True, YES, yes, Yes,Y, y, ON, on, On,
// 0, 0.0, f, F, FALSE, false, False, NO, no, No, N,n, OFF, off, Off.
// Any other value returns an error.
func ParseBool(val interface{}) (value bool, err error) {
return config.ParseBool(val)
}
// ToString converts values of any type to string.
func ToString(x interface{}) string {
return config.ToString(x)
}

View File

@ -0,0 +1,55 @@
// Copyright 2016 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 config
import (
"os"
"testing"
)
func TestExpandValueEnv(t *testing.T) {
testCases := []struct {
item string
want string
}{
{"", ""},
{"$", "$"},
{"{", "{"},
{"{}", "{}"},
{"${}", ""},
{"${|}", ""},
{"${}", ""},
{"${{}}", ""},
{"${{||}}", "}"},
{"${pwd||}", ""},
{"${pwd||}", ""},
{"${pwd||}", ""},
{"${pwd||}}", "}"},
{"${pwd||{{||}}}", "{{||}}"},
{"${GOPATH}", os.Getenv("GOPATH")},
{"${GOPATH||}", os.Getenv("GOPATH")},
{"${GOPATH||root}", os.Getenv("GOPATH")},
{"${GOPATH_NOT||root}", "root"},
{"${GOPATH_NOT||||root}", "||root"},
}
for _, c := range testCases {
if got := ExpandValueEnv(c.item); got != c.want {
t.Errorf("expand value error, item %q want %q, got %q", c.item, c.want, got)
}
}
}

50
adapter/config/env/env.go vendored Normal file
View File

@ -0,0 +1,50 @@
// Copyright 2014 beego Author. All Rights Reserved.
// Copyright 2017 Faissal Elamraoui. 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 env is used to parse environment.
package env
import (
"github.com/astaxie/beego/core/config/env"
)
// Get returns a value by key.
// If the key does not exist, the default value will be returned.
func Get(key string, defVal string) string {
return env.Get(key, defVal)
}
// MustGet returns a value by key.
// If the key does not exist, it will return an error.
func MustGet(key string) (string, error) {
return env.MustGet(key)
}
// Set sets a value in the ENV copy.
// This does not affect the child process environment.
func Set(key string, value string) {
env.Set(key, value)
}
// MustSet sets a value in the ENV copy and the child process environment.
// It returns an error in case the set operation failed.
func MustSet(key string, value string) error {
return env.MustSet(key, value)
}
// GetAll returns all keys/values in the current child process environment.
func GetAll() map[string]string {
return env.GetAll()
}

75
adapter/config/env/env_test.go vendored Normal file
View File

@ -0,0 +1,75 @@
// Copyright 2014 beego Author. All Rights Reserved.
// Copyright 2017 Faissal Elamraoui. 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 env
import (
"os"
"testing"
)
func TestEnvGet(t *testing.T) {
gopath := Get("GOPATH", "")
if gopath != os.Getenv("GOPATH") {
t.Error("expected GOPATH not empty.")
}
noExistVar := Get("NOEXISTVAR", "foo")
if noExistVar != "foo" {
t.Errorf("expected NOEXISTVAR to equal foo, got %s.", noExistVar)
}
}
func TestEnvMustGet(t *testing.T) {
gopath, err := MustGet("GOPATH")
if err != nil {
t.Error(err)
}
if gopath != os.Getenv("GOPATH") {
t.Errorf("expected GOPATH to be the same, got %s.", gopath)
}
_, err = MustGet("NOEXISTVAR")
if err == nil {
t.Error("expected error to be non-nil")
}
}
func TestEnvSet(t *testing.T) {
Set("MYVAR", "foo")
myVar := Get("MYVAR", "bar")
if myVar != "foo" {
t.Errorf("expected MYVAR to equal foo, got %s.", myVar)
}
}
func TestEnvMustSet(t *testing.T) {
err := MustSet("FOO", "bar")
if err != nil {
t.Error(err)
}
fooVar := os.Getenv("FOO")
if fooVar != "bar" {
t.Errorf("expected FOO variable to equal bar, got %s.", fooVar)
}
}
func TestEnvGetAll(t *testing.T) {
envMap := GetAll()
if len(envMap) == 0 {
t.Error("expected environment not empty.")
}
}

25
adapter/config/fake.go Normal file
View File

@ -0,0 +1,25 @@
// 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 config
import (
"github.com/astaxie/beego/core/config"
)
// NewFakeConfig return a fake Configer
func NewFakeConfig() Configer {
new := config.NewFakeConfig()
return &newToOldConfigerAdapter{delegate: new}
}

190
adapter/config/ini_test.go Normal file
View File

@ -0,0 +1,190 @@
// 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 config
import (
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
)
func TestIni(t *testing.T) {
var (
inicontext = `
;comment one
#comment two
appname = beeapi
httpport = 8080
mysqlport = 3600
PI = 3.1415976
runmode = "dev"
autorender = false
copyrequestbody = true
session= on
cookieon= off
newreg = OFF
needlogin = ON
enableSession = Y
enableCookie = N
flag = 1
path1 = ${GOPATH}
path2 = ${GOPATH||/home/go}
[demo]
key1="asta"
key2 = "xie"
CaseInsensitive = true
peers = one;two;three
password = ${GOPATH}
`
keyValue = map[string]interface{}{
"appname": "beeapi",
"httpport": 8080,
"mysqlport": int64(3600),
"pi": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"session": true,
"cookieon": false,
"newreg": false,
"needlogin": true,
"enableSession": true,
"enableCookie": false,
"flag": true,
"path1": os.Getenv("GOPATH"),
"path2": os.Getenv("GOPATH"),
"demo::key1": "asta",
"demo::key2": "xie",
"demo::CaseInsensitive": true,
"demo::peers": []string{"one", "two", "three"},
"demo::password": os.Getenv("GOPATH"),
"null": "",
"demo2::key1": "",
"error": "",
"emptystrings": []string{},
}
)
f, err := os.Create("testini.conf")
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(inicontext)
if err != nil {
f.Close()
t.Fatal(err)
}
f.Close()
defer os.Remove("testini.conf")
iniconf, err := NewConfig("ini", "testini.conf")
if err != nil {
t.Fatal(err)
}
for k, v := range keyValue {
var err error
var value interface{}
switch v.(type) {
case int:
value, err = iniconf.Int(k)
case int64:
value, err = iniconf.Int64(k)
case float64:
value, err = iniconf.Float(k)
case bool:
value, err = iniconf.Bool(k)
case []string:
value = iniconf.Strings(k)
case string:
value = iniconf.String(k)
default:
value, err = iniconf.DIY(k)
}
if err != nil {
t.Fatalf("get key %q value fail,err %s", k, err)
} else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) {
t.Fatalf("get key %q value, want %v got %v .", k, v, value)
}
}
if err = iniconf.Set("name", "astaxie"); err != nil {
t.Fatal(err)
}
if iniconf.String("name") != "astaxie" {
t.Fatal("get name error")
}
}
func TestIniSave(t *testing.T) {
const (
inicontext = `
app = app
;comment one
#comment two
# comment three
appname = beeapi
httpport = 8080
# DB Info
# enable db
[dbinfo]
# db type name
# suport mysql,sqlserver
name = mysql
`
saveResult = `
app=app
#comment one
#comment two
# comment three
appname=beeapi
httpport=8080
# DB Info
# enable db
[dbinfo]
# db type name
# suport mysql,sqlserver
name=mysql
`
)
cfg, err := NewConfigData("ini", []byte(inicontext))
if err != nil {
t.Fatal(err)
}
name := "newIniConfig.ini"
if err := cfg.SaveConfigFile(name); err != nil {
t.Fatal(err)
}
defer os.Remove(name)
if data, err := ioutil.ReadFile(name); err != nil {
t.Fatal(err)
} else {
cfgData := string(data)
datas := strings.Split(saveResult, "\n")
for _, line := range datas {
if !strings.Contains(cfgData, line+"\n") {
t.Fatalf("different after save ini config file. need contains %q", line)
}
}
}
}

View File

@ -12,4 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package testing
package config
import (
_ "github.com/astaxie/beego/core/config/json"
)

View File

@ -15,33 +15,14 @@
package config
import (
"fmt"
"os"
"testing"
)
var jsoncontext = `{
"appname": "beeapi",
"httpport": 8080,
"mysqlport": 3600,
"PI": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"database": {
"host": "host",
"port": "port",
"database": "database",
"username": "username",
"password": "password",
"conns":{
"maxconnection":12,
"autoconnect":true,
"connectioninfo":"info"
}
}
}`
func TestJsonStartsWithArray(t *testing.T) {
var jsoncontextwitharray = `[
const jsoncontextwitharray = `[
{
"url": "user",
"serviceAPI": "http://www.test.com/user"
@ -51,8 +32,6 @@ var jsoncontextwitharray = `[
"serviceAPI": "http://www.test.com/employee"
}
]`
func TestJsonStartsWithArray(t *testing.T) {
f, err := os.Create("testjsonWithArray.conf")
if err != nil {
t.Fatal(err)
@ -89,6 +68,70 @@ func TestJsonStartsWithArray(t *testing.T) {
}
func TestJson(t *testing.T) {
var (
jsoncontext = `{
"appname": "beeapi",
"testnames": "foo;bar",
"httpport": 8080,
"mysqlport": 3600,
"PI": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"session": "on",
"cookieon": "off",
"newreg": "OFF",
"needlogin": "ON",
"enableSession": "Y",
"enableCookie": "N",
"flag": 1,
"path1": "${GOPATH}",
"path2": "${GOPATH||/home/go}",
"database": {
"host": "host",
"port": "port",
"database": "database",
"username": "username",
"password": "${GOPATH}",
"conns":{
"maxconnection":12,
"autoconnect":true,
"connectioninfo":"info",
"root": "${GOPATH}"
}
}
}`
keyValue = map[string]interface{}{
"appname": "beeapi",
"testnames": []string{"foo", "bar"},
"httpport": 8080,
"mysqlport": int64(3600),
"PI": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"session": true,
"cookieon": false,
"newreg": false,
"needlogin": true,
"enableSession": true,
"enableCookie": false,
"flag": true,
"path1": os.Getenv("GOPATH"),
"path2": os.Getenv("GOPATH"),
"database::host": "host",
"database::port": "port",
"database::database": "database",
"database::password": os.Getenv("GOPATH"),
"database::conns::maxconnection": 12,
"database::conns::autoconnect": true,
"database::conns::connectioninfo": "info",
"database::conns::root": os.Getenv("GOPATH"),
"unknown": "",
}
)
f, err := os.Create("testjson.conf")
if err != nil {
t.Fatal(err)
@ -104,31 +147,32 @@ func TestJson(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if jsonconf.String("appname") != "beeapi" {
t.Fatal("appname not equal to beeapi")
}
if port, err := jsonconf.Int("httpport"); err != nil || port != 8080 {
t.Error(port)
t.Fatal(err)
}
if port, err := jsonconf.Int64("mysqlport"); err != nil || port != 3600 {
t.Error(port)
t.Fatal(err)
}
if pi, err := jsonconf.Float("PI"); err != nil || pi != 3.1415976 {
t.Error(pi)
t.Fatal(err)
}
if jsonconf.String("runmode") != "dev" {
t.Fatal("runmode not equal to dev")
}
if v, err := jsonconf.Bool("autorender"); err != nil || v != false {
t.Error(v)
t.Fatal(err)
}
if v, err := jsonconf.Bool("copyrequestbody"); err != nil || v != true {
t.Error(v)
t.Fatal(err)
for k, v := range keyValue {
var err error
var value interface{}
switch v.(type) {
case int:
value, err = jsonconf.Int(k)
case int64:
value, err = jsonconf.Int64(k)
case float64:
value, err = jsonconf.Float(k)
case bool:
value, err = jsonconf.Bool(k)
case []string:
value = jsonconf.Strings(k)
case string:
value = jsonconf.String(k)
default:
value, err = jsonconf.DIY(k)
}
if err != nil {
t.Fatalf("get key %q value fatal,%v err %s", k, v, err)
} else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) {
t.Fatalf("get key %q value, want %v got %v .", k, v, value)
}
}
if err = jsonconf.Set("name", "astaxie"); err != nil {
t.Fatal(err)
@ -136,15 +180,7 @@ func TestJson(t *testing.T) {
if jsonconf.String("name") != "astaxie" {
t.Fatal("get name error")
}
if jsonconf.String("database::host") != "host" {
t.Fatal("get database::host error")
}
if jsonconf.String("database::conns::connectioninfo") != "info" {
t.Fatal("get database::conns::connectioninfo error")
}
if maxconnection, err := jsonconf.Int("database::conns::maxconnection"); err != nil || maxconnection != 12 {
t.Fatal("get database::conns::maxconnection error")
}
if db, err := jsonconf.DIY("database"); err != nil {
t.Fatal(err)
} else if m, ok := db.(map[string]interface{}); !ok {
@ -179,4 +215,8 @@ func TestJson(t *testing.T) {
if _, err := jsonconf.Bool("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting a Bool")
}
if !jsonconf.DefaultBool("unknown", true) {
t.Error("unknown keys with default value wrong")
}
}

34
adapter/config/xml/xml.go Normal file
View File

@ -0,0 +1,34 @@
// 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 xml for config provider.
//
// depend on github.com/beego/x2j.
//
// go install github.com/beego/x2j.
//
// Usage:
// import(
// _ "github.com/astaxie/beego/config/xml"
// "github.com/astaxie/beego/config"
// )
//
// cnf, err := config.NewConfig("xml", "config.xml")
//
// More docs http://beego.me/docs/module/config.md
package xml
import (
_ "github.com/astaxie/beego/core/config/xml"
)

View File

@ -0,0 +1,125 @@
// 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 xml
import (
"fmt"
"os"
"testing"
"github.com/astaxie/beego/adapter/config"
)
func TestXML(t *testing.T) {
var (
//xml parse should incluce in <config></config> tags
xmlcontext = `<?xml version="1.0" encoding="UTF-8"?>
<config>
<appname>beeapi</appname>
<httpport>8080</httpport>
<mysqlport>3600</mysqlport>
<PI>3.1415976</PI>
<runmode>dev</runmode>
<autorender>false</autorender>
<copyrequestbody>true</copyrequestbody>
<path1>${GOPATH}</path1>
<path2>${GOPATH||/home/go}</path2>
<mysection>
<id>1</id>
<name>MySection</name>
</mysection>
</config>
`
keyValue = map[string]interface{}{
"appname": "beeapi",
"httpport": 8080,
"mysqlport": int64(3600),
"PI": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"path1": os.Getenv("GOPATH"),
"path2": os.Getenv("GOPATH"),
"error": "",
"emptystrings": []string{},
}
)
f, err := os.Create("testxml.conf")
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(xmlcontext)
if err != nil {
f.Close()
t.Fatal(err)
}
f.Close()
defer os.Remove("testxml.conf")
xmlconf, err := config.NewConfig("xml", "testxml.conf")
if err != nil {
t.Fatal(err)
}
var xmlsection map[string]string
xmlsection, err = xmlconf.GetSection("mysection")
if err != nil {
t.Fatal(err)
}
if len(xmlsection) == 0 {
t.Error("section should not be empty")
}
for k, v := range keyValue {
var (
value interface{}
err error
)
switch v.(type) {
case int:
value, err = xmlconf.Int(k)
case int64:
value, err = xmlconf.Int64(k)
case float64:
value, err = xmlconf.Float(k)
case bool:
value, err = xmlconf.Bool(k)
case []string:
value = xmlconf.Strings(k)
case string:
value = xmlconf.String(k)
default:
value, err = xmlconf.DIY(k)
}
if err != nil {
t.Errorf("get key %q value fatal,%v err %s", k, v, err)
} else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) {
t.Errorf("get key %q value, want %v got %v .", k, v, value)
}
}
if err = xmlconf.Set("name", "astaxie"); err != nil {
t.Fatal(err)
}
if xmlconf.String("name") != "astaxie" {
t.Fatal("get name error")
}
}

View File

@ -0,0 +1,34 @@
// 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 yaml for config provider
//
// depend on github.com/beego/goyaml2
//
// go install github.com/beego/goyaml2
//
// Usage:
// import(
// _ "github.com/astaxie/beego/config/yaml"
// "github.com/astaxie/beego/config"
// )
//
// cnf, err := config.NewConfig("yaml", "config.yaml")
//
// More docs http://beego.me/docs/module/config.md
package yaml
import (
_ "github.com/astaxie/beego/core/config/yaml"
)

View File

@ -15,13 +15,17 @@
package yaml
import (
"fmt"
"os"
"testing"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/adapter/config"
)
var yamlcontext = `
func TestYaml(t *testing.T) {
var (
yamlcontext = `
"appname": beeapi
"httpport": 8080
"mysqlport": 3600
@ -29,9 +33,27 @@ var yamlcontext = `
"runmode": dev
"autorender": false
"copyrequestbody": true
"PATH": GOPATH
"path1": ${GOPATH}
"path2": ${GOPATH||/home/go}
"empty": ""
`
func TestYaml(t *testing.T) {
keyValue = map[string]interface{}{
"appname": "beeapi",
"httpport": 8080,
"mysqlport": int64(3600),
"PI": 3.1415976,
"runmode": "dev",
"autorender": false,
"copyrequestbody": true,
"PATH": "GOPATH",
"path1": os.Getenv("GOPATH"),
"path2": os.Getenv("GOPATH"),
"error": "",
"emptystrings": []string{},
}
)
f, err := os.Create("testyaml.conf")
if err != nil {
t.Fatal(err)
@ -47,36 +69,47 @@ func TestYaml(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if yamlconf.String("appname") != "beeapi" {
t.Fatal("appname not equal to beeapi")
}
if port, err := yamlconf.Int("httpport"); err != nil || port != 8080 {
t.Error(port)
t.Fatal(err)
}
if port, err := yamlconf.Int64("mysqlport"); err != nil || port != 3600 {
t.Error(port)
t.Fatal(err)
}
if pi, err := yamlconf.Float("PI"); err != nil || pi != 3.1415976 {
t.Error(pi)
t.Fatal(err)
}
if yamlconf.String("runmode") != "dev" {
t.Fatal("runmode not equal to dev")
}
if v, err := yamlconf.Bool("autorender"); err != nil || v != false {
t.Error(v)
t.Fatal(err)
}
if v, err := yamlconf.Bool("copyrequestbody"); err != nil || v != true {
t.Error(v)
t.Fatal(err)
for k, v := range keyValue {
var (
value interface{}
err error
)
switch v.(type) {
case int:
value, err = yamlconf.Int(k)
case int64:
value, err = yamlconf.Int64(k)
case float64:
value, err = yamlconf.Float(k)
case bool:
value, err = yamlconf.Bool(k)
case []string:
value = yamlconf.Strings(k)
case string:
value = yamlconf.String(k)
default:
value, err = yamlconf.DIY(k)
}
if err != nil {
t.Errorf("get key %q value fatal,%v err %s", k, v, err)
} else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) {
t.Errorf("get key %q value, want %v got %v .", k, v, value)
}
}
if err = yamlconf.Set("name", "astaxie"); err != nil {
t.Fatal(err)
}
if yamlconf.String("name") != "astaxie" {
t.Fatal("get name error")
}
}

View File

@ -0,0 +1,45 @@
// Copyright 2015 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 context
import (
"io"
"net/http"
"os"
"github.com/astaxie/beego/server/web/context"
)
// InitGzip init the gzipcompress
func InitGzip(minLength, compressLevel int, methods []string) {
context.InitGzip(minLength, compressLevel, methods)
}
// WriteFile reads from file and writes to writer by the specific encoding(gzip/deflate)
func WriteFile(encoding string, writer io.Writer, file *os.File) (bool, string, error) {
return context.WriteFile(encoding, writer, file)
}
// WriteBody reads writes content to writer by the specific encoding(gzip/deflate)
func WriteBody(encoding string, writer io.Writer, content []byte) (bool, string, error) {
return context.WriteBody(encoding, writer, content)
}
// ParseEncoding will extract the right encoding for response
// the Accept-Encoding's sec is here:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
func ParseEncoding(r *http.Request) string {
return context.ParseEncoding(r)
}

146
adapter/context/context.go Normal file
View File

@ -0,0 +1,146 @@
// 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 context provide the context utils
// Usage:
//
// import "github.com/astaxie/beego/context"
//
// ctx := context.Context{Request:req,ResponseWriter:rw}
//
// more docs http://beego.me/docs/module/context.md
package context
import (
"bufio"
"net"
"net/http"
"github.com/astaxie/beego/server/web/context"
)
// commonly used mime-types
const (
ApplicationJSON = context.ApplicationJSON
ApplicationXML = context.ApplicationXML
ApplicationYAML = context.ApplicationYAML
TextXML = context.TextXML
)
// NewContext return the Context with Input and Output
func NewContext() *Context {
return (*Context)(context.NewContext())
}
// Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter.
// BeegoInput and BeegoOutput provides some api to operate request and response more easily.
type Context context.Context
// Reset init Context, BeegoInput and BeegoOutput
func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) {
(*context.Context)(ctx).Reset(rw, r)
}
// Redirect does redirection to localurl with http header status code.
func (ctx *Context) Redirect(status int, localurl string) {
(*context.Context)(ctx).Redirect(status, localurl)
}
// Abort stops this request.
// if beego.ErrorMaps exists, panic body.
func (ctx *Context) Abort(status int, body string) {
(*context.Context)(ctx).Abort(status, body)
}
// WriteString Write string to response body.
// it sends response body.
func (ctx *Context) WriteString(content string) {
(*context.Context)(ctx).WriteString(content)
}
// GetCookie Get cookie from request by a given key.
// It's alias of BeegoInput.Cookie.
func (ctx *Context) GetCookie(key string) string {
return (*context.Context)(ctx).GetCookie(key)
}
// SetCookie Set cookie for response.
// It's alias of BeegoOutput.Cookie.
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
(*context.Context)(ctx).SetCookie(name, value, others)
}
// GetSecureCookie Get secure cookie from request by a given key.
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
return (*context.Context)(ctx).GetSecureCookie(Secret, key)
}
// SetSecureCookie Set Secure cookie for response.
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
(*context.Context)(ctx).SetSecureCookie(Secret, name, value, others)
}
// XSRFToken creates a xsrf token string and returns.
func (ctx *Context) XSRFToken(key string, expire int64) string {
return (*context.Context)(ctx).XSRFToken(key, expire)
}
// CheckXSRFCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf".
func (ctx *Context) CheckXSRFCookie() bool {
return (*context.Context)(ctx).CheckXSRFCookie()
}
// RenderMethodResult renders the return value of a controller method to the output
func (ctx *Context) RenderMethodResult(result interface{}) {
(*context.Context)(ctx).RenderMethodResult(result)
}
// Response is a wrapper for the http.ResponseWriter
// started set to true if response was written to then don't execute other handler
type Response context.Response
// Write writes the data to the connection as part of an HTTP reply,
// and sets `started` to true.
// started means the response has sent out.
func (r *Response) Write(p []byte) (int, error) {
return (*context.Response)(r).Write(p)
}
// WriteHeader sends an HTTP response header with status code,
// and sets `started` to true.
func (r *Response) WriteHeader(code int) {
(*context.Response)(r).WriteHeader(code)
}
// Hijack hijacker for http
func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return (*context.Response)(r).Hijack()
}
// Flush http.Flusher
func (r *Response) Flush() {
(*context.Response)(r).Flush()
}
// CloseNotify http.CloseNotifier
func (r *Response) CloseNotify() <-chan bool {
return (*context.Response)(r).CloseNotify()
}
// Pusher http.Pusher
func (r *Response) Pusher() (pusher http.Pusher) {
return (*context.Response)(r).Pusher()
}

282
adapter/context/input.go Normal file
View File

@ -0,0 +1,282 @@
// 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 context
import (
"github.com/astaxie/beego/server/web/context"
)
// BeegoInput operates the http request header, data, cookie and body.
// it also contains router params and current session.
type BeegoInput context.BeegoInput
// NewInput return BeegoInput generated by Context.
func NewInput() *BeegoInput {
return (*BeegoInput)(context.NewInput())
}
// Reset init the BeegoInput
func (input *BeegoInput) Reset(ctx *Context) {
(*context.BeegoInput)(input).Reset((*context.Context)(ctx))
}
// Protocol returns request protocol name, such as HTTP/1.1 .
func (input *BeegoInput) Protocol() string {
return (*context.BeegoInput)(input).Protocol()
}
// URI returns full request url with query string, fragment.
func (input *BeegoInput) URI() string {
return input.Context.Request.RequestURI
}
// URL returns request url path (without query string, fragment).
func (input *BeegoInput) URL() string {
return (*context.BeegoInput)(input).URL()
}
// Site returns base site url as scheme://domain type.
func (input *BeegoInput) Site() string {
return (*context.BeegoInput)(input).Site()
}
// Scheme returns request scheme as "http" or "https".
func (input *BeegoInput) Scheme() string {
return (*context.BeegoInput)(input).Scheme()
}
// Domain returns host name.
// Alias of Host method.
func (input *BeegoInput) Domain() string {
return (*context.BeegoInput)(input).Domain()
}
// Host returns host name.
// if no host info in request, return localhost.
func (input *BeegoInput) Host() string {
return (*context.BeegoInput)(input).Host()
}
// Method returns http request method.
func (input *BeegoInput) Method() string {
return (*context.BeegoInput)(input).Method()
}
// Is returns boolean of this request is on given method, such as Is("POST").
func (input *BeegoInput) Is(method string) bool {
return (*context.BeegoInput)(input).Is(method)
}
// IsGet Is this a GET method request?
func (input *BeegoInput) IsGet() bool {
return (*context.BeegoInput)(input).IsGet()
}
// IsPost Is this a POST method request?
func (input *BeegoInput) IsPost() bool {
return (*context.BeegoInput)(input).IsPost()
}
// IsHead Is this a Head method request?
func (input *BeegoInput) IsHead() bool {
return (*context.BeegoInput)(input).IsHead()
}
// IsOptions Is this a OPTIONS method request?
func (input *BeegoInput) IsOptions() bool {
return (*context.BeegoInput)(input).IsOptions()
}
// IsPut Is this a PUT method request?
func (input *BeegoInput) IsPut() bool {
return (*context.BeegoInput)(input).IsPut()
}
// IsDelete Is this a DELETE method request?
func (input *BeegoInput) IsDelete() bool {
return (*context.BeegoInput)(input).IsDelete()
}
// IsPatch Is this a PATCH method request?
func (input *BeegoInput) IsPatch() bool {
return (*context.BeegoInput)(input).IsPatch()
}
// IsAjax returns boolean of this request is generated by ajax.
func (input *BeegoInput) IsAjax() bool {
return (*context.BeegoInput)(input).IsAjax()
}
// IsSecure returns boolean of this request is in https.
func (input *BeegoInput) IsSecure() bool {
return (*context.BeegoInput)(input).IsSecure()
}
// IsWebsocket returns boolean of this request is in webSocket.
func (input *BeegoInput) IsWebsocket() bool {
return (*context.BeegoInput)(input).IsWebsocket()
}
// IsUpload returns boolean of whether file uploads in this request or not..
func (input *BeegoInput) IsUpload() bool {
return (*context.BeegoInput)(input).IsUpload()
}
// AcceptsHTML Checks if request accepts html response
func (input *BeegoInput) AcceptsHTML() bool {
return (*context.BeegoInput)(input).AcceptsHTML()
}
// AcceptsXML Checks if request accepts xml response
func (input *BeegoInput) AcceptsXML() bool {
return (*context.BeegoInput)(input).AcceptsXML()
}
// AcceptsJSON Checks if request accepts json response
func (input *BeegoInput) AcceptsJSON() bool {
return (*context.BeegoInput)(input).AcceptsJSON()
}
// AcceptsYAML Checks if request accepts json response
func (input *BeegoInput) AcceptsYAML() bool {
return (*context.BeegoInput)(input).AcceptsYAML()
}
// IP returns request client ip.
// if in proxy, return first proxy id.
// if error, return RemoteAddr.
func (input *BeegoInput) IP() string {
return (*context.BeegoInput)(input).IP()
}
// Proxy returns proxy client ips slice.
func (input *BeegoInput) Proxy() []string {
return (*context.BeegoInput)(input).Proxy()
}
// Referer returns http referer header.
func (input *BeegoInput) Referer() string {
return (*context.BeegoInput)(input).Referer()
}
// Refer returns http referer header.
func (input *BeegoInput) Refer() string {
return (*context.BeegoInput)(input).Refer()
}
// SubDomains returns sub domain string.
// if aa.bb.domain.com, returns aa.bb .
func (input *BeegoInput) SubDomains() string {
return (*context.BeegoInput)(input).SubDomains()
}
// Port returns request client port.
// when error or empty, return 80.
func (input *BeegoInput) Port() int {
return (*context.BeegoInput)(input).Port()
}
// UserAgent returns request client user agent string.
func (input *BeegoInput) UserAgent() string {
return (*context.BeegoInput)(input).UserAgent()
}
// ParamsLen return the length of the params
func (input *BeegoInput) ParamsLen() int {
return (*context.BeegoInput)(input).ParamsLen()
}
// Param returns router param by a given key.
func (input *BeegoInput) Param(key string) string {
return (*context.BeegoInput)(input).Param(key)
}
// Params returns the map[key]value.
func (input *BeegoInput) Params() map[string]string {
return (*context.BeegoInput)(input).Params()
}
// SetParam will set the param with key and value
func (input *BeegoInput) SetParam(key, val string) {
(*context.BeegoInput)(input).SetParam(key, val)
}
// ResetParams clears any of the input's Params
// This function is used to clear parameters so they may be reset between filter
// passes.
func (input *BeegoInput) ResetParams() {
(*context.BeegoInput)(input).ResetParams()
}
// Query returns input data item string by a given string.
func (input *BeegoInput) Query(key string) string {
return (*context.BeegoInput)(input).Query(key)
}
// Header returns request header item string by a given string.
// if non-existed, return empty string.
func (input *BeegoInput) Header(key string) string {
return (*context.BeegoInput)(input).Header(key)
}
// Cookie returns request cookie item string by a given key.
// if non-existed, return empty string.
func (input *BeegoInput) Cookie(key string) string {
return (*context.BeegoInput)(input).Cookie(key)
}
// Session returns current session item value by a given key.
// if non-existed, return nil.
func (input *BeegoInput) Session(key interface{}) interface{} {
return (*context.BeegoInput)(input).Session(key)
}
// CopyBody returns the raw request body data as bytes.
func (input *BeegoInput) CopyBody(MaxMemory int64) []byte {
return (*context.BeegoInput)(input).CopyBody(MaxMemory)
}
// Data return the implicit data in the input
func (input *BeegoInput) Data() map[interface{}]interface{} {
return (*context.BeegoInput)(input).Data()
}
// GetData returns the stored data in this context.
func (input *BeegoInput) GetData(key interface{}) interface{} {
return (*context.BeegoInput)(input).GetData(key)
}
// SetData stores data with given key in this context.
// This data are only available in this context.
func (input *BeegoInput) SetData(key, val interface{}) {
(*context.BeegoInput)(input).SetData(key, val)
}
// ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type
func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error {
return (*context.BeegoInput)(input).ParseFormOrMultiForm(maxMemory)
}
// Bind data from request.Form[key] to dest
// like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie
// var id int beegoInput.Bind(&id, "id") id ==123
// var isok bool beegoInput.Bind(&isok, "isok") isok ==true
// var ft float64 beegoInput.Bind(&ft, "ft") ft ==1.2
// ol := make([]int, 0, 2) beegoInput.Bind(&ol, "ol") ol ==[1 2]
// ul := make([]string, 0, 2) beegoInput.Bind(&ul, "ul") ul ==[str array]
// user struct{Name} beegoInput.Bind(&user, "user") user == {Name:"astaxie"}
func (input *BeegoInput) Bind(dest interface{}, key string) error {
return (*context.BeegoInput)(input).Bind(dest, key)
}

154
adapter/context/output.go Normal file
View File

@ -0,0 +1,154 @@
// 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 context
import (
"github.com/astaxie/beego/server/web/context"
)
// BeegoOutput does work for sending response header.
type BeegoOutput context.BeegoOutput
// NewOutput returns new BeegoOutput.
// it contains nothing now.
func NewOutput() *BeegoOutput {
return (*BeegoOutput)(context.NewOutput())
}
// Reset init BeegoOutput
func (output *BeegoOutput) Reset(ctx *Context) {
(*context.BeegoOutput)(output).Reset((*context.Context)(ctx))
}
// Header sets response header item string via given key.
func (output *BeegoOutput) Header(key, val string) {
(*context.BeegoOutput)(output).Header(key, val)
}
// Body sets response body content.
// if EnableGzip, compress content string.
// it sends out response body directly.
func (output *BeegoOutput) Body(content []byte) error {
return (*context.BeegoOutput)(output).Body(content)
}
// Cookie sets cookie value via given key.
// others are ordered as cookie's max age time, path,domain, secure and httponly.
func (output *BeegoOutput) Cookie(name string, value string, others ...interface{}) {
(*context.BeegoOutput)(output).Cookie(name, value, others)
}
// JSON writes json to response body.
// if encoding is true, it converts utf-8 to \u0000 type.
func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, encoding bool) error {
return (*context.BeegoOutput)(output).JSON(data, hasIndent, encoding)
}
// YAML writes yaml to response body.
func (output *BeegoOutput) YAML(data interface{}) error {
return (*context.BeegoOutput)(output).YAML(data)
}
// JSONP writes jsonp to response body.
func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
return (*context.BeegoOutput)(output).JSONP(data, hasIndent)
}
// XML writes xml string to response body.
func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
return (*context.BeegoOutput)(output).XML(data, hasIndent)
}
// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) {
(*context.BeegoOutput)(output).ServeFormatted(data, hasIndent, hasEncode...)
}
// Download forces response for download file.
// it prepares the download response header automatically.
func (output *BeegoOutput) Download(file string, filename ...string) {
(*context.BeegoOutput)(output).Download(file, filename...)
}
// ContentType sets the content type from ext string.
// MIME type is given in mime package.
func (output *BeegoOutput) ContentType(ext string) {
(*context.BeegoOutput)(output).ContentType(ext)
}
// SetStatus sets response status code.
// It writes response header directly.
func (output *BeegoOutput) SetStatus(status int) {
(*context.BeegoOutput)(output).SetStatus(status)
}
// IsCachable returns boolean of this request is cached.
// HTTP 304 means cached.
func (output *BeegoOutput) IsCachable() bool {
return (*context.BeegoOutput)(output).IsCachable()
}
// IsEmpty returns boolean of this request is empty.
// HTTP 201204 and 304 means empty.
func (output *BeegoOutput) IsEmpty() bool {
return (*context.BeegoOutput)(output).IsEmpty()
}
// IsOk returns boolean of this request runs well.
// HTTP 200 means ok.
func (output *BeegoOutput) IsOk() bool {
return (*context.BeegoOutput)(output).IsOk()
}
// IsSuccessful returns boolean of this request runs successfully.
// HTTP 2xx means ok.
func (output *BeegoOutput) IsSuccessful() bool {
return (*context.BeegoOutput)(output).IsSuccessful()
}
// IsRedirect returns boolean of this request is redirection header.
// HTTP 301,302,307 means redirection.
func (output *BeegoOutput) IsRedirect() bool {
return (*context.BeegoOutput)(output).IsRedirect()
}
// IsForbidden returns boolean of this request is forbidden.
// HTTP 403 means forbidden.
func (output *BeegoOutput) IsForbidden() bool {
return (*context.BeegoOutput)(output).IsForbidden()
}
// IsNotFound returns boolean of this request is not found.
// HTTP 404 means not found.
func (output *BeegoOutput) IsNotFound() bool {
return (*context.BeegoOutput)(output).IsNotFound()
}
// IsClientError returns boolean of this request client sends error data.
// HTTP 4xx means client error.
func (output *BeegoOutput) IsClientError() bool {
return (*context.BeegoOutput)(output).IsClientError()
}
// IsServerError returns boolean of this server handler errors.
// HTTP 5xx means server internal error.
func (output *BeegoOutput) IsServerError() bool {
return (*context.BeegoOutput)(output).IsServerError()
}
// Session sets session item value with given key.
func (output *BeegoOutput) Session(name interface{}, value interface{}) {
(*context.BeegoOutput)(output).Session(name, value)
}

View File

@ -0,0 +1,8 @@
package context
import (
"github.com/astaxie/beego/server/web/context"
)
// Renderer defines an http response renderer
type Renderer context.Renderer

View File

@ -0,0 +1,26 @@
package context
import (
"net/http"
"strconv"
)
const (
// BadRequest indicates http error 400
BadRequest StatusCode = http.StatusBadRequest
// NotFound indicates http error 404
NotFound StatusCode = http.StatusNotFound
)
// StatusCode sets the http response status code
type StatusCode int
func (s StatusCode) Error() string {
return strconv.Itoa(int(s))
}
// Render sets the http status code
func (s StatusCode) Render(ctx *Context) {
ctx.Output.SetStatus(int(s))
}

399
adapter/controller.go Normal file
View File

@ -0,0 +1,399 @@
// 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 (
"mime/multipart"
"net/url"
"github.com/astaxie/beego/adapter/session"
webContext "github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web"
)
var (
// ErrAbort custom error when user stop request handler manually.
ErrAbort = web.ErrAbort
// GlobalControllerRouter store comments with controller. pkgpath+controller:comments
GlobalControllerRouter = web.GlobalControllerRouter
)
// ControllerFilter store the filter for controller
type ControllerFilter web.ControllerFilter
// ControllerFilterComments store the comment for controller level filter
type ControllerFilterComments web.ControllerFilterComments
// ControllerImportComments store the import comment for controller needed
type ControllerImportComments web.ControllerImportComments
// ControllerComments store the comment for the controller method
type ControllerComments web.ControllerComments
// ControllerCommentsSlice implements the sort interface
type ControllerCommentsSlice web.ControllerCommentsSlice
func (p ControllerCommentsSlice) Len() int {
return (web.ControllerCommentsSlice)(p).Len()
}
func (p ControllerCommentsSlice) Less(i, j int) bool {
return (web.ControllerCommentsSlice)(p).Less(i, j)
}
func (p ControllerCommentsSlice) Swap(i, j int) {
(web.ControllerCommentsSlice)(p).Swap(i, j)
}
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
type Controller web.Controller
func (c *Controller) Init(ctx *webContext.Context, controllerName, actionName string, app interface{}) {
(*web.Controller)(c).Init(ctx, controllerName, actionName, app)
}
// ControllerInterface is an interface to uniform all controller handler.
type ControllerInterface web.ControllerInterface
// Prepare runs after Init before request function execution.
func (c *Controller) Prepare() {
(*web.Controller)(c).Prepare()
}
// Finish runs after request function execution.
func (c *Controller) Finish() {
(*web.Controller)(c).Finish()
}
// Get adds a request function to handle GET request.
func (c *Controller) Get() {
(*web.Controller)(c).Get()
}
// Post adds a request function to handle POST request.
func (c *Controller) Post() {
(*web.Controller)(c).Post()
}
// Delete adds a request function to handle DELETE request.
func (c *Controller) Delete() {
(*web.Controller)(c).Delete()
}
// Put adds a request function to handle PUT request.
func (c *Controller) Put() {
(*web.Controller)(c).Put()
}
// Head adds a request function to handle HEAD request.
func (c *Controller) Head() {
(*web.Controller)(c).Head()
}
// Patch adds a request function to handle PATCH request.
func (c *Controller) Patch() {
(*web.Controller)(c).Patch()
}
// Options adds a request function to handle OPTIONS request.
func (c *Controller) Options() {
(*web.Controller)(c).Options()
}
// Trace adds a request function to handle Trace request.
// this method SHOULD NOT be overridden.
// https://tools.ietf.org/html/rfc7231#section-4.3.8
// The TRACE method requests a remote, application-level loop-back of
// the request message. The final recipient of the request SHOULD
// reflect the message received, excluding some fields described below,
// back to the client as the message body of a 200 (OK) response with a
// Content-Type of "message/http" (Section 8.3.1 of [RFC7230]).
func (c *Controller) Trace() {
(*web.Controller)(c).Trace()
}
// HandlerFunc call function with the name
func (c *Controller) HandlerFunc(fnname string) bool {
return (*web.Controller)(c).HandlerFunc(fnname)
}
// URLMapping register the internal Controller router.
func (c *Controller) URLMapping() {
(*web.Controller)(c).URLMapping()
}
// Mapping the method to function
func (c *Controller) Mapping(method string, fn func()) {
(*web.Controller)(c).Mapping(method, fn)
}
// Render sends the response with rendered template bytes as text/html type.
func (c *Controller) Render() error {
return (*web.Controller)(c).Render()
}
// RenderString returns the rendered template string. Do not send out response.
func (c *Controller) RenderString() (string, error) {
return (*web.Controller)(c).RenderString()
}
// RenderBytes returns the bytes of rendered template string. Do not send out response.
func (c *Controller) RenderBytes() ([]byte, error) {
return (*web.Controller)(c).RenderBytes()
}
// Redirect sends the redirection response to url with status code.
func (c *Controller) Redirect(url string, code int) {
(*web.Controller)(c).Redirect(url, code)
}
// SetData set the data depending on the accepted
func (c *Controller) SetData(data interface{}) {
(*web.Controller)(c).SetData(data)
}
// Abort stops controller handler and show the error data if code is defined in ErrorMap or code string.
func (c *Controller) Abort(code string) {
(*web.Controller)(c).Abort(code)
}
// CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
func (c *Controller) CustomAbort(status int, body string) {
(*web.Controller)(c).CustomAbort(status, body)
}
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
func (c *Controller) StopRun() {
(*web.Controller)(c).StopRun()
}
// URLFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
func (c *Controller) URLFor(endpoint string, values ...interface{}) string {
return (*web.Controller)(c).URLFor(endpoint, values...)
}
// ServeJSON sends a json response with encoding charset.
func (c *Controller) ServeJSON(encoding ...bool) {
(*web.Controller)(c).ServeJSON(encoding...)
}
// ServeJSONP sends a jsonp response.
func (c *Controller) ServeJSONP() {
(*web.Controller)(c).ServeJSONP()
}
// ServeXML sends xml response.
func (c *Controller) ServeXML() {
(*web.Controller)(c).ServeXML()
}
// ServeYAML sends yaml response.
func (c *Controller) ServeYAML() {
(*web.Controller)(c).ServeYAML()
}
// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
func (c *Controller) ServeFormatted(encoding ...bool) {
(*web.Controller)(c).ServeFormatted(encoding...)
}
// 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()
}
// ParseForm maps input data map to obj struct.
func (c *Controller) ParseForm(obj interface{}) error {
return (*web.Controller)(c).ParseForm(obj)
}
// GetString returns the input value by key string or the default value while it's present and input is blank
func (c *Controller) GetString(key string, def ...string) string {
return (*web.Controller)(c).GetString(key, def...)
}
// GetStrings returns the input string slice by key string or the default value while it's present and input is blank
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
func (c *Controller) GetStrings(key string, def ...[]string) []string {
return (*web.Controller)(c).GetStrings(key, def...)
}
// GetInt returns input as an int or the default value while it's present and input is blank
func (c *Controller) GetInt(key string, def ...int) (int, error) {
return (*web.Controller)(c).GetInt(key, def...)
}
// GetInt8 return input as an int8 or the default value while it's present and input is blank
func (c *Controller) GetInt8(key string, def ...int8) (int8, error) {
return (*web.Controller)(c).GetInt8(key, def...)
}
// GetUint8 return input as an uint8 or the default value while it's present and input is blank
func (c *Controller) GetUint8(key string, def ...uint8) (uint8, error) {
return (*web.Controller)(c).GetUint8(key, def...)
}
// GetInt16 returns input as an int16 or the default value while it's present and input is blank
func (c *Controller) GetInt16(key string, def ...int16) (int16, error) {
return (*web.Controller)(c).GetInt16(key, def...)
}
// GetUint16 returns input as an uint16 or the default value while it's present and input is blank
func (c *Controller) GetUint16(key string, def ...uint16) (uint16, error) {
return (*web.Controller)(c).GetUint16(key, def...)
}
// GetInt32 returns input as an int32 or the default value while it's present and input is blank
func (c *Controller) GetInt32(key string, def ...int32) (int32, error) {
return (*web.Controller)(c).GetInt32(key, def...)
}
// GetUint32 returns input as an uint32 or the default value while it's present and input is blank
func (c *Controller) GetUint32(key string, def ...uint32) (uint32, error) {
return (*web.Controller)(c).GetUint32(key, def...)
}
// GetInt64 returns input value as int64 or the default value while it's present and input is blank.
func (c *Controller) GetInt64(key string, def ...int64) (int64, error) {
return (*web.Controller)(c).GetInt64(key, def...)
}
// GetUint64 returns input value as uint64 or the default value while it's present and input is blank.
func (c *Controller) GetUint64(key string, def ...uint64) (uint64, error) {
return (*web.Controller)(c).GetUint64(key, def...)
}
// GetBool returns input value as bool or the default value while it's present and input is blank.
func (c *Controller) GetBool(key string, def ...bool) (bool, error) {
return (*web.Controller)(c).GetBool(key, def...)
}
// GetFloat returns input value as float64 or the default value while it's present and input is blank.
func (c *Controller) GetFloat(key string, def ...float64) (float64, error) {
return (*web.Controller)(c).GetFloat(key, def...)
}
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
return (*web.Controller)(c).GetFile(key)
}
// GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles")
// if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent)
// return
// }
// for i, _ := range files {
// //for each fileheader, get a handle to the actual file
// file, err := files[i].Open()
// defer file.Close()
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// //create destination file making sure the path is writeable.
// dst, err := os.Create("upload/" + files[i].Filename)
// defer dst.Close()
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// //copy the uploaded file to the destination file
// if _, err := io.Copy(dst, file); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// }
func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) {
return (*web.Controller)(c).GetFiles(key)
}
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
func (c *Controller) SaveToFile(fromfile, tofile string) error {
return (*web.Controller)(c).SaveToFile(fromfile, tofile)
}
// StartSession starts session and load old session data info this controller.
func (c *Controller) StartSession() session.Store {
s := (*web.Controller)(c).StartSession()
return session.CreateNewToOldStoreAdapter(s)
}
// SetSession puts value into session.
func (c *Controller) SetSession(name interface{}, value interface{}) {
(*web.Controller)(c).SetSession(name, value)
}
// GetSession gets value from session.
func (c *Controller) GetSession(name interface{}) interface{} {
return (*web.Controller)(c).GetSession(name)
}
// DelSession removes value from session.
func (c *Controller) DelSession(name interface{}) {
(*web.Controller)(c).DelSession(name)
}
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
func (c *Controller) SessionRegenerateID() {
(*web.Controller)(c).SessionRegenerateID()
}
// DestroySession cleans session data and session cookie.
func (c *Controller) DestroySession() {
(*web.Controller)(c).DestroySession()
}
// IsAjax returns this request is ajax or not.
func (c *Controller) IsAjax() bool {
return (*web.Controller)(c).IsAjax()
}
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
return (*web.Controller)(c).GetSecureCookie(Secret, key)
}
// SetSecureCookie puts value into cookie after encoded the value.
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
(*web.Controller)(c).SetSecureCookie(Secret, name, value, others...)
}
// XSRFToken creates a CSRF token string and returns.
func (c *Controller) XSRFToken() string {
return (*web.Controller)(c).XSRFToken()
}
// CheckXSRFCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf".
func (c *Controller) CheckXSRFCookie() bool {
return (*web.Controller)(c).CheckXSRFCookie()
}
// XSRFFormHTML writes an input field contains xsrf token value.
func (c *Controller) XSRFFormHTML() string {
return (*web.Controller)(c).XSRFFormHTML()
}
// GetControllerAndAction gets the executing controller name and action name.
func (c *Controller) GetControllerAndAction() (string, string) {
return (*web.Controller)(c).GetControllerAndAction()
}

16
adapter/doc.go Normal file
View File

@ -0,0 +1,16 @@
// 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.
// used to keep compatible with v1.x
package adapter

202
adapter/error.go Normal file
View File

@ -0,0 +1,202 @@
// 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"
"github.com/astaxie/beego/adapter/context"
beecontext "github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web"
)
const (
errorTypeHandler = iota
errorTypeController
)
var tpl = `
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>beego application error</title>
<style>
html, body, body * {padding: 0; margin: 0;}
#header {background:#ffd; border-bottom:solid 2px #A31515; padding: 20px 10px;}
#header h2{ }
#footer {border-top:solid 1px #aaa; padding: 5px 10px; font-size: 12px; color:green;}
#content {padding: 5px;}
#content .stack b{ font-size: 13px; color: red;}
#content .stack pre{padding-left: 10px;}
table {}
td.t {text-align: right; padding-right: 5px; color: #888;}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<div id="header">
<h2>{{.AppError}}</h2>
</div>
<div id="content">
<table>
<tr>
<td class="t">Request Method: </td><td>{{.RequestMethod}}</td>
</tr>
<tr>
<td class="t">Request URL: </td><td>{{.RequestURL}}</td>
</tr>
<tr>
<td class="t">RemoteAddr: </td><td>{{.RemoteAddr }}</td>
</tr>
</table>
<div class="stack">
<b>Stack</b>
<pre>{{.Stack}}</pre>
</div>
</div>
<div id="footer">
<p>beego {{ .BeegoVersion }} (beego framework)</p>
<p>golang version: {{.GoVersion}}</p>
</div>
</body>
</html>
`
var errtpl = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{{.Title}}</title>
<style type="text/css">
* {
margin:0;
padding:0;
}
body {
background-color:#EFEFEF;
font: .9em "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
#wrapper{
width:600px;
margin:40px auto 0;
text-align:center;
-moz-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
-webkit-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
}
#wrapper h1{
color:#FFF;
text-align:center;
margin-bottom:20px;
}
#wrapper a{
display:block;
font-size:.9em;
padding-top:20px;
color:#FFF;
text-decoration:none;
text-align:center;
}
#container {
width:600px;
padding-bottom:15px;
background-color:#FFFFFF;
}
.navtop{
height:40px;
background-color:#24B2EB;
padding:13px;
}
.content {
padding:10px 10px 25px;
background: #FFFFFF;
margin:;
color:#333;
}
a.button{
color:white;
padding:15px 20px;
text-shadow:1px 1px 0 #00A5FF;
font-weight:bold;
text-align:center;
border:1px solid #24B2EB;
margin:0px 200px;
clear:both;
background-color: #24B2EB;
border-radius:100px;
-moz-border-radius:100px;
-webkit-border-radius:100px;
}
a.button:hover{
text-decoration:none;
background-color: #24B2EB;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="container">
<div class="navtop">
<h1>{{.Title}}</h1>
</div>
<div id="content">
{{.Content}}
<a href="/" title="Home" class="button">Go Home</a><br />
<br>Powered by beego {{.BeegoVersion}}
</div>
</div>
</div>
</body>
</html>
`
// ErrorMaps holds map of http handlers for each error string.
// there is 10 kinds default error(40x and 50x)
var ErrorMaps = web.ErrorMaps
// ErrorHandler registers http.HandlerFunc to each http err code string.
// usage:
// beego.ErrorHandler("404",NotFound)
// beego.ErrorHandler("500",InternalServerError)
func ErrorHandler(code string, h http.HandlerFunc) *App {
return (*App)(web.ErrorHandler(code, h))
}
// ErrorController registers ControllerInterface to each http err code string.
// usage:
// beego.ErrorController(&controllers.ErrorController{})
func ErrorController(c ControllerInterface) *App {
return (*App)(web.ErrorController(c))
}
// Exception Write HttpStatus with errCode and Exec error handler if exist.
func Exception(errCode uint64, ctx *context.Context) {
web.Exception(errCode, (*beecontext.Context)(ctx))
}

36
adapter/filter.go Normal file
View File

@ -0,0 +1,36 @@
// 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/context"
"github.com/astaxie/beego/server/web"
beecontext "github.com/astaxie/beego/server/web/context"
)
// FilterFunc defines a filter function which is invoked before the controller handler is executed.
type FilterFunc func(*context.Context)
// FilterRouter defines a filter operation which is invoked before the controller handler is executed.
// It can match the URL against a pattern, and execute a filter function
// when a request with a matching URL arrives.
type FilterRouter web.FilterRouter
// ValidRouter checks if the current request is matched by this filter.
// If the request is matched, the values of the URL parameters defined
// by the filter pattern are also returned.
func (f *FilterRouter) ValidRouter(url string, ctx *context.Context) bool {
return (*web.FilterRouter)(f).ValidRouter(url, (*beecontext.Context)(ctx))
}

63
adapter/flash.go Normal file
View File

@ -0,0 +1,63 @@
// 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/server/web"
)
// FlashData is a tools to maintain data when using across request.
type FlashData web.FlashData
// NewFlash return a new empty FlashData struct.
func NewFlash() *FlashData {
return (*FlashData)(web.NewFlash())
}
// Set message to flash
func (fd *FlashData) Set(key string, msg string, args ...interface{}) {
(*web.FlashData)(fd).Set(key, msg, args...)
}
// Success writes success message to flash.
func (fd *FlashData) Success(msg string, args ...interface{}) {
(*web.FlashData)(fd).Success(msg, args...)
}
// Notice writes notice message to flash.
func (fd *FlashData) Notice(msg string, args ...interface{}) {
(*web.FlashData)(fd).Notice(msg, args...)
}
// Warning writes warning message to flash.
func (fd *FlashData) Warning(msg string, args ...interface{}) {
(*web.FlashData)(fd).Warning(msg, args...)
}
// Error writes error message to flash.
func (fd *FlashData) Error(msg string, args ...interface{}) {
(*web.FlashData)(fd).Error(msg, args...)
}
// Store does the saving operation of flash data.
// the data are encoded and saved in cookie.
func (fd *FlashData) Store(c *Controller) {
(*web.FlashData)(fd).Store((*web.Controller)(c))
}
// ReadFromRequest parsed flash data from encoded values in cookie.
func ReadFromRequest(c *Controller) *FlashData {
return (*FlashData)(web.ReadFromRequest((*web.Controller)(c)))
}

35
adapter/fs.go Normal file
View File

@ -0,0 +1,35 @@
// 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 adapter
import (
"net/http"
"path/filepath"
"github.com/astaxie/beego/server/web"
)
type FileSystem web.FileSystem
func (d FileSystem) Open(name string) (http.File, error) {
return (web.FileSystem)(d).Open(name)
}
// Walk walks the file tree rooted at root in filesystem, calling walkFn for each file or
// directory in the tree, including root. All errors that arise visiting files
// and directories are filtered by walkFn.
func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
return web.Walk(fs, root, walkFn)
}

94
adapter/grace/grace.go Normal file
View File

@ -0,0 +1,94 @@
// 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 grace use to hot reload
// Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
//
// Usage:
//
// import(
// "log"
// "net/http"
// "os"
//
// "github.com/astaxie/beego/grace"
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("WORLD!"))
// }
//
// func main() {
// mux := http.NewServeMux()
// mux.HandleFunc("/hello", handler)
//
// err := grace.ListenAndServe("localhost:8080", mux)
// if err != nil {
// log.Println(err)
// }
// log.Println("Server on 8080 stopped")
// os.Exit(0)
// }
package grace
import (
"net/http"
"time"
"github.com/astaxie/beego/server/web/grace"
)
const (
// PreSignal is the position to add filter before signal
PreSignal = iota
// PostSignal is the position to add filter after signal
PostSignal
// StateInit represent the application inited
StateInit
// StateRunning represent the application is running
StateRunning
// StateShuttingDown represent the application is shutting down
StateShuttingDown
// StateTerminate represent the application is killed
StateTerminate
)
var (
// DefaultReadTimeOut is the HTTP read timeout
DefaultReadTimeOut time.Duration
// DefaultWriteTimeOut is the HTTP Write timeout
DefaultWriteTimeOut time.Duration
// DefaultMaxHeaderBytes is the Max HTTP Header size, default is 0, no limit
DefaultMaxHeaderBytes int
// DefaultTimeout is the shutdown server's timeout. default is 60s
DefaultTimeout = grace.DefaultTimeout
)
// NewServer returns a new graceServer.
func NewServer(addr string, handler http.Handler) (srv *Server) {
return (*Server)(grace.NewServer(addr, handler))
}
// ListenAndServe refer http.ListenAndServe
func ListenAndServe(addr string, handler http.Handler) error {
server := NewServer(addr, handler)
return server.ListenAndServe()
}
// ListenAndServeTLS refer http.ListenAndServeTLS
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error {
server := NewServer(addr, handler)
return server.ListenAndServeTLS(certFile, keyFile)
}

48
adapter/grace/server.go Normal file
View File

@ -0,0 +1,48 @@
package grace
import (
"os"
"github.com/astaxie/beego/server/web/grace"
)
// Server embedded http.Server
type Server grace.Server
// Serve accepts incoming connections on the Listener l,
// creating a new service goroutine for each.
// The service goroutines read requests and then call srv.Handler to reply to them.
func (srv *Server) Serve() (err error) {
return (*grace.Server)(srv).Serve()
}
// ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
// to handle requests on incoming connections. If srv.Addr is blank, ":http" is
// used.
func (srv *Server) ListenAndServe() (err error) {
return (*grace.Server)(srv).ListenAndServe()
}
// ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
// Serve to handle requests on incoming TLS connections.
//
// Filenames containing a certificate and matching private key for the server must
// be provided. If the certificate is signed by a certificate authority, the
// certFile should be the concatenation of the server's certificate followed by the
// CA's certificate.
//
// If srv.Addr is blank, ":https" is used.
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
return (*grace.Server)(srv).ListenAndServeTLS(certFile, keyFile)
}
// ListenAndServeMutualTLS listens on the TCP network address srv.Addr and then calls
// Serve to handle requests on incoming mutual TLS connections.
func (srv *Server) ListenAndServeMutualTLS(certFile, keyFile, trustFile string) error {
return (*grace.Server)(srv).ListenAndServeMutualTLS(certFile, keyFile, trustFile)
}
// RegisterSignalHook registers a function to be run PreSignal or PostSignal for a given signal.
func (srv *Server) RegisterSignalHook(ppFlag int, sig os.Signal, f func()) error {
return (*grace.Server)(srv).RegisterSignalHook(ppFlag, sig, f)
}

300
adapter/httplib/httplib.go Normal file
View File

@ -0,0 +1,300 @@
// 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 httplib is used as http.Client
// Usage:
//
// import "github.com/astaxie/beego/httplib"
//
// b := httplib.Post("http://beego.me/")
// b.Param("username","astaxie")
// b.Param("password","123456")
// b.PostFile("uploadfile1", "httplib.pdf")
// b.PostFile("uploadfile2", "httplib.txt")
// str, err := b.String()
// if err != nil {
// t.Fatal(err)
// }
// fmt.Println(str)
//
// more docs http://beego.me/docs/module/httplib.md
package httplib
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"time"
"github.com/astaxie/beego/client/httplib"
)
// SetDefaultSetting Overwrite default settings
func SetDefaultSetting(setting BeegoHTTPSettings) {
httplib.SetDefaultSetting(httplib.BeegoHTTPSettings(setting))
}
// NewBeegoRequest return *BeegoHttpRequest with specific method
func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest {
return &BeegoHTTPRequest{
delegate: httplib.NewBeegoRequest(rawurl, method),
}
}
// Get returns *BeegoHttpRequest with GET method.
func Get(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "GET")
}
// Post returns *BeegoHttpRequest with POST method.
func Post(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "POST")
}
// Put returns *BeegoHttpRequest with PUT method.
func Put(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "PUT")
}
// Delete returns *BeegoHttpRequest DELETE method.
func Delete(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "DELETE")
}
// Head returns *BeegoHttpRequest with HEAD method.
func Head(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "HEAD")
}
// BeegoHTTPSettings is the http.Client setting
type BeegoHTTPSettings httplib.BeegoHTTPSettings
// BeegoHTTPRequest provides more useful methods for requesting one url than http.Request.
type BeegoHTTPRequest struct {
delegate *httplib.BeegoHTTPRequest
}
// GetRequest return the request object
func (b *BeegoHTTPRequest) GetRequest() *http.Request {
return b.delegate.GetRequest()
}
// Setting Change request settings
func (b *BeegoHTTPRequest) Setting(setting BeegoHTTPSettings) *BeegoHTTPRequest {
b.delegate.Setting(httplib.BeegoHTTPSettings(setting))
return b
}
// SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
func (b *BeegoHTTPRequest) SetBasicAuth(username, password string) *BeegoHTTPRequest {
b.delegate.SetBasicAuth(username, password)
return b
}
// SetEnableCookie sets enable/disable cookiejar
func (b *BeegoHTTPRequest) SetEnableCookie(enable bool) *BeegoHTTPRequest {
b.delegate.SetEnableCookie(enable)
return b
}
// SetUserAgent sets User-Agent header field
func (b *BeegoHTTPRequest) SetUserAgent(useragent string) *BeegoHTTPRequest {
b.delegate.SetUserAgent(useragent)
return b
}
// Debug sets show debug or not when executing request.
func (b *BeegoHTTPRequest) Debug(isdebug bool) *BeegoHTTPRequest {
b.delegate.Debug(isdebug)
return b
}
// Retries sets Retries times.
// default is 0 means no retried.
// -1 means retried forever.
// others means retried times.
func (b *BeegoHTTPRequest) Retries(times int) *BeegoHTTPRequest {
b.delegate.Retries(times)
return b
}
func (b *BeegoHTTPRequest) RetryDelay(delay time.Duration) *BeegoHTTPRequest {
b.delegate.RetryDelay(delay)
return b
}
// DumpBody setting whether need to Dump the Body.
func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
b.delegate.DumpBody(isdump)
return b
}
// DumpRequest return the DumpRequest
func (b *BeegoHTTPRequest) DumpRequest() []byte {
return b.delegate.DumpRequest()
}
// SetTimeout sets connect time out and read-write time out for BeegoRequest.
func (b *BeegoHTTPRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHTTPRequest {
b.delegate.SetTimeout(connectTimeout, readWriteTimeout)
return b
}
// SetTLSClientConfig sets tls connection configurations if visiting https url.
func (b *BeegoHTTPRequest) SetTLSClientConfig(config *tls.Config) *BeegoHTTPRequest {
b.delegate.SetTLSClientConfig(config)
return b
}
// Header add header item string in request.
func (b *BeegoHTTPRequest) Header(key, value string) *BeegoHTTPRequest {
b.delegate.Header(key, value)
return b
}
// SetHost set the request host
func (b *BeegoHTTPRequest) SetHost(host string) *BeegoHTTPRequest {
b.delegate.SetHost(host)
return b
}
// SetProtocolVersion Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1.
func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
b.delegate.SetProtocolVersion(vers)
return b
}
// SetCookie add cookie into request.
func (b *BeegoHTTPRequest) SetCookie(cookie *http.Cookie) *BeegoHTTPRequest {
b.delegate.SetCookie(cookie)
return b
}
// SetTransport set the setting transport
func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPRequest {
b.delegate.SetTransport(transport)
return b
}
// SetProxy set the http proxy
// example:
//
// func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil
// }
func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest {
b.delegate.SetProxy(proxy)
return b
}
// SetCheckRedirect specifies the policy for handling redirects.
//
// If CheckRedirect is nil, the Client uses its default policy,
// which is to stop after 10 consecutive requests.
func (b *BeegoHTTPRequest) SetCheckRedirect(redirect func(req *http.Request, via []*http.Request) error) *BeegoHTTPRequest {
b.delegate.SetCheckRedirect(redirect)
return b
}
// Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2...
func (b *BeegoHTTPRequest) Param(key, value string) *BeegoHTTPRequest {
b.delegate.Param(key, value)
return b
}
// PostFile add a post file to the request
func (b *BeegoHTTPRequest) PostFile(formname, filename string) *BeegoHTTPRequest {
b.delegate.PostFile(formname, filename)
return b
}
// Body adds request raw body.
// it supports string and []byte.
func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
b.delegate.Body(data)
return b
}
// XMLBody adds request raw body encoding by XML.
func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
_, err := b.delegate.XMLBody(obj)
return b, err
}
// YAMLBody adds request raw body encoding by YAML.
func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
_, err := b.delegate.YAMLBody(obj)
return b, err
}
// JSONBody adds request raw body encoding by JSON.
func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
_, err := b.delegate.JSONBody(obj)
return b, err
}
// DoRequest will do the client.Do
func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
return b.delegate.DoRequest()
}
// String returns the body string in response.
// it calls Response inner.
func (b *BeegoHTTPRequest) String() (string, error) {
return b.delegate.String()
}
// Bytes returns the body []byte in response.
// it calls Response inner.
func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
return b.delegate.Bytes()
}
// ToFile saves the body data in response to one file.
// it calls Response inner.
func (b *BeegoHTTPRequest) ToFile(filename string) error {
return b.delegate.ToFile(filename)
}
// ToJSON returns the map that marshals from the body bytes as json in response .
// it calls Response inner.
func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
return b.delegate.ToJSON(v)
}
// ToXML returns the map that marshals from the body bytes as xml in response .
// it calls Response inner.
func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
return b.delegate.ToXML(v)
}
// ToYAML returns the map that marshals from the body bytes as yaml in response .
// it calls Response inner.
func (b *BeegoHTTPRequest) ToYAML(v interface{}) error {
return b.delegate.ToYAML(v)
}
// Response executes request client gets response mannually.
func (b *BeegoHTTPRequest) Response() (*http.Response, error) {
return b.delegate.Response()
}
// TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
return httplib.TimeoutDialer(cTimeout, rwTimeout)
}

View File

@ -15,10 +15,14 @@
package httplib
import (
"errors"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"testing"
"time"
)
func TestResponse(t *testing.T) {
@ -30,6 +34,34 @@ func TestResponse(t *testing.T) {
t.Log(resp)
}
func TestDoRequest(t *testing.T) {
req := Get("https://goolnk.com/33BD2j")
retryAmount := 1
req.Retries(1)
req.RetryDelay(1400 * time.Millisecond)
retryDelay := 1400 * time.Millisecond
req.SetCheckRedirect(func(redirectReq *http.Request, redirectVia []*http.Request) error {
return errors.New("Redirect triggered")
})
startTime := time.Now().UnixNano() / int64(time.Millisecond)
_, err := req.Response()
if err == nil {
t.Fatal("Response should have yielded an error")
}
endTime := time.Now().UnixNano() / int64(time.Millisecond)
elapsedTime := endTime - startTime
delayedTime := int64(retryAmount) * retryDelay.Milliseconds()
if elapsedTime < delayedTime {
t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime)
}
}
func TestGet(t *testing.T) {
req := Get("http://httpbin.org/get")
b, err := req.Bytes()
@ -66,23 +98,24 @@ func TestSimplePost(t *testing.T) {
}
}
func TestPostFile(t *testing.T) {
v := "smallfish"
req := Post("http://httpbin.org/post")
req.Param("username", v)
req.PostFile("uploadfile", "httplib_test.go")
// func TestPostFile(t *testing.T) {
// v := "smallfish"
// req := Post("http://httpbin.org/post")
// req.Debug(true)
// req.Param("username", v)
// req.PostFile("uploadfile", "httplib_test.go")
str, err := req.String()
if err != nil {
t.Fatal(err)
}
t.Log(str)
// str, err := req.String()
// if err != nil {
// t.Fatal(err)
// }
// t.Log(str)
n := strings.Index(str, v)
if n == -1 {
t.Fatal(v + " not found in post")
}
}
// n := strings.Index(str, v)
// if n == -1 {
// t.Fatal(v + " not found in post")
// }
// }
func TestSimplePut(t *testing.T) {
str, err := Put("http://httpbin.org/put").String()
@ -100,6 +133,14 @@ func TestSimpleDelete(t *testing.T) {
t.Log(str)
}
func TestSimpleDeleteParam(t *testing.T) {
str, err := Delete("http://httpbin.org/delete").Param("key", "val").String()
if err != nil {
t.Fatal(err)
}
t.Log(str)
}
func TestWithCookie(t *testing.T) {
v := "smallfish"
str, err := Get("http://httpbin.org/cookies/set?k1=" + v).SetEnableCookie(true).String()
@ -148,10 +189,20 @@ func TestWithUserAgent(t *testing.T) {
func TestWithSetting(t *testing.T) {
v := "beego"
var setting BeegoHttpSettings
var setting BeegoHTTPSettings
setting.EnableCookie = true
setting.UserAgent = v
setting.Transport = nil
setting.Transport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 50,
IdleConnTimeout: 90 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
setting.ReadWriteTimeout = 5 * time.Second
SetDefaultSetting(setting)
str, err := Get("http://httpbin.org/get").String()
@ -175,19 +226,25 @@ func TestToJson(t *testing.T) {
t.Log(resp)
// httpbin will return http remote addr
type Ip struct {
type IP struct {
Origin string `json:"origin"`
}
var ip Ip
err = req.ToJson(&ip)
var ip IP
err = req.ToJSON(&ip)
if err != nil {
t.Fatal(err)
}
t.Log(ip.Origin)
if n := strings.Count(ip.Origin, "."); n != 3 {
ips := strings.Split(ip.Origin, ",")
if len(ips) == 0 {
t.Fatal("response is not valid ip")
}
for i := range ips {
if net.ParseIP(strings.TrimSpace(ips[i])).To4() == nil {
t.Fatal("response is not valid ip")
}
}
}
func TestToFile(t *testing.T) {
@ -203,3 +260,27 @@ func TestToFile(t *testing.T) {
t.Fatal(err)
}
}
func TestToFileDir(t *testing.T) {
f := "./files/beego_testfile"
req := Get("http://httpbin.org/ip")
err := req.ToFile(f)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll("./files")
b, err := ioutil.ReadFile(f)
if n := strings.Index(string(b), "origin"); n == -1 {
t.Fatal(err)
}
}
func TestHeader(t *testing.T) {
req := Get("http://httpbin.org/headers")
req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")
str, err := req.String()
if err != nil {
t.Fatal(err)
}
t.Log(str)
}

129
adapter/log.go Normal file
View File

@ -0,0 +1,129 @@
// 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 (
"strings"
"github.com/astaxie/beego/core/logs"
webLog "github.com/astaxie/beego/core/logs"
)
// Log levels to control the logging output.
// Deprecated: use github.com/astaxie/beego/logs instead.
const (
LevelEmergency = webLog.LevelEmergency
LevelAlert = webLog.LevelAlert
LevelCritical = webLog.LevelCritical
LevelError = webLog.LevelError
LevelWarning = webLog.LevelWarning
LevelNotice = webLog.LevelNotice
LevelInformational = webLog.LevelInformational
LevelDebug = webLog.LevelDebug
)
// BeeLogger references the used application logger.
// Deprecated: use github.com/astaxie/beego/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.
func SetLevel(l int) {
logs.SetLevel(l)
}
// SetLogFuncCall set the CallDepth, default is 3
// Deprecated: use github.com/astaxie/beego/logs instead.
func SetLogFuncCall(b bool) {
logs.SetLogFuncCall(b)
}
// SetLogger sets a new logger.
// Deprecated: use github.com/astaxie/beego/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.
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.
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.
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.
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.
func Warning(v ...interface{}) {
logs.Warning(generateFmtStr(len(v)), v...)
}
// Warn compatibility alias for Warning()
// Deprecated: use github.com/astaxie/beego/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.
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.
func Informational(v ...interface{}) {
logs.Informational(generateFmtStr(len(v)), v...)
}
// Info compatibility alias for Warning()
// Deprecated: use github.com/astaxie/beego/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.
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.
func Trace(v ...interface{}) {
logs.Trace(generateFmtStr(len(v)), v...)
}
func generateFmtStr(n int) string {
return strings.Repeat("%v ", n)
}

27
adapter/logs/accesslog.go Normal file
View File

@ -0,0 +1,27 @@
// 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 logs
import (
"github.com/astaxie/beego/core/logs"
)
// AccessLogRecord struct for holding access log data.
type AccessLogRecord logs.AccessLogRecord
// AccessLog - Format and print access log.
func AccessLog(r *AccessLogRecord, format string) {
logs.AccessLog((*logs.AccessLogRecord)(r), format)
}

View File

@ -0,0 +1,5 @@
package alils
import (
_ "github.com/astaxie/beego/core/logs/alils"
)

5
adapter/logs/es/es.go Normal file
View File

@ -0,0 +1,5 @@
package es
import (
_ "github.com/astaxie/beego/core/logs/es"
)

347
adapter/logs/log.go Normal file
View File

@ -0,0 +1,347 @@
// 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 logs provide a general log interface
// Usage:
//
// import "github.com/astaxie/beego/logs"
//
// log := NewLogger(10000)
// log.SetLogger("console", "")
//
// > the first params stand for how many channel
//
// Use it like this:
//
// log.Trace("trace")
// log.Info("info")
// log.Warn("warning")
// log.Debug("debug")
// log.Critical("critical")
//
// more docs http://beego.me/docs/module/logs.md
package logs
import (
"log"
"time"
"github.com/astaxie/beego/core/logs"
)
// RFC5424 log message levels.
const (
LevelEmergency = iota
LevelAlert
LevelCritical
LevelError
LevelWarning
LevelNotice
LevelInformational
LevelDebug
)
// levelLogLogger is defined to implement log.Logger
// the real log level will be LevelEmergency
const levelLoggerImpl = -1
// Name for adapter with beego official support
const (
AdapterConsole = "console"
AdapterFile = "file"
AdapterMultiFile = "multifile"
AdapterMail = "smtp"
AdapterConn = "conn"
AdapterEs = "es"
AdapterJianLiao = "jianliao"
AdapterSlack = "slack"
AdapterAliLS = "alils"
)
// Legacy log level constants to ensure backwards compatibility.
const (
LevelInfo = LevelInformational
LevelTrace = LevelDebug
LevelWarn = LevelWarning
)
type newLoggerFunc func() Logger
// Logger defines the behavior of a log provider.
type Logger interface {
Init(config string) error
WriteMsg(when time.Time, msg string, level int) error
Destroy()
Flush()
}
// Register makes a log provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, log newLoggerFunc) {
logs.Register(name, func() logs.Logger {
return &oldToNewAdapter{
old: log(),
}
})
}
// BeeLogger is default logger in beego application.
// it can contain several providers and log message into all providers.
type BeeLogger logs.BeeLogger
const defaultAsyncMsgLen = 1e3
// NewLogger returns a new BeeLogger.
// channelLen means the number of messages in chan(used where asynchronous is true).
// if the buffering chan is full, logger adapters write to file or other way.
func NewLogger(channelLens ...int64) *BeeLogger {
return (*BeeLogger)(logs.NewLogger(channelLens...))
}
// Async set the log to asynchronous and start the goroutine
func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger {
(*logs.BeeLogger)(bl).Async(msgLen...)
return bl
}
// SetLogger provides a given logger adapter into BeeLogger with config string.
// config need to be correct JSON as string: {"interval":360}.
func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error {
return (*logs.BeeLogger)(bl).SetLogger(adapterName, configs...)
}
// DelLogger remove a logger adapter in BeeLogger.
func (bl *BeeLogger) DelLogger(adapterName string) error {
return (*logs.BeeLogger)(bl).DelLogger(adapterName)
}
func (bl *BeeLogger) Write(p []byte) (n int, err error) {
return (*logs.BeeLogger)(bl).Write(p)
}
// SetLevel Set log message level.
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
// log providers will not even be sent the message.
func (bl *BeeLogger) SetLevel(l int) {
(*logs.BeeLogger)(bl).SetLevel(l)
}
// GetLevel Get Current log message level.
func (bl *BeeLogger) GetLevel() int {
return (*logs.BeeLogger)(bl).GetLevel()
}
// SetLogFuncCallDepth set log funcCallDepth
func (bl *BeeLogger) SetLogFuncCallDepth(d int) {
(*logs.BeeLogger)(bl).SetLogFuncCallDepth(d)
}
// GetLogFuncCallDepth return log funcCallDepth for wrapper
func (bl *BeeLogger) GetLogFuncCallDepth() int {
return (*logs.BeeLogger)(bl).GetLogFuncCallDepth()
}
// EnableFuncCallDepth enable log funcCallDepth
func (bl *BeeLogger) EnableFuncCallDepth(b bool) {
(*logs.BeeLogger)(bl).EnableFuncCallDepth(b)
}
// set prefix
func (bl *BeeLogger) SetPrefix(s string) {
(*logs.BeeLogger)(bl).SetPrefix(s)
}
// Emergency Log EMERGENCY level message.
func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Emergency(format, v...)
}
// Alert Log ALERT level message.
func (bl *BeeLogger) Alert(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Alert(format, v...)
}
// Critical Log CRITICAL level message.
func (bl *BeeLogger) Critical(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Critical(format, v...)
}
// Error Log ERROR level message.
func (bl *BeeLogger) Error(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Error(format, v...)
}
// Warning Log WARNING level message.
func (bl *BeeLogger) Warning(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Warning(format, v...)
}
// Notice Log NOTICE level message.
func (bl *BeeLogger) Notice(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Notice(format, v...)
}
// Informational Log INFORMATIONAL level message.
func (bl *BeeLogger) Informational(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Informational(format, v...)
}
// Debug Log DEBUG level message.
func (bl *BeeLogger) Debug(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Debug(format, v...)
}
// Warn Log WARN level message.
// compatibility alias for Warning()
func (bl *BeeLogger) Warn(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Warn(format, v...)
}
// Info Log INFO level message.
// compatibility alias for Informational()
func (bl *BeeLogger) Info(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Info(format, v...)
}
// Trace Log TRACE level message.
// compatibility alias for Debug()
func (bl *BeeLogger) Trace(format string, v ...interface{}) {
(*logs.BeeLogger)(bl).Trace(format, v...)
}
// Flush flush all chan data.
func (bl *BeeLogger) Flush() {
(*logs.BeeLogger)(bl).Flush()
}
// Close close logger, flush all chan data and destroy all adapters in BeeLogger.
func (bl *BeeLogger) Close() {
(*logs.BeeLogger)(bl).Close()
}
// Reset close all outputs, and set bl.outputs to nil
func (bl *BeeLogger) Reset() {
(*logs.BeeLogger)(bl).Reset()
}
// GetBeeLogger returns the default BeeLogger
func GetBeeLogger() *BeeLogger {
return (*BeeLogger)(logs.GetBeeLogger())
}
// GetLogger returns the default BeeLogger
func GetLogger(prefixes ...string) *log.Logger {
return logs.GetLogger(prefixes...)
}
// Reset will remove all the adapter
func Reset() {
logs.Reset()
}
// Async set the beelogger with Async mode and hold msglen messages
func Async(msgLen ...int64) *BeeLogger {
return (*BeeLogger)(logs.Async(msgLen...))
}
// SetLevel sets the global log level used by the simple logger.
func SetLevel(l int) {
logs.SetLevel(l)
}
// SetPrefix sets the prefix
func SetPrefix(s string) {
logs.SetPrefix(s)
}
// EnableFuncCallDepth enable log funcCallDepth
func EnableFuncCallDepth(b bool) {
logs.EnableFuncCallDepth(b)
}
// SetLogFuncCall set the CallDepth, default is 4
func SetLogFuncCall(b bool) {
logs.SetLogFuncCall(b)
}
// SetLogFuncCallDepth set log funcCallDepth
func SetLogFuncCallDepth(d int) {
logs.SetLogFuncCallDepth(d)
}
// SetLogger sets a new logger.
func SetLogger(adapter string, config ...string) error {
return logs.SetLogger(adapter, config...)
}
// Emergency logs a message at emergency level.
func Emergency(f interface{}, v ...interface{}) {
logs.Emergency(f, v...)
}
// Alert logs a message at alert level.
func Alert(f interface{}, v ...interface{}) {
logs.Alert(f, v...)
}
// Critical logs a message at critical level.
func Critical(f interface{}, v ...interface{}) {
logs.Critical(f, v...)
}
// Error logs a message at error level.
func Error(f interface{}, v ...interface{}) {
logs.Error(f, v...)
}
// Warning logs a message at warning level.
func Warning(f interface{}, v ...interface{}) {
logs.Warning(f, v...)
}
// Warn compatibility alias for Warning()
func Warn(f interface{}, v ...interface{}) {
logs.Warn(f, v...)
}
// Notice logs a message at notice level.
func Notice(f interface{}, v ...interface{}) {
logs.Notice(f, v...)
}
// Informational logs a message at info level.
func Informational(f interface{}, v ...interface{}) {
logs.Informational(f, v...)
}
// Info compatibility alias for Warning()
func Info(f interface{}, v ...interface{}) {
logs.Info(f, v...)
}
// Debug logs a message at debug level.
func Debug(f interface{}, v ...interface{}) {
logs.Debug(f, v...)
}
// Trace logs a message at trace level.
// compatibility alias for Warning()
func Trace(f interface{}, v ...interface{}) {
logs.Trace(f, v...)
}
func init() {
SetLogFuncCallDepth(4)
}

View File

@ -0,0 +1,69 @@
// 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
import (
"time"
"github.com/astaxie/beego/core/logs"
)
type oldToNewAdapter struct {
old Logger
}
func (o *oldToNewAdapter) Init(config string) error {
return o.old.Init(config)
}
func (o *oldToNewAdapter) WriteMsg(lm *logs.LogMsg) error {
return o.old.WriteMsg(lm.When, lm.OldStyleFormat(), lm.Level)
}
func (o *oldToNewAdapter) Destroy() {
o.old.Destroy()
}
func (o *oldToNewAdapter) Flush() {
o.old.Flush()
}
func (o *oldToNewAdapter) SetFormatter(f logs.LogFormatter) {
panic("unsupported operation, you should not invoke this method")
}
type newToOldAdapter struct {
n logs.Logger
}
func (n *newToOldAdapter) Init(config string) error {
return n.n.Init(config)
}
func (n *newToOldAdapter) WriteMsg(when time.Time, msg string, level int) error {
return n.n.WriteMsg(&logs.LogMsg{
When: when,
Msg: msg,
Level: level,
})
}
func (n *newToOldAdapter) Destroy() {
panic("implement me")
}
func (n *newToOldAdapter) Flush() {
panic("implement me")
}

38
adapter/logs/logger.go Normal file
View File

@ -0,0 +1,38 @@
// 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 logs
import (
"github.com/astaxie/beego/core/logs"
)
// ColorByStatus return color by http code
// 2xx return Green
// 3xx return White
// 4xx return Yellow
// 5xx return Red
func ColorByStatus(code int) string {
return logs.ColorByStatus(code)
}
// ColorByMethod return color by http code
func ColorByMethod(method string) string {
return logs.ColorByMethod(method)
}
// ResetColor return reset color
func ResetColor() string {
return logs.ResetColor()
}

View File

@ -0,0 +1,24 @@
// Copyright 2016 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 logs
import (
"testing"
)
func TestBeeLogger_Info(t *testing.T) {
log := NewLogger(1000)
log.SetLogger("file", `{"net":"tcp","addr":":7020"}`)
}

View File

@ -0,0 +1,100 @@
// 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 metric
import (
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/astaxie/beego"
"github.com/astaxie/beego/core/logs"
"github.com/astaxie/beego/server/web"
)
func PrometheusMiddleWare(next http.Handler) http.Handler {
summaryVec := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "beego",
Subsystem: "http_request",
ConstLabels: map[string]string{
"server": web.BConfig.ServerName,
"env": web.BConfig.RunMode,
"appname": web.BConfig.AppName,
},
Help: "The statics info for http request",
}, []string{"pattern", "method", "status", "duration"})
prometheus.MustRegister(summaryVec)
registerBuildInfo()
return http.HandlerFunc(func(writer http.ResponseWriter, q *http.Request) {
start := time.Now()
next.ServeHTTP(writer, q)
end := time.Now()
go report(end.Sub(start), writer, q, summaryVec)
})
}
func registerBuildInfo() {
buildInfo := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "beego",
Subsystem: "build_info",
Help: "The building information",
ConstLabels: map[string]string{
"appname": web.BConfig.AppName,
"build_version": beego.BuildVersion,
"build_revision": beego.BuildGitRevision,
"build_status": beego.BuildStatus,
"build_tag": beego.BuildTag,
"build_time": strings.Replace(beego.BuildTime, "--", " ", 1),
"go_version": beego.GoVersion,
"git_branch": beego.GitBranch,
"start_time": time.Now().Format("2006-01-02 15:04:05"),
},
}, []string{})
prometheus.MustRegister(buildInfo)
buildInfo.WithLabelValues().Set(1)
}
func report(dur time.Duration, writer http.ResponseWriter, q *http.Request, vec *prometheus.SummaryVec) {
ctrl := web.BeeApp.Handlers
ctx := ctrl.GetContext()
ctx.Reset(writer, q)
defer ctrl.GiveBackContext(ctx)
// We cannot read the status code from q.Response.StatusCode
// since the http server does not set q.Response. So q.Response is nil
// Thus, we use reflection to read the status from writer whose concrete type is http.response
responseVal := reflect.ValueOf(writer).Elem()
field := responseVal.FieldByName("status")
status := -1
if field.IsValid() && field.Kind() == reflect.Int {
status = int(field.Int())
}
ptn := "UNKNOWN"
if rt, found := ctrl.FindRouter(ctx); found {
ptn = rt.GetPattern()
} else {
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))
}

View File

@ -0,0 +1,42 @@
// 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 metric
import (
"net/http"
"net/url"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/astaxie/beego/adapter/context"
)
func TestPrometheusMiddleWare(t *testing.T) {
middleware := PrometheusMiddleWare(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
writer := &context.Response{}
request := &http.Request{
URL: &url.URL{
Host: "localhost",
RawPath: "/a/b/c",
},
Method: "POST",
}
vec := prometheus.NewSummaryVec(prometheus.SummaryOpts{}, []string{"pattern", "method", "status", "duration"})
report(time.Second, writer, request, vec)
middleware.ServeHTTP(writer, request)
}

198
adapter/migration/ddl.go Normal file
View File

@ -0,0 +1,198 @@
// 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 migration
import (
"github.com/astaxie/beego/client/orm/migration"
)
// Index struct defines the structure of Index Columns
type Index migration.Index
// Unique struct defines a single unique key combination
type Unique migration.Unique
// Column struct defines a single column of a table
type Column migration.Column
// Foreign struct defines a single foreign relationship
type Foreign migration.Foreign
// RenameColumn struct allows renaming of columns
type RenameColumn migration.RenameColumn
// CreateTable creates the table on system
func (m *Migration) CreateTable(tablename, engine, charset string, p ...func()) {
(*migration.Migration)(m).CreateTable(tablename, engine, charset, p...)
}
// AlterTable set the ModifyType to alter
func (m *Migration) AlterTable(tablename string) {
(*migration.Migration)(m).AlterTable(tablename)
}
// NewCol creates a new standard column and attaches it to m struct
func (m *Migration) NewCol(name string) *Column {
return (*Column)((*migration.Migration)(m).NewCol(name))
}
// PriCol creates a new primary column and attaches it to m struct
func (m *Migration) PriCol(name string) *Column {
return (*Column)((*migration.Migration)(m).PriCol(name))
}
// UniCol creates / appends columns to specified unique key and attaches it to m struct
func (m *Migration) UniCol(uni, name string) *Column {
return (*Column)((*migration.Migration)(m).UniCol(uni, name))
}
// ForeignCol creates a new foreign column and returns the instance of column
func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) {
return (*Foreign)((*migration.Migration)(m).ForeignCol(colname, foreigncol, foreigntable))
}
// SetOnDelete sets the on delete of foreign
func (foreign *Foreign) SetOnDelete(del string) *Foreign {
(*migration.Foreign)(foreign).SetOnDelete(del)
return foreign
}
// SetOnUpdate sets the on update of foreign
func (foreign *Foreign) SetOnUpdate(update string) *Foreign {
(*migration.Foreign)(foreign).SetOnUpdate(update)
return foreign
}
// Remove marks the columns to be removed.
// it allows reverse m to create the column.
func (c *Column) Remove() {
(*migration.Column)(c).Remove()
}
// SetAuto enables auto_increment of column (can be used once)
func (c *Column) SetAuto(inc bool) *Column {
(*migration.Column)(c).SetAuto(inc)
return c
}
// SetNullable sets the column to be null
func (c *Column) SetNullable(null bool) *Column {
(*migration.Column)(c).SetNullable(null)
return c
}
// SetDefault sets the default value, prepend with "DEFAULT "
func (c *Column) SetDefault(def string) *Column {
(*migration.Column)(c).SetDefault(def)
return c
}
// SetUnsigned sets the column to be unsigned int
func (c *Column) SetUnsigned(unsign bool) *Column {
(*migration.Column)(c).SetUnsigned(unsign)
return c
}
// SetDataType sets the dataType of the column
func (c *Column) SetDataType(dataType string) *Column {
(*migration.Column)(c).SetDataType(dataType)
return c
}
// SetOldNullable allows reverting to previous nullable on reverse ms
func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn {
(*migration.RenameColumn)(c).SetOldNullable(null)
return c
}
// SetOldDefault allows reverting to previous default on reverse ms
func (c *RenameColumn) SetOldDefault(def string) *RenameColumn {
(*migration.RenameColumn)(c).SetOldDefault(def)
return c
}
// SetOldUnsigned allows reverting to previous unsgined on reverse ms
func (c *RenameColumn) SetOldUnsigned(unsign bool) *RenameColumn {
(*migration.RenameColumn)(c).SetOldUnsigned(unsign)
return c
}
// SetOldDataType allows reverting to previous datatype on reverse ms
func (c *RenameColumn) SetOldDataType(dataType string) *RenameColumn {
(*migration.RenameColumn)(c).SetOldDataType(dataType)
return c
}
// SetPrimary adds the columns to the primary key (can only be used any number of times in only one m)
func (c *Column) SetPrimary(m *Migration) *Column {
(*migration.Column)(c).SetPrimary((*migration.Migration)(m))
return c
}
// AddColumnsToUnique adds the columns to Unique Struct
func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
cls := toNewColumnsArray(columns)
(*migration.Unique)(unique).AddColumnsToUnique(cls...)
return unique
}
// AddColumns adds columns to m struct
func (m *Migration) AddColumns(columns ...*Column) *Migration {
cls := toNewColumnsArray(columns)
(*migration.Migration)(m).AddColumns(cls...)
return m
}
func toNewColumnsArray(columns []*Column) []*migration.Column {
cls := make([]*migration.Column, 0, len(columns))
for _, c := range columns {
cls = append(cls, (*migration.Column)(c))
}
return cls
}
// AddPrimary adds the column to primary in m struct
func (m *Migration) AddPrimary(primary *Column) *Migration {
(*migration.Migration)(m).AddPrimary((*migration.Column)(primary))
return m
}
// AddUnique adds the column to unique in m struct
func (m *Migration) AddUnique(unique *Unique) *Migration {
(*migration.Migration)(m).AddUnique((*migration.Unique)(unique))
return m
}
// AddForeign adds the column to foreign in m struct
func (m *Migration) AddForeign(foreign *Foreign) *Migration {
(*migration.Migration)(m).AddForeign((*migration.Foreign)(foreign))
return m
}
// AddIndex adds the column to index in m struct
func (m *Migration) AddIndex(index *Index) *Migration {
(*migration.Migration)(m).AddIndex((*migration.Index)(index))
return m
}
// RenameColumn allows renaming of columns
func (m *Migration) RenameColumn(from, to string) *RenameColumn {
return (*RenameColumn)((*migration.Migration)(m).RenameColumn(from, to))
}
// GetSQL returns the generated sql depending on ModifyType
func (m *Migration) GetSQL() (sql string) {
return (*migration.Migration)(m).GetSQL()
}

32
adapter/migration/doc.go Normal file
View File

@ -0,0 +1,32 @@
// Package migration enables you to generate migrations back and forth. It generates both migrations.
//
// //Creates a table
// m.CreateTable("tablename","InnoDB","utf8");
//
// //Alter a table
// m.AlterTable("tablename")
//
// Standard Column Methods
// * SetDataType
// * SetNullable
// * SetDefault
// * SetUnsigned (use only on integer types unless produces error)
//
// //Sets a primary column, multiple calls allowed, standard column methods available
// m.PriCol("id").SetAuto(true).SetNullable(false).SetDataType("INT(10)").SetUnsigned(true)
//
// //UniCol Can be used multiple times, allows standard Column methods. Use same "index" string to add to same index
// m.UniCol("index","column")
//
// //Standard Column Initialisation, can call .Remove() after NewCol("") on alter to remove
// m.NewCol("name").SetDataType("VARCHAR(255) COLLATE utf8_unicode_ci").SetNullable(false)
// m.NewCol("value").SetDataType("DOUBLE(8,2)").SetNullable(false)
//
// //Rename Columns , only use with Alter table, doesn't works with Create, prefix standard column methods with "Old" to
// //create a true reversible migration eg: SetOldDataType("DOUBLE(12,3)")
// m.RenameColumn("from","to")...
//
// //Foreign Columns, single columns are only supported, SetOnDelete & SetOnUpdate are available, call appropriately.
// //Supports standard column methods, automatic reverse.
// m.ForeignCol("local_col","foreign_col","foreign_table")
package migration

View File

@ -0,0 +1,111 @@
// 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 migration is used for migration
//
// The table structure is as follow:
//
// CREATE TABLE `migrations` (
// `id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key',
// `name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique',
// `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back',
// `statements` longtext COMMENT 'SQL statements for this migration',
// `rollback_statements` longtext,
// `status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back',
// PRIMARY KEY (`id_migration`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package migration
import (
"github.com/astaxie/beego/client/orm/migration"
)
// const the data format for the bee generate migration datatype
const (
DateFormat = "20060102_150405"
DBDateFormat = "2006-01-02 15:04:05"
)
// Migrationer is an interface for all Migration struct
type Migrationer interface {
Up()
Down()
Reset()
Exec(name, status string) error
GetCreated() int64
}
// Migration defines the migrations by either SQL or DDL
type Migration migration.Migration
// Up implement in the Inheritance struct for upgrade
func (m *Migration) Up() {
(*migration.Migration)(m).Up()
}
// Down implement in the Inheritance struct for down
func (m *Migration) Down() {
(*migration.Migration)(m).Down()
}
// Migrate adds the SQL to the execution list
func (m *Migration) Migrate(migrationType string) {
(*migration.Migration)(m).Migrate(migrationType)
}
// SQL add sql want to execute
func (m *Migration) SQL(sql string) {
(*migration.Migration)(m).SQL(sql)
}
// Reset the sqls
func (m *Migration) Reset() {
(*migration.Migration)(m).Reset()
}
// Exec execute the sql already add in the sql
func (m *Migration) Exec(name, status string) error {
return (*migration.Migration)(m).Exec(name, status)
}
// GetCreated get the unixtime from the Created
func (m *Migration) GetCreated() int64 {
return (*migration.Migration)(m).GetCreated()
}
// Register register the Migration in the map
func Register(name string, m Migrationer) error {
return migration.Register(name, m)
}
// Upgrade upgrade the migration from lasttime
func Upgrade(lasttime int64) error {
return migration.Upgrade(lasttime)
}
// Rollback rollback the migration by the name
func Rollback(name string) error {
return migration.Rollback(name)
}
// Reset reset all migration
// run all migration's down function
func Reset() error {
return migration.Reset()
}
// Refresh first Reset, then Upgrade
func Refresh() error {
return migration.Refresh()
}

378
adapter/namespace.go Normal file
View File

@ -0,0 +1,378 @@
// 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"
adtContext "github.com/astaxie/beego/adapter/context"
"github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web"
)
type namespaceCond func(*adtContext.Context) bool
// LinkNamespace used as link action
type LinkNamespace func(*Namespace)
// Namespace is store all the info
type Namespace web.Namespace
// NewNamespace get new Namespace
func NewNamespace(prefix string, params ...LinkNamespace) *Namespace {
nps := oldToNewLinkNs(params)
return (*Namespace)(web.NewNamespace(prefix, nps...))
}
func oldToNewLinkNs(params []LinkNamespace) []web.LinkNamespace {
nps := make([]web.LinkNamespace, 0, len(params))
for _, p := range params {
nps = append(nps, func(namespace *web.Namespace) {
p((*Namespace)(namespace))
})
}
return nps
}
// Cond set condition function
// if cond return true can run this namespace, else can't
// usage:
// ns.Cond(func (ctx *context.Context) bool{
// if ctx.Input.Domain() == "api.beego.me" {
// return true
// }
// return false
// })
// Cond as the first filter
func (n *Namespace) Cond(cond namespaceCond) *Namespace {
(*web.Namespace)(n).Cond(func(context *context.Context) bool {
return cond((*adtContext.Context)(context))
})
return n
}
// Filter add filter in the Namespace
// action has before & after
// FilterFunc
// usage:
// Filter("before", func (ctx *context.Context){
// _, ok := ctx.Input.Session("uid").(int)
// if !ok && ctx.Request.RequestURI != "/login" {
// ctx.Redirect(302, "/login")
// }
// })
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace {
nfs := oldToNewFilter(filter)
(*web.Namespace)(n).Filter(action, nfs...)
return n
}
func oldToNewFilter(filter []FilterFunc) []web.FilterFunc {
nfs := make([]web.FilterFunc, 0, len(filter))
for _, f := range filter {
nfs = append(nfs, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
return nfs
}
// Router same as beego.Rourer
// refer: https://godoc.org/github.com/astaxie/beego#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
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
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
func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Get(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Post same as beego.Post
// refer: https://godoc.org/github.com/astaxie/beego#Post
func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Post(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Delete same as beego.Delete
// refer: https://godoc.org/github.com/astaxie/beego#Delete
func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Delete(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Put same as beego.Put
// refer: https://godoc.org/github.com/astaxie/beego#Put
func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Put(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Head same as beego.Head
// refer: https://godoc.org/github.com/astaxie/beego#Head
func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Head(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Options same as beego.Options
// refer: https://godoc.org/github.com/astaxie/beego#Options
func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Options(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Patch same as beego.Patch
// refer: https://godoc.org/github.com/astaxie/beego#Patch
func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Patch(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Any same as beego.Any
// refer: https://godoc.org/github.com/astaxie/beego#Any
func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace {
(*web.Namespace)(n).Any(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
return n
}
// Handler same as beego.Handler
// refer: https://godoc.org/github.com/astaxie/beego#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
func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
nL := oldToNewCtrlIntfs(cList)
(*web.Namespace)(n).Include(nL...)
return n
}
// Namespace add nest Namespace
// usage:
// ns := beego.NewNamespace(“/v1”).
// Namespace(
// beego.NewNamespace("/shop").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("shopinfo"))
// }),
// beego.NewNamespace("/order").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("orderinfo"))
// }),
// beego.NewNamespace("/crm").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("crminfo"))
// }),
// )
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace {
nns := oldToNewNs(ns)
(*web.Namespace)(n).Namespace(nns...)
return n
}
func oldToNewNs(ns []*Namespace) []*web.Namespace {
nns := make([]*web.Namespace, 0, len(ns))
for _, n := range ns {
nns = append(nns, (*web.Namespace)(n))
}
return nns
}
// AddNamespace register Namespace into beego.Handler
// support multi Namespace
func AddNamespace(nl ...*Namespace) {
nnl := oldToNewNs(nl)
web.AddNamespace(nnl...)
}
// NSCond is Namespace Condition
func NSCond(cond namespaceCond) LinkNamespace {
return func(namespace *Namespace) {
web.NSCond(func(b *context.Context) bool {
return cond((*adtContext.Context)(b))
})
}
}
// NSBefore Namespace BeforeRouter filter
func NSBefore(filterList ...FilterFunc) LinkNamespace {
return func(namespace *Namespace) {
nfs := oldToNewFilter(filterList)
web.NSBefore(nfs...)
}
}
// NSAfter add Namespace FinishRouter filter
func NSAfter(filterList ...FilterFunc) LinkNamespace {
return func(namespace *Namespace) {
nfs := oldToNewFilter(filterList)
web.NSAfter(nfs...)
}
}
// NSInclude Namespace Include ControllerInterface
func NSInclude(cList ...ControllerInterface) LinkNamespace {
return func(namespace *Namespace) {
nfs := oldToNewCtrlIntfs(cList)
web.NSInclude(nfs...)
}
}
// NSRouter call Namespace Router
func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) LinkNamespace {
return func(namespace *Namespace) {
web.Router(rootpath, c, mappingMethods...)
}
}
// NSGet call Namespace Get
func NSGet(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSGet(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSPost call Namespace Post
func NSPost(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.Post(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSHead call Namespace Head
func NSHead(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSHead(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSPut call Namespace Put
func NSPut(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSPut(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSDelete call Namespace Delete
func NSDelete(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSDelete(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSAny call Namespace Any
func NSAny(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSAny(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSOptions call Namespace Options
func NSOptions(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSOptions(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSPatch call Namespace Patch
func NSPatch(rootpath string, f FilterFunc) LinkNamespace {
return func(ns *Namespace) {
web.NSPatch(rootpath, func(ctx *context.Context) {
f((*adtContext.Context)(ctx))
})
}
}
// NSAutoRouter call Namespace AutoRouter
func NSAutoRouter(c ControllerInterface) LinkNamespace {
return func(ns *Namespace) {
web.NSAutoRouter(c)
}
}
// NSAutoPrefix call Namespace AutoPrefix
func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace {
return func(ns *Namespace) {
web.NSAutoPrefix(prefix, c)
}
}
// NSNamespace add sub Namespace
func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace {
return func(ns *Namespace) {
nps := oldToNewLinkNs(params)
web.NSNamespace(prefix, nps...)
}
}
// NSHandler add handler
func NSHandler(rootpath string, h http.Handler) LinkNamespace {
return func(ns *Namespace) {
web.NSHandler(rootpath, h)
}
}

28
adapter/orm/cmd.go Normal file
View File

@ -0,0 +1,28 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// RunCommand listen for orm command and then run it if command arguments passed.
func RunCommand() {
orm.RunCommand()
}
func RunSyncdb(name string, force bool, verbose bool) error {
return orm.RunSyncdb(name, force, verbose)
}

View File

@ -14,16 +14,11 @@
package orm
// oracle dbBaser
type dbBaseOracle struct {
dbBase
}
import (
"github.com/astaxie/beego/client/orm"
)
var _ dbBaser = new(dbBaseOracle)
// create oracle dbBaser.
func newdbBaseOracle() dbBaser {
b := new(dbBaseOracle)
b.ins = b
return b
}
var (
// ErrMissPK missing pk error
ErrMissPK = orm.ErrMissPK
)

121
adapter/orm/db_alias.go Normal file
View File

@ -0,0 +1,121 @@
// 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 orm
import (
"context"
"database/sql"
"time"
"github.com/astaxie/beego/client/orm"
)
// DriverType database driver constant int.
type DriverType orm.DriverType
// Enum the Database driver
const (
DRMySQL = DriverType(orm.DRMySQL)
DRSqlite = DriverType(orm.DRSqlite) // sqlite
DROracle = DriverType(orm.DROracle) // oracle
DRPostgres = DriverType(orm.DRPostgres) // pgsql
DRTiDB = DriverType(orm.DRTiDB) // TiDB
)
type DB orm.DB
func (d *DB) Begin() (*sql.Tx, error) {
return (*orm.DB)(d).Begin()
}
func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
return (*orm.DB)(d).BeginTx(ctx, opts)
}
func (d *DB) Prepare(query string) (*sql.Stmt, error) {
return (*orm.DB)(d).Prepare(query)
}
func (d *DB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
return (*orm.DB)(d).PrepareContext(ctx, query)
}
func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
return (*orm.DB)(d).Exec(query, args...)
}
func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return (*orm.DB)(d).ExecContext(ctx, query, args...)
}
func (d *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
return (*orm.DB)(d).Query(query, args...)
}
func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return (*orm.DB)(d).QueryContext(ctx, query, args...)
}
func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row {
return (*orm.DB)(d).QueryRow(query, args)
}
func (d *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
return (*orm.DB)(d).QueryRowContext(ctx, query, args...)
}
// AddAliasWthDB add a aliasName for the drivename
func AddAliasWthDB(aliasName, driverName string, db *sql.DB) error {
return orm.AddAliasWthDB(aliasName, driverName, db)
}
// RegisterDataBase Setting the database connect params. Use the database driver self dataSource args.
func RegisterDataBase(aliasName, driverName, dataSource string, params ...int) error {
opts := make([]orm.DBOption, 0, 2)
if len(params) > 0 {
opts = append(opts, orm.MaxIdleConnections(params[0]))
}
if len(params) > 1 {
opts = append(opts, orm.MaxOpenConnections(params[1]))
}
return orm.RegisterDataBase(aliasName, driverName, dataSource, opts...)
}
// RegisterDriver Register a database driver use specify driver name, this can be definition the driver is which database type.
func RegisterDriver(driverName string, typ DriverType) error {
return orm.RegisterDriver(driverName, orm.DriverType(typ))
}
// SetDataBaseTZ Change the database default used timezone
func SetDataBaseTZ(aliasName string, tz *time.Location) error {
return orm.SetDataBaseTZ(aliasName, tz)
}
// SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name
func SetMaxIdleConns(aliasName string, maxIdleConns int) {
orm.SetMaxIdleConns(aliasName, maxIdleConns)
}
// SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name
func SetMaxOpenConns(aliasName string, maxOpenConns int) {
orm.SetMaxOpenConns(aliasName, maxOpenConns)
}
// GetDB Get *sql.DB from registered database by db alias name.
// Use "default" as alias name if you not set.
func GetDB(aliasNames ...string) (*sql.DB, error) {
return orm.GetDB(aliasNames...)
}

25
adapter/orm/models.go Normal file
View File

@ -0,0 +1,25 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// ResetModelCache Clean model cache. Then you can re-RegisterModel.
// Common use this api for test case.
func ResetModelCache() {
orm.ResetModelCache()
}

View File

@ -0,0 +1,40 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// RegisterModel register models
func RegisterModel(models ...interface{}) {
orm.RegisterModel(models...)
}
// RegisterModelWithPrefix register models with a prefix
func RegisterModelWithPrefix(prefix string, models ...interface{}) {
orm.RegisterModelWithPrefix(prefix, models)
}
// RegisterModelWithSuffix register models with a suffix
func RegisterModelWithSuffix(suffix string, models ...interface{}) {
orm.RegisterModelWithSuffix(suffix, models...)
}
// BootStrap bootstrap models.
// make all model parsed and can not add more models
func BootStrap() {
orm.BootStrap()
}

View File

@ -0,0 +1,625 @@
// 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 orm
import (
"time"
"github.com/astaxie/beego/client/orm"
)
// Define the Type enum
const (
TypeBooleanField = orm.TypeBooleanField
TypeVarCharField = orm.TypeVarCharField
TypeCharField = orm.TypeCharField
TypeTextField = orm.TypeTextField
TypeTimeField = orm.TypeTimeField
TypeDateField = orm.TypeDateField
TypeDateTimeField = orm.TypeDateTimeField
TypeBitField = orm.TypeBitField
TypeSmallIntegerField = orm.TypeSmallIntegerField
TypeIntegerField = orm.TypeIntegerField
TypeBigIntegerField = orm.TypeBigIntegerField
TypePositiveBitField = orm.TypePositiveBitField
TypePositiveSmallIntegerField = orm.TypePositiveSmallIntegerField
TypePositiveIntegerField = orm.TypePositiveIntegerField
TypePositiveBigIntegerField = orm.TypePositiveBigIntegerField
TypeFloatField = orm.TypeFloatField
TypeDecimalField = orm.TypeDecimalField
TypeJSONField = orm.TypeJSONField
TypeJsonbField = orm.TypeJsonbField
RelForeignKey = orm.RelForeignKey
RelOneToOne = orm.RelOneToOne
RelManyToMany = orm.RelManyToMany
RelReverseOne = orm.RelReverseOne
RelReverseMany = orm.RelReverseMany
)
// Define some logic enum
const (
IsIntegerField = orm.IsIntegerField
IsPositiveIntegerField = orm.IsPositiveIntegerField
IsRelField = orm.IsRelField
IsFieldType = orm.IsFieldType
)
// BooleanField A true/false field.
type BooleanField orm.BooleanField
// Value return the BooleanField
func (e BooleanField) Value() bool {
return orm.BooleanField(e).Value()
}
// Set will set the BooleanField
func (e *BooleanField) Set(d bool) {
(*orm.BooleanField)(e).Set(d)
}
// String format the Bool to string
func (e *BooleanField) String() string {
return (*orm.BooleanField)(e).String()
}
// FieldType return BooleanField the type
func (e *BooleanField) FieldType() int {
return (*orm.BooleanField)(e).FieldType()
}
// SetRaw set the interface to bool
func (e *BooleanField) SetRaw(value interface{}) error {
return (*orm.BooleanField)(e).SetRaw(value)
}
// RawValue return the current value
func (e *BooleanField) RawValue() interface{} {
return (*orm.BooleanField)(e).RawValue()
}
// verify the BooleanField implement the Fielder interface
var _ Fielder = new(BooleanField)
// CharField A string field
// required values tag: size
// The size is enforced at the database level and in modelss validation.
// eg: `orm:"size(120)"`
type CharField orm.CharField
// Value return the CharField's Value
func (e CharField) Value() string {
return orm.CharField(e).Value()
}
// Set CharField value
func (e *CharField) Set(d string) {
(*orm.CharField)(e).Set(d)
}
// String return the CharField
func (e *CharField) String() string {
return (*orm.CharField)(e).String()
}
// FieldType return the enum type
func (e *CharField) FieldType() int {
return (*orm.CharField)(e).FieldType()
}
// SetRaw set the interface to string
func (e *CharField) SetRaw(value interface{}) error {
return (*orm.CharField)(e).SetRaw(value)
}
// RawValue return the CharField value
func (e *CharField) RawValue() interface{} {
return (*orm.CharField)(e).RawValue()
}
// verify CharField implement Fielder
var _ Fielder = new(CharField)
// TimeField A time, represented in go by a time.Time instance.
// only time values like 10:00:00
// Has a few extra, optional attr tag:
//
// auto_now:
// Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps.
// Note that the current date is always used; its not just a default value that you can override.
//
// auto_now_add:
// Automatically set the field to now when the object is first created. Useful for creation of timestamps.
// Note that the current date is always used; its not just a default value that you can override.
//
// eg: `orm:"auto_now"` or `orm:"auto_now_add"`
type TimeField orm.TimeField
// Value return the time.Time
func (e TimeField) Value() time.Time {
return orm.TimeField(e).Value()
}
// Set set the TimeField's value
func (e *TimeField) Set(d time.Time) {
(*orm.TimeField)(e).Set(d)
}
// String convert time to string
func (e *TimeField) String() string {
return (*orm.TimeField)(e).String()
}
// FieldType return enum type Date
func (e *TimeField) FieldType() int {
return (*orm.TimeField)(e).FieldType()
}
// SetRaw convert the interface to time.Time. Allow string and time.Time
func (e *TimeField) SetRaw(value interface{}) error {
return (*orm.TimeField)(e).SetRaw(value)
}
// RawValue return time value
func (e *TimeField) RawValue() interface{} {
return (*orm.TimeField)(e).RawValue()
}
var _ Fielder = new(TimeField)
// DateField A date, represented in go by a time.Time instance.
// only date values like 2006-01-02
// Has a few extra, optional attr tag:
//
// auto_now:
// Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps.
// Note that the current date is always used; its not just a default value that you can override.
//
// auto_now_add:
// Automatically set the field to now when the object is first created. Useful for creation of timestamps.
// Note that the current date is always used; its not just a default value that you can override.
//
// eg: `orm:"auto_now"` or `orm:"auto_now_add"`
type DateField orm.DateField
// Value return the time.Time
func (e DateField) Value() time.Time {
return orm.DateField(e).Value()
}
// Set set the DateField's value
func (e *DateField) Set(d time.Time) {
(*orm.DateField)(e).Set(d)
}
// String convert datetime to string
func (e *DateField) String() string {
return (*orm.DateField)(e).String()
}
// FieldType return enum type Date
func (e *DateField) FieldType() int {
return (*orm.DateField)(e).FieldType()
}
// SetRaw convert the interface to time.Time. Allow string and time.Time
func (e *DateField) SetRaw(value interface{}) error {
return (*orm.DateField)(e).SetRaw(value)
}
// RawValue return Date value
func (e *DateField) RawValue() interface{} {
return (*orm.DateField)(e).RawValue()
}
// verify DateField implement fielder interface
var _ Fielder = new(DateField)
// DateTimeField A date, represented in go by a time.Time instance.
// datetime values like 2006-01-02 15:04:05
// Takes the same extra arguments as DateField.
type DateTimeField orm.DateTimeField
// Value return the datetime value
func (e DateTimeField) Value() time.Time {
return orm.DateTimeField(e).Value()
}
// Set set the time.Time to datetime
func (e *DateTimeField) Set(d time.Time) {
(*orm.DateTimeField)(e).Set(d)
}
// String return the time's String
func (e *DateTimeField) String() string {
return (*orm.DateTimeField)(e).String()
}
// FieldType return the enum TypeDateTimeField
func (e *DateTimeField) FieldType() int {
return (*orm.DateTimeField)(e).FieldType()
}
// SetRaw convert the string or time.Time to DateTimeField
func (e *DateTimeField) SetRaw(value interface{}) error {
return (*orm.DateTimeField)(e).SetRaw(value)
}
// RawValue return the datetime value
func (e *DateTimeField) RawValue() interface{} {
return (*orm.DateTimeField)(e).RawValue()
}
// verify datetime implement fielder
var _ Fielder = new(DateTimeField)
// FloatField A floating-point number represented in go by a float32 value.
type FloatField orm.FloatField
// Value return the FloatField value
func (e FloatField) Value() float64 {
return orm.FloatField(e).Value()
}
// Set the Float64
func (e *FloatField) Set(d float64) {
(*orm.FloatField)(e).Set(d)
}
// String return the string
func (e *FloatField) String() string {
return (*orm.FloatField)(e).String()
}
// FieldType return the enum type
func (e *FloatField) FieldType() int {
return (*orm.FloatField)(e).FieldType()
}
// SetRaw converter interface Float64 float32 or string to FloatField
func (e *FloatField) SetRaw(value interface{}) error {
return (*orm.FloatField)(e).SetRaw(value)
}
// RawValue return the FloatField value
func (e *FloatField) RawValue() interface{} {
return (*orm.FloatField)(e).RawValue()
}
// verify FloatField implement Fielder
var _ Fielder = new(FloatField)
// SmallIntegerField -32768 to 32767
type SmallIntegerField orm.SmallIntegerField
// Value return int16 value
func (e SmallIntegerField) Value() int16 {
return orm.SmallIntegerField(e).Value()
}
// Set the SmallIntegerField value
func (e *SmallIntegerField) Set(d int16) {
(*orm.SmallIntegerField)(e).Set(d)
}
// String convert smallint to string
func (e *SmallIntegerField) String() string {
return (*orm.SmallIntegerField)(e).String()
}
// FieldType return enum type SmallIntegerField
func (e *SmallIntegerField) FieldType() int {
return (*orm.SmallIntegerField)(e).FieldType()
}
// SetRaw convert interface int16/string to int16
func (e *SmallIntegerField) SetRaw(value interface{}) error {
return (*orm.SmallIntegerField)(e).SetRaw(value)
}
// RawValue return smallint value
func (e *SmallIntegerField) RawValue() interface{} {
return (*orm.SmallIntegerField)(e).RawValue()
}
// verify SmallIntegerField implement Fielder
var _ Fielder = new(SmallIntegerField)
// IntegerField -2147483648 to 2147483647
type IntegerField orm.IntegerField
// Value return the int32
func (e IntegerField) Value() int32 {
return orm.IntegerField(e).Value()
}
// Set IntegerField value
func (e *IntegerField) Set(d int32) {
(*orm.IntegerField)(e).Set(d)
}
// String convert Int32 to string
func (e *IntegerField) String() string {
return (*orm.IntegerField)(e).String()
}
// FieldType return the enum type
func (e *IntegerField) FieldType() int {
return (*orm.IntegerField)(e).FieldType()
}
// SetRaw convert interface int32/string to int32
func (e *IntegerField) SetRaw(value interface{}) error {
return (*orm.IntegerField)(e).SetRaw(value)
}
// RawValue return IntegerField value
func (e *IntegerField) RawValue() interface{} {
return (*orm.IntegerField)(e).RawValue()
}
// verify IntegerField implement Fielder
var _ Fielder = new(IntegerField)
// BigIntegerField -9223372036854775808 to 9223372036854775807.
type BigIntegerField orm.BigIntegerField
// Value return int64
func (e BigIntegerField) Value() int64 {
return orm.BigIntegerField(e).Value()
}
// Set the BigIntegerField value
func (e *BigIntegerField) Set(d int64) {
(*orm.BigIntegerField)(e).Set(d)
}
// String convert BigIntegerField to string
func (e *BigIntegerField) String() string {
return (*orm.BigIntegerField)(e).String()
}
// FieldType return enum type
func (e *BigIntegerField) FieldType() int {
return (*orm.BigIntegerField)(e).FieldType()
}
// SetRaw convert interface int64/string to int64
func (e *BigIntegerField) SetRaw(value interface{}) error {
return (*orm.BigIntegerField)(e).SetRaw(value)
}
// RawValue return BigIntegerField value
func (e *BigIntegerField) RawValue() interface{} {
return (*orm.BigIntegerField)(e).RawValue()
}
// verify BigIntegerField implement Fielder
var _ Fielder = new(BigIntegerField)
// PositiveSmallIntegerField 0 to 65535
type PositiveSmallIntegerField orm.PositiveSmallIntegerField
// Value return uint16
func (e PositiveSmallIntegerField) Value() uint16 {
return orm.PositiveSmallIntegerField(e).Value()
}
// Set PositiveSmallIntegerField value
func (e *PositiveSmallIntegerField) Set(d uint16) {
(*orm.PositiveSmallIntegerField)(e).Set(d)
}
// String convert uint16 to string
func (e *PositiveSmallIntegerField) String() string {
return (*orm.PositiveSmallIntegerField)(e).String()
}
// FieldType return enum type
func (e *PositiveSmallIntegerField) FieldType() int {
return (*orm.PositiveSmallIntegerField)(e).FieldType()
}
// SetRaw convert Interface uint16/string to uint16
func (e *PositiveSmallIntegerField) SetRaw(value interface{}) error {
return (*orm.PositiveSmallIntegerField)(e).SetRaw(value)
}
// RawValue returns PositiveSmallIntegerField value
func (e *PositiveSmallIntegerField) RawValue() interface{} {
return (*orm.PositiveSmallIntegerField)(e).RawValue()
}
// verify PositiveSmallIntegerField implement Fielder
var _ Fielder = new(PositiveSmallIntegerField)
// PositiveIntegerField 0 to 4294967295
type PositiveIntegerField orm.PositiveIntegerField
// Value return PositiveIntegerField value. Uint32
func (e PositiveIntegerField) Value() uint32 {
return orm.PositiveIntegerField(e).Value()
}
// Set the PositiveIntegerField value
func (e *PositiveIntegerField) Set(d uint32) {
(*orm.PositiveIntegerField)(e).Set(d)
}
// String convert PositiveIntegerField to string
func (e *PositiveIntegerField) String() string {
return (*orm.PositiveIntegerField)(e).String()
}
// FieldType return enum type
func (e *PositiveIntegerField) FieldType() int {
return (*orm.PositiveIntegerField)(e).FieldType()
}
// SetRaw convert interface uint32/string to Uint32
func (e *PositiveIntegerField) SetRaw(value interface{}) error {
return (*orm.PositiveIntegerField)(e).SetRaw(value)
}
// RawValue return the PositiveIntegerField Value
func (e *PositiveIntegerField) RawValue() interface{} {
return (*orm.PositiveIntegerField)(e).RawValue()
}
// verify PositiveIntegerField implement Fielder
var _ Fielder = new(PositiveIntegerField)
// PositiveBigIntegerField 0 to 18446744073709551615
type PositiveBigIntegerField orm.PositiveBigIntegerField
// Value return uint64
func (e PositiveBigIntegerField) Value() uint64 {
return orm.PositiveBigIntegerField(e).Value()
}
// Set PositiveBigIntegerField value
func (e *PositiveBigIntegerField) Set(d uint64) {
(*orm.PositiveBigIntegerField)(e).Set(d)
}
// String convert PositiveBigIntegerField to string
func (e *PositiveBigIntegerField) String() string {
return (*orm.PositiveBigIntegerField)(e).String()
}
// FieldType return enum type
func (e *PositiveBigIntegerField) FieldType() int {
return (*orm.PositiveBigIntegerField)(e).FieldType()
}
// SetRaw convert interface uint64/string to Uint64
func (e *PositiveBigIntegerField) SetRaw(value interface{}) error {
return (*orm.PositiveBigIntegerField)(e).SetRaw(value)
}
// RawValue return PositiveBigIntegerField value
func (e *PositiveBigIntegerField) RawValue() interface{} {
return (*orm.PositiveBigIntegerField)(e).RawValue()
}
// verify PositiveBigIntegerField implement Fielder
var _ Fielder = new(PositiveBigIntegerField)
// TextField A large text field.
type TextField orm.TextField
// Value return TextField value
func (e TextField) Value() string {
return orm.TextField(e).Value()
}
// Set the TextField value
func (e *TextField) Set(d string) {
(*orm.TextField)(e).Set(d)
}
// String convert TextField to string
func (e *TextField) String() string {
return (*orm.TextField)(e).String()
}
// FieldType return enum type
func (e *TextField) FieldType() int {
return (*orm.TextField)(e).FieldType()
}
// SetRaw convert interface string to string
func (e *TextField) SetRaw(value interface{}) error {
return (*orm.TextField)(e).SetRaw(value)
}
// RawValue return TextField value
func (e *TextField) RawValue() interface{} {
return (*orm.TextField)(e).RawValue()
}
// verify TextField implement Fielder
var _ Fielder = new(TextField)
// JSONField postgres json field.
type JSONField orm.JSONField
// Value return JSONField value
func (j JSONField) Value() string {
return orm.JSONField(j).Value()
}
// Set the JSONField value
func (j *JSONField) Set(d string) {
(*orm.JSONField)(j).Set(d)
}
// String convert JSONField to string
func (j *JSONField) String() string {
return (*orm.JSONField)(j).String()
}
// FieldType return enum type
func (j *JSONField) FieldType() int {
return (*orm.JSONField)(j).FieldType()
}
// SetRaw convert interface string to string
func (j *JSONField) SetRaw(value interface{}) error {
return (*orm.JSONField)(j).SetRaw(value)
}
// RawValue return JSONField value
func (j *JSONField) RawValue() interface{} {
return (*orm.JSONField)(j).RawValue()
}
// verify JSONField implement Fielder
var _ Fielder = new(JSONField)
// JsonbField postgres json field.
type JsonbField orm.JsonbField
// Value return JsonbField value
func (j JsonbField) Value() string {
return orm.JsonbField(j).Value()
}
// Set the JsonbField value
func (j *JsonbField) Set(d string) {
(*orm.JsonbField)(j).Set(d)
}
// String convert JsonbField to string
func (j *JsonbField) String() string {
return (*orm.JsonbField)(j).String()
}
// FieldType return enum type
func (j *JsonbField) FieldType() int {
return (*orm.JsonbField)(j).FieldType()
}
// SetRaw convert interface string to string
func (j *JsonbField) SetRaw(value interface{}) error {
return (*orm.JsonbField)(j).SetRaw(value)
}
// RawValue return JsonbField value
func (j *JsonbField) RawValue() interface{} {
return (*orm.JsonbField)(j).RawValue()
}
// verify JsonbField implement Fielder
var _ Fielder = new(JsonbField)

314
adapter/orm/orm.go Normal file
View File

@ -0,0 +1,314 @@
// 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.
// +build go1.8
// Package orm provide ORM for MySQL/PostgreSQL/sqlite
// Simple Usage
//
// package main
//
// import (
// "fmt"
// "github.com/astaxie/beego/orm"
// _ "github.com/go-sql-driver/mysql" // import your used driver
// )
//
// // Model Struct
// type User struct {
// Id int `orm:"auto"`
// Name string `orm:"size(100)"`
// }
//
// func init() {
// orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30)
// }
//
// func main() {
// o := orm.NewOrm()
// user := User{Name: "slene"}
// // insert
// id, err := o.Insert(&user)
// // update
// user.Name = "astaxie"
// num, err := o.Update(&user)
// // read one
// u := User{Id: user.Id}
// err = o.Read(&u)
// // delete
// num, err = o.Delete(&u)
// }
//
// more docs: http://beego.me/docs/mvc/model/overview.md
package orm
import (
"context"
"database/sql"
"errors"
"github.com/astaxie/beego/client/orm"
"github.com/astaxie/beego/client/orm/hints"
"github.com/astaxie/beego/core/utils"
)
// DebugQueries define the debug
const (
DebugQueries = iota
)
// Define common vars
var (
Debug = orm.Debug
DebugLog = orm.DebugLog
DefaultRowsLimit = orm.DefaultRowsLimit
DefaultRelsDepth = orm.DefaultRelsDepth
DefaultTimeLoc = orm.DefaultTimeLoc
ErrTxHasBegan = errors.New("<Ormer.Begin> transaction already begin")
ErrTxDone = errors.New("<Ormer.Commit/Rollback> transaction not begin")
ErrMultiRows = errors.New("<QuerySeter> return multi rows")
ErrNoRows = errors.New("<QuerySeter> no row found")
ErrStmtClosed = errors.New("<QuerySeter> stmt already closed")
ErrArgs = errors.New("<Ormer> args error may be empty")
ErrNotImplement = errors.New("have not implement")
)
type ormer struct {
delegate orm.Ormer
txDelegate orm.TxOrmer
isTx bool
}
var _ Ormer = new(ormer)
// read data to model
func (o *ormer) Read(md interface{}, cols ...string) error {
if o.isTx {
return o.txDelegate.Read(md, cols...)
}
return o.delegate.Read(md, cols...)
}
// read data to model, like Read(), but use "SELECT FOR UPDATE" form
func (o *ormer) ReadForUpdate(md interface{}, cols ...string) error {
if o.isTx {
return o.txDelegate.ReadForUpdate(md, cols...)
}
return o.delegate.ReadForUpdate(md, cols...)
}
// Try to read a row from the database, or insert one if it doesn't exist
func (o *ormer) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) {
if o.isTx {
return o.txDelegate.ReadOrCreate(md, col1, cols...)
}
return o.delegate.ReadOrCreate(md, col1, cols...)
}
// insert model data to database
func (o *ormer) Insert(md interface{}) (int64, error) {
if o.isTx {
return o.txDelegate.Insert(md)
}
return o.delegate.Insert(md)
}
// insert some models to database
func (o *ormer) InsertMulti(bulk int, mds interface{}) (int64, error) {
if o.isTx {
return o.txDelegate.InsertMulti(bulk, mds)
}
return o.delegate.InsertMulti(bulk, mds)
}
// InsertOrUpdate data to database
func (o *ormer) InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error) {
if o.isTx {
return o.txDelegate.InsertOrUpdate(md, colConflitAndArgs...)
}
return o.delegate.InsertOrUpdate(md, colConflitAndArgs...)
}
// update model to database.
// cols set the columns those want to update.
func (o *ormer) Update(md interface{}, cols ...string) (int64, error) {
if o.isTx {
return o.txDelegate.Update(md, cols...)
}
return o.delegate.Update(md, cols...)
}
// delete model in database
// cols shows the delete conditions values read from. default is pk
func (o *ormer) Delete(md interface{}, cols ...string) (int64, error) {
if o.isTx {
return o.txDelegate.Delete(md, cols...)
}
return o.delegate.Delete(md, cols...)
}
// create a models to models queryer
func (o *ormer) QueryM2M(md interface{}, name string) QueryM2Mer {
if o.isTx {
return o.txDelegate.QueryM2M(md, name)
}
return o.delegate.QueryM2M(md, name)
}
// load related models to md model.
// args are limit, offset int and order string.
//
// example:
// orm.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
//
// make sure the relation is defined in model struct tags.
func (o *ormer) LoadRelated(md interface{}, name string, args ...interface{}) (int64, error) {
kvs := make([]utils.KV, 0, 4)
for i, arg := range args {
switch i {
case 0:
if v, ok := arg.(bool); ok {
if v {
kvs = append(kvs, hints.DefaultRelDepth())
}
} else if v, ok := arg.(int); ok {
kvs = append(kvs, hints.RelDepth(v))
}
case 1:
kvs = append(kvs, hints.Limit(orm.ToInt64(arg)))
case 2:
kvs = append(kvs, hints.Offset(orm.ToInt64(arg)))
case 3:
kvs = append(kvs, hints.Offset(orm.ToInt64(arg)))
}
}
if o.isTx {
return o.txDelegate.LoadRelated(md, name, kvs...)
}
return o.delegate.LoadRelated(md, name, kvs...)
}
// return a QuerySeter for table operations.
// table name can be string or struct.
// e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)),
func (o *ormer) QueryTable(ptrStructOrTableName interface{}) (qs QuerySeter) {
if o.isTx {
return o.txDelegate.QueryTable(ptrStructOrTableName)
}
return o.delegate.QueryTable(ptrStructOrTableName)
}
// switch to another registered database driver by given name.
func (o *ormer) Using(name string) error {
if o.isTx {
return ErrTxHasBegan
}
o.delegate = orm.NewOrmUsingDB(name)
return nil
}
// begin transaction
func (o *ormer) Begin() error {
if o.isTx {
return ErrTxHasBegan
}
return o.BeginTx(context.Background(), nil)
}
func (o *ormer) BeginTx(ctx context.Context, opts *sql.TxOptions) error {
if o.isTx {
return ErrTxHasBegan
}
txOrmer, err := o.delegate.BeginWithCtxAndOpts(ctx, opts)
if err != nil {
return err
}
o.txDelegate = txOrmer
o.isTx = true
return nil
}
// commit transaction
func (o *ormer) Commit() error {
if !o.isTx {
return ErrTxDone
}
err := o.txDelegate.Commit()
if err == nil {
o.isTx = false
o.txDelegate = nil
} else if err == sql.ErrTxDone {
return ErrTxDone
}
return err
}
// rollback transaction
func (o *ormer) Rollback() error {
if !o.isTx {
return ErrTxDone
}
err := o.txDelegate.Rollback()
if err == nil {
o.isTx = false
o.txDelegate = nil
} else if err == sql.ErrTxDone {
return ErrTxDone
}
return err
}
// return a raw query seter for raw sql string.
func (o *ormer) Raw(query string, args ...interface{}) RawSeter {
if o.isTx {
return o.txDelegate.Raw(query, args...)
}
return o.delegate.Raw(query, args...)
}
// return current using database Driver
func (o *ormer) Driver() Driver {
if o.isTx {
return o.txDelegate.Driver()
}
return o.delegate.Driver()
}
// return sql.DBStats for current database
func (o *ormer) DBStats() *sql.DBStats {
if o.isTx {
return o.txDelegate.DBStats()
}
return o.delegate.DBStats()
}
// NewOrm create new orm
func NewOrm() Ormer {
o := orm.NewOrm()
return &ormer{
delegate: o,
}
}
// NewOrmWithDB create a new ormer object with specify *sql.DB for query
func NewOrmWithDB(driverName, aliasName string, db *sql.DB) (Ormer, error) {
o, err := orm.NewOrmWithDB(driverName, aliasName, db)
if err != nil {
return nil, err
}
return &ormer{
delegate: o,
}, nil
}

83
adapter/orm/orm_conds.go Normal file
View File

@ -0,0 +1,83 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// ExprSep define the expression separation
const (
ExprSep = "__"
)
// Condition struct.
// work for WHERE conditions.
type Condition orm.Condition
// NewCondition return new condition struct
func NewCondition() *Condition {
return (*Condition)(orm.NewCondition())
}
// Raw add raw sql to condition
func (c Condition) Raw(expr string, sql string) *Condition {
return (*Condition)((orm.Condition)(c).Raw(expr, sql))
}
// And add expression to condition
func (c Condition) And(expr string, args ...interface{}) *Condition {
return (*Condition)((orm.Condition)(c).And(expr, args...))
}
// AndNot add NOT expression to condition
func (c Condition) AndNot(expr string, args ...interface{}) *Condition {
return (*Condition)((orm.Condition)(c).AndNot(expr, args...))
}
// AndCond combine a condition to current condition
func (c *Condition) AndCond(cond *Condition) *Condition {
return (*Condition)((*orm.Condition)(c).AndCond((*orm.Condition)(cond)))
}
// AndNotCond combine a AND NOT condition to current condition
func (c *Condition) AndNotCond(cond *Condition) *Condition {
return (*Condition)((*orm.Condition)(c).AndNotCond((*orm.Condition)(cond)))
}
// Or add OR expression to condition
func (c Condition) Or(expr string, args ...interface{}) *Condition {
return (*Condition)((orm.Condition)(c).Or(expr, args...))
}
// OrNot add OR NOT expression to condition
func (c Condition) OrNot(expr string, args ...interface{}) *Condition {
return (*Condition)((orm.Condition)(c).OrNot(expr, args...))
}
// OrCond combine a OR condition to current condition
func (c *Condition) OrCond(cond *Condition) *Condition {
return (*Condition)((*orm.Condition)(c).OrCond((*orm.Condition)(cond)))
}
// OrNotCond combine a OR NOT condition to current condition
func (c *Condition) OrNotCond(cond *Condition) *Condition {
return (*Condition)((*orm.Condition)(c).OrNotCond((*orm.Condition)(cond)))
}
// IsEmpty check the condition arguments are empty or not.
func (c *Condition) IsEmpty() bool {
return (*orm.Condition)(c).IsEmpty()
}

32
adapter/orm/orm_log.go Normal file
View File

@ -0,0 +1,32 @@
// 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 orm
import (
"io"
"github.com/astaxie/beego/client/orm"
)
// Log implement the log.Logger
type Log orm.Log
// costomer log func
var LogFunc = orm.LogFunc
// NewLog set io.Writer to create a Logger.
func NewLog(out io.Writer) *Log {
return (*Log)(orm.NewLog(out))
}

View File

@ -0,0 +1,32 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// define Col operations
const (
ColAdd = orm.ColAdd
ColMinus = orm.ColMinus
ColMultiply = orm.ColMultiply
ColExcept = orm.ColExcept
ColBitAnd = orm.ColBitAnd
ColBitRShift = orm.ColBitRShift
ColBitLShift = orm.ColBitLShift
ColBitXOR = orm.ColBitXOR
ColBitOr = orm.ColBitOr
)

27
adapter/orm/qb.go Normal file
View File

@ -0,0 +1,27 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// QueryBuilder is the Query builder interface
type QueryBuilder orm.QueryBuilder
// NewQueryBuilder return the QueryBuilder
func NewQueryBuilder(driver string) (qb QueryBuilder, err error) {
return orm.NewQueryBuilder(driver)
}

150
adapter/orm/qb_mysql.go Normal file
View File

@ -0,0 +1,150 @@
// 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// CommaSpace is the separation
const CommaSpace = orm.CommaSpace
// MySQLQueryBuilder is the SQL build
type MySQLQueryBuilder orm.MySQLQueryBuilder
// Select will join the fields
func (qb *MySQLQueryBuilder) Select(fields ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Select(fields...)
}
// ForUpdate add the FOR UPDATE clause
func (qb *MySQLQueryBuilder) ForUpdate() QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).ForUpdate()
}
// From join the tables
func (qb *MySQLQueryBuilder) From(tables ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).From(tables...)
}
// InnerJoin INNER JOIN the table
func (qb *MySQLQueryBuilder) InnerJoin(table string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).InnerJoin(table)
}
// LeftJoin LEFT JOIN the table
func (qb *MySQLQueryBuilder) LeftJoin(table string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).LeftJoin(table)
}
// RightJoin RIGHT JOIN the table
func (qb *MySQLQueryBuilder) RightJoin(table string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).RightJoin(table)
}
// On join with on cond
func (qb *MySQLQueryBuilder) On(cond string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).On(cond)
}
// Where join the Where cond
func (qb *MySQLQueryBuilder) Where(cond string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Where(cond)
}
// And join the and cond
func (qb *MySQLQueryBuilder) And(cond string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).And(cond)
}
// Or join the or cond
func (qb *MySQLQueryBuilder) Or(cond string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Or(cond)
}
// In join the IN (vals)
func (qb *MySQLQueryBuilder) In(vals ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).In(vals...)
}
// OrderBy join the Order by fields
func (qb *MySQLQueryBuilder) OrderBy(fields ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).OrderBy(fields...)
}
// Asc join the asc
func (qb *MySQLQueryBuilder) Asc() QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Asc()
}
// Desc join the desc
func (qb *MySQLQueryBuilder) Desc() QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Desc()
}
// Limit join the limit num
func (qb *MySQLQueryBuilder) Limit(limit int) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Limit(limit)
}
// Offset join the offset num
func (qb *MySQLQueryBuilder) Offset(offset int) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Offset(offset)
}
// GroupBy join the Group by fields
func (qb *MySQLQueryBuilder) GroupBy(fields ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).GroupBy(fields...)
}
// Having join the Having cond
func (qb *MySQLQueryBuilder) Having(cond string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Having(cond)
}
// Update join the update table
func (qb *MySQLQueryBuilder) Update(tables ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Update(tables...)
}
// Set join the set kv
func (qb *MySQLQueryBuilder) Set(kv ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Set(kv...)
}
// Delete join the Delete tables
func (qb *MySQLQueryBuilder) Delete(tables ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Delete(tables...)
}
// InsertInto join the insert SQL
func (qb *MySQLQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).InsertInto(table, fields...)
}
// Values join the Values(vals)
func (qb *MySQLQueryBuilder) Values(vals ...string) QueryBuilder {
return (*orm.MySQLQueryBuilder)(qb).Values(vals...)
}
// Subquery join the sub as alias
func (qb *MySQLQueryBuilder) Subquery(sub string, alias string) string {
return (*orm.MySQLQueryBuilder)(qb).Subquery(sub, alias)
}
// String join all Tokens
func (qb *MySQLQueryBuilder) String() string {
return (*orm.MySQLQueryBuilder)(qb).String()
}

147
adapter/orm/qb_tidb.go Normal file
View File

@ -0,0 +1,147 @@
// Copyright 2015 TiDB 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 orm
import (
"github.com/astaxie/beego/client/orm"
)
// TiDBQueryBuilder is the SQL build
type TiDBQueryBuilder orm.TiDBQueryBuilder
// Select will join the fields
func (qb *TiDBQueryBuilder) Select(fields ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Select(fields...)
}
// ForUpdate add the FOR UPDATE clause
func (qb *TiDBQueryBuilder) ForUpdate() QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).ForUpdate()
}
// From join the tables
func (qb *TiDBQueryBuilder) From(tables ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).From(tables...)
}
// InnerJoin INNER JOIN the table
func (qb *TiDBQueryBuilder) InnerJoin(table string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).InnerJoin(table)
}
// LeftJoin LEFT JOIN the table
func (qb *TiDBQueryBuilder) LeftJoin(table string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).LeftJoin(table)
}
// RightJoin RIGHT JOIN the table
func (qb *TiDBQueryBuilder) RightJoin(table string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).RightJoin(table)
}
// On join with on cond
func (qb *TiDBQueryBuilder) On(cond string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).On(cond)
}
// Where join the Where cond
func (qb *TiDBQueryBuilder) Where(cond string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Where(cond)
}
// And join the and cond
func (qb *TiDBQueryBuilder) And(cond string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).And(cond)
}
// Or join the or cond
func (qb *TiDBQueryBuilder) Or(cond string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Or(cond)
}
// In join the IN (vals)
func (qb *TiDBQueryBuilder) In(vals ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).In(vals...)
}
// OrderBy join the Order by fields
func (qb *TiDBQueryBuilder) OrderBy(fields ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).OrderBy(fields...)
}
// Asc join the asc
func (qb *TiDBQueryBuilder) Asc() QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Asc()
}
// Desc join the desc
func (qb *TiDBQueryBuilder) Desc() QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Desc()
}
// Limit join the limit num
func (qb *TiDBQueryBuilder) Limit(limit int) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Limit(limit)
}
// Offset join the offset num
func (qb *TiDBQueryBuilder) Offset(offset int) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Offset(offset)
}
// GroupBy join the Group by fields
func (qb *TiDBQueryBuilder) GroupBy(fields ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).GroupBy(fields...)
}
// Having join the Having cond
func (qb *TiDBQueryBuilder) Having(cond string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Having(cond)
}
// Update join the update table
func (qb *TiDBQueryBuilder) Update(tables ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Update(tables...)
}
// Set join the set kv
func (qb *TiDBQueryBuilder) Set(kv ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Set(kv...)
}
// Delete join the Delete tables
func (qb *TiDBQueryBuilder) Delete(tables ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Delete(tables...)
}
// InsertInto join the insert SQL
func (qb *TiDBQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).InsertInto(table, fields...)
}
// Values join the Values(vals)
func (qb *TiDBQueryBuilder) Values(vals ...string) QueryBuilder {
return (*orm.TiDBQueryBuilder)(qb).Values(vals...)
}
// Subquery join the sub as alias
func (qb *TiDBQueryBuilder) Subquery(sub string, alias string) string {
return (*orm.TiDBQueryBuilder)(qb).Subquery(sub, alias)
}
// String join all Tokens
func (qb *TiDBQueryBuilder) String() string {
return (*orm.TiDBQueryBuilder)(qb).String()
}

View File

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

150
adapter/orm/types.go Normal file
View File

@ -0,0 +1,150 @@
// 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 orm
import (
"context"
"database/sql"
"github.com/astaxie/beego/client/orm"
)
// Params stores the Params
type Params orm.Params
// ParamsList stores paramslist
type ParamsList orm.ParamsList
// Driver define database driver
type Driver orm.Driver
// Fielder define field info
type Fielder orm.Fielder
// Ormer define the orm interface
type Ormer interface {
// read data to model
// for example:
// this will find User by Id field
// u = &User{Id: user.Id}
// err = Ormer.Read(u)
// this will find User by UserName field
// u = &User{UserName: "astaxie", Password: "pass"}
// err = Ormer.Read(u, "UserName")
Read(md interface{}, cols ...string) error
// Like Read(), but with "FOR UPDATE" clause, useful in transaction.
// Some databases are not support this feature.
ReadForUpdate(md interface{}, cols ...string) error
// Try to read a row from the database, or insert one if it doesn't exist
ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error)
// insert model data to database
// for example:
// user := new(User)
// id, err = Ormer.Insert(user)
// user must be a pointer and Insert will set user's pk field
Insert(interface{}) (int64, error)
// mysql:InsertOrUpdate(model) or InsertOrUpdate(model,"colu=colu+value")
// if colu type is integer : can use(+-*/), string : convert(colu,"value")
// postgres: InsertOrUpdate(model,"conflictColumnName") or InsertOrUpdate(model,"conflictColumnName","colu=colu+value")
// if colu type is integer : can use(+-*/), string : colu || "value"
InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error)
// insert some models to database
InsertMulti(bulk int, mds interface{}) (int64, error)
// update model to database.
// cols set the columns those want to update.
// find model by Id(pk) field and update columns specified by fields, if cols is null then update all columns
// for example:
// user := User{Id: 2}
// user.Langs = append(user.Langs, "zh-CN", "en-US")
// user.Extra.Name = "beego"
// user.Extra.Data = "orm"
// num, err = Ormer.Update(&user, "Langs", "Extra")
Update(md interface{}, cols ...string) (int64, error)
// delete model in database
Delete(md interface{}, cols ...string) (int64, error)
// load related models to md model.
// args are limit, offset int and order string.
//
// example:
// Ormer.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
// args[0] bool true useDefaultRelsDepth ; false depth 0
// args[0] int loadRelationDepth
// args[1] int limit default limit 1000
// args[2] int offset default offset 0
// args[3] string order for example : "-Id"
// make sure the relation is defined in model struct tags.
LoadRelated(md interface{}, name string, args ...interface{}) (int64, error)
// create a models to models queryer
// for example:
// post := Post{Id: 4}
// m2m := Ormer.QueryM2M(&post, "Tags")
QueryM2M(md interface{}, name string) QueryM2Mer
// return a QuerySeter for table operations.
// table name can be string or struct.
// e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)),
QueryTable(ptrStructOrTableName interface{}) QuerySeter
// switch to another registered database driver by given name.
Using(name string) error
// begin transaction
// for example:
// o := NewOrm()
// err := o.Begin()
// ...
// err = o.Rollback()
Begin() error
// begin transaction with provided context and option
// the provided context is used until the transaction is committed or rolled back.
// if the context is canceled, the transaction will be rolled back.
// the provided TxOptions is optional and may be nil if defaults should be used.
// if a non-default isolation level is used that the driver doesn't support, an error will be returned.
// for example:
// o := NewOrm()
// err := o.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
// ...
// err = o.Rollback()
BeginTx(ctx context.Context, opts *sql.TxOptions) error
// commit transaction
Commit() error
// rollback transaction
Rollback() error
// return a raw query seter for raw sql string.
// for example:
// ormer.Raw("UPDATE `user` SET `user_name` = ? WHERE `user_name` = ?", "slene", "testing").Exec()
// // update user testing's name to slene
Raw(query string, args ...interface{}) RawSeter
Driver() Driver
DBStats() *sql.DBStats
}
// Inserter insert prepared statement
type Inserter orm.Inserter
// QuerySeter query seter
type QuerySeter orm.QuerySeter
// QueryM2Mer model to model query struct
// all operations are on the m2m table only, will not affect the origin model table
type QueryM2Mer orm.QueryM2Mer
// RawPreparer raw query statement
type RawPreparer orm.RawPreparer
// RawSeter raw query seter
// create From Ormer.Raw
// for example:
// sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
// rs := Ormer.Raw(sql, 1)
type RawSeter orm.RawSeter

286
adapter/orm/utils.go Normal file
View File

@ -0,0 +1,286 @@
// 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 orm
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/astaxie/beego/client/orm"
)
type fn func(string) string
var (
nameStrategyMap = map[string]fn{
defaultNameStrategy: snakeString,
SnakeAcronymNameStrategy: snakeStringWithAcronym,
}
defaultNameStrategy = "snakeString"
SnakeAcronymNameStrategy = "snakeStringWithAcronym"
nameStrategy = defaultNameStrategy
)
// StrTo is the target string
type StrTo orm.StrTo
// Set string
func (f *StrTo) Set(v string) {
(*orm.StrTo)(f).Set(v)
}
// Clear string
func (f *StrTo) Clear() {
(*orm.StrTo)(f).Clear()
}
// Exist check string exist
func (f StrTo) Exist() bool {
return orm.StrTo(f).Exist()
}
// Bool string to bool
func (f StrTo) Bool() (bool, error) {
return orm.StrTo(f).Bool()
}
// Float32 string to float32
func (f StrTo) Float32() (float32, error) {
return orm.StrTo(f).Float32()
}
// Float64 string to float64
func (f StrTo) Float64() (float64, error) {
return orm.StrTo(f).Float64()
}
// Int string to int
func (f StrTo) Int() (int, error) {
return orm.StrTo(f).Int()
}
// Int8 string to int8
func (f StrTo) Int8() (int8, error) {
return orm.StrTo(f).Int8()
}
// Int16 string to int16
func (f StrTo) Int16() (int16, error) {
return orm.StrTo(f).Int16()
}
// Int32 string to int32
func (f StrTo) Int32() (int32, error) {
return orm.StrTo(f).Int32()
}
// Int64 string to int64
func (f StrTo) Int64() (int64, error) {
return orm.StrTo(f).Int64()
}
// Uint string to uint
func (f StrTo) Uint() (uint, error) {
return orm.StrTo(f).Uint()
}
// Uint8 string to uint8
func (f StrTo) Uint8() (uint8, error) {
return orm.StrTo(f).Uint8()
}
// Uint16 string to uint16
func (f StrTo) Uint16() (uint16, error) {
return orm.StrTo(f).Uint16()
}
// Uint32 string to uint32
func (f StrTo) Uint32() (uint32, error) {
return orm.StrTo(f).Uint32()
}
// Uint64 string to uint64
func (f StrTo) Uint64() (uint64, error) {
return orm.StrTo(f).Uint64()
}
// String string to string
func (f StrTo) String() string {
return orm.StrTo(f).String()
}
// ToStr interface to string
func ToStr(value interface{}, args ...int) (s string) {
switch v := value.(type) {
case bool:
s = strconv.FormatBool(v)
case float32:
s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
case float64:
s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
case int:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int8:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int16:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int32:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int64:
s = strconv.FormatInt(v, argInt(args).Get(0, 10))
case uint:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint8:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint16:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint32:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint64:
s = strconv.FormatUint(v, argInt(args).Get(0, 10))
case string:
s = v
case []byte:
s = string(v)
default:
s = fmt.Sprintf("%v", v)
}
return s
}
// ToInt64 interface to int64
func ToInt64(value interface{}) (d int64) {
val := reflect.ValueOf(value)
switch value.(type) {
case int, int8, int16, int32, int64:
d = val.Int()
case uint, uint8, uint16, uint32, uint64:
d = int64(val.Uint())
default:
panic(fmt.Errorf("ToInt64 need numeric not `%T`", value))
}
return
}
func snakeStringWithAcronym(s string) string {
data := make([]byte, 0, len(s)*2)
num := len(s)
for i := 0; i < num; i++ {
d := s[i]
before := false
after := false
if i > 0 {
before = s[i-1] >= 'a' && s[i-1] <= 'z'
}
if i+1 < num {
after = s[i+1] >= 'a' && s[i+1] <= 'z'
}
if i > 0 && d >= 'A' && d <= 'Z' && (before || after) {
data = append(data, '_')
}
data = append(data, d)
}
return strings.ToLower(string(data[:]))
}
// snake string, XxYy to xx_yy , XxYY to xx_y_y
func snakeString(s string) string {
data := make([]byte, 0, len(s)*2)
j := false
num := len(s)
for i := 0; i < num; i++ {
d := s[i]
if i > 0 && d >= 'A' && d <= 'Z' && j {
data = append(data, '_')
}
if d != '_' {
j = true
}
data = append(data, d)
}
return strings.ToLower(string(data[:]))
}
// SetNameStrategy set different name strategy
func SetNameStrategy(s string) {
if SnakeAcronymNameStrategy != s {
nameStrategy = defaultNameStrategy
}
nameStrategy = s
}
// camel string, xx_yy to XxYy
func camelString(s string) string {
data := make([]byte, 0, len(s))
flag, num := true, len(s)-1
for i := 0; i <= num; i++ {
d := s[i]
if d == '_' {
flag = true
continue
} else if flag {
if d >= 'a' && d <= 'z' {
d = d - 32
}
flag = false
}
data = append(data, d)
}
return string(data[:])
}
type argString []string
// get string by index from string slice
func (a argString) Get(i int, args ...string) (r string) {
if i >= 0 && i < len(a) {
r = a[i]
} else if len(args) > 0 {
r = args[0]
}
return
}
type argInt []int
// get int by index from int slice
func (a argInt) Get(i int, args ...int) (r int) {
if i >= 0 && i < len(a) {
r = a[i]
}
if len(args) > 0 {
r = args[0]
}
return
}
// parse time to string with location
func timeParse(dateString, format string) (time.Time, error) {
tp, err := time.ParseInLocation(format, dateString, DefaultTimeLoc)
return tp, err
}
// get pointer indirect type
func indirectType(v reflect.Type) reflect.Type {
switch v.Kind() {
case reflect.Ptr:
return indirectType(v.Elem())
default:
return v
}
}

70
adapter/orm/utils_test.go Normal file
View File

@ -0,0 +1,70 @@
// 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 orm
import (
"testing"
)
func TestCamelString(t *testing.T) {
snake := []string{"pic_url", "hello_world_", "hello__World", "_HelLO_Word", "pic_url_1", "pic_url__1"}
camel := []string{"PicUrl", "HelloWorld", "HelloWorld", "HelLOWord", "PicUrl1", "PicUrl1"}
answer := make(map[string]string)
for i, v := range snake {
answer[v] = camel[i]
}
for _, v := range snake {
res := camelString(v)
if res != answer[v] {
t.Error("Unit Test Fail:", v, res, answer[v])
}
}
}
func TestSnakeString(t *testing.T) {
camel := []string{"PicUrl", "HelloWorld", "HelloWorld", "HelLOWord", "PicUrl1", "XyXX"}
snake := []string{"pic_url", "hello_world", "hello_world", "hel_l_o_word", "pic_url1", "xy_x_x"}
answer := make(map[string]string)
for i, v := range camel {
answer[v] = snake[i]
}
for _, v := range camel {
res := snakeString(v)
if res != answer[v] {
t.Error("Unit Test Fail:", v, res, answer[v])
}
}
}
func TestSnakeStringWithAcronym(t *testing.T) {
camel := []string{"ID", "PicURL", "HelloWorld", "HelloWorld", "HelLOWord", "PicUrl1", "XyXX"}
snake := []string{"id", "pic_url", "hello_world", "hello_world", "hel_lo_word", "pic_url1", "xy_xx"}
answer := make(map[string]string)
for i, v := range camel {
answer[v] = snake[i]
}
for _, v := range camel {
res := snakeStringWithAcronym(v)
if res != answer[v] {
t.Error("Unit Test Fail:", v, res, answer[v])
}
}
}

View File

@ -0,0 +1,94 @@
// 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 apiauth provides handlers to enable apiauth support.
//
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/apiauth"
// )
//
// func main(){
// // apiauth every request
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIBaiscAuth("appid","appkey"))
// beego.Run()
// }
//
// Advanced Usage:
//
// func getAppSecret(appid string) string {
// // get appsecret by appid
// // maybe store in configure, maybe in database
// }
//
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APISecretAuth(getAppSecret, 360))
//
// Information:
//
// In the request user should include these params in the query
//
// 1. appid
//
// appid is assigned to the application
//
// 2. signature
//
// get the signature use apiauth.Signature()
//
// when you send to server remember use url.QueryEscape()
//
// 3. timestamp:
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
//
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"
)
// AppIDToAppSecret is used to get appsecret throw appid
type AppIDToAppSecret apiauth.AppIDToAppSecret
// APIBasicAuth use the basic appid/appkey as the AppIdToAppSecret
func APIBasicAuth(appid, appkey string) beego.FilterFunc {
f := apiauth.APIBasicAuth(appid, appkey)
return func(c *context.Context) {
f((*beecontext.Context)(c))
}
}
// APIBaiscAuth calls APIBasicAuth for previous callers
func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
return APIBasicAuth(appid, appkey)
}
// APISecretAuth use AppIdToAppSecret verify and
func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc {
ft := apiauth.APISecretAuth(apiauth.AppIDToAppSecret(f), timeout)
return func(ctx *context.Context) {
ft((*beecontext.Context)(ctx))
}
}
// Signature used to generate signature with the appsecret/method/params/RequestURI
func Signature(appsecret, method string, params url.Values, requestURL string) string {
return apiauth.Signature(appsecret, method, params, requestURL)
}

View File

@ -0,0 +1,20 @@
package apiauth
import (
"net/url"
"testing"
)
func TestSignature(t *testing.T) {
appsecret := "beego secret"
method := "GET"
RequestURL := "http://localhost/test/url"
params := make(url.Values)
params.Add("arg1", "hello")
params.Add("arg2", "beego")
signature := "mFdpvLh48ca4mDVEItE9++AKKQ/IVca7O/ZyyB8hR58="
if Signature(appsecret, method, params, RequestURL) != signature {
t.Error("Signature error")
}
}

View File

@ -0,0 +1,81 @@
// 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 auth provides handlers to enable basic auth support.
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/auth"
// )
//
// func main(){
// // authenticate every request
// beego.InsertFilter("*", beego.BeforeRouter,auth.Basic("username","secretpassword"))
// beego.Run()
// }
//
//
// Advanced Usage:
//
// func SecretAuth(username, password string) bool {
// return username == "astaxie" && password == "helloBeego"
// }
// authPlugin := auth.NewBasicAuthenticator(SecretAuth, "Authorization Required")
// beego.InsertFilter("*", beego.BeforeRouter,authPlugin)
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"
)
// Basic is the http basic auth
func Basic(username string, password string) beego.FilterFunc {
return func(c *context.Context) {
f := auth.Basic(username, password)
f((*beecontext.Context)(c))
}
}
// NewBasicAuthenticator return the BasicAuth
func NewBasicAuthenticator(secrets SecretProvider, realm string) beego.FilterFunc {
f := auth.NewBasicAuthenticator(auth.SecretProvider(secrets), realm)
return func(c *context.Context) {
f((*beecontext.Context)(c))
}
}
// SecretProvider is the SecretProvider function
type SecretProvider auth.SecretProvider
// BasicAuth store the SecretProvider and Realm
type BasicAuth auth.BasicAuth
// CheckAuth Checks the username/password combination from the request. Returns
// either an empty string (authentication failed) or the name of the
// authenticated user.
// Supports MD5 and SHA1 password entries
func (a *BasicAuth) CheckAuth(r *http.Request) string {
return (*auth.BasicAuth)(a).CheckAuth(r)
}
// RequireAuth http.Handler for BasicAuth which initiates the authentication process
// (or requires reauthentication).
func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) {
(*auth.BasicAuth)(a).RequireAuth(w, r)
}

View File

@ -0,0 +1,80 @@
// 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 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/casbin/casbin"
// )
//
// func main(){
// // mediate the access for every request
// beego.InsertFilter("*", beego.BeforeRouter, authz.NewAuthorizer(casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")))
// beego.Run()
// }
//
//
// Advanced Usage:
//
// func main(){
// e := casbin.NewEnforcer("authz_model.conf", "")
// e.AddRoleForUser("alice", "admin")
// e.AddPolicy(...)
//
// beego.InsertFilter("*", beego.BeforeRouter, authz.NewAuthorizer(e))
// beego.Run()
// }
package authz
import (
"net/http"
"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"
)
// NewAuthorizer returns the authorizer.
// Use a casbin enforcer as input
func NewAuthorizer(e *casbin.Enforcer) beego.FilterFunc {
f := authz.NewAuthorizer(e)
return func(context *context.Context) {
f((*beecontext.Context)(context))
}
}
// BasicAuthorizer stores the casbin handler
type BasicAuthorizer authz.BasicAuthorizer
// GetUserName gets the user name from the request.
// Currently, only HTTP basic authentication is supported
func (a *BasicAuthorizer) GetUserName(r *http.Request) string {
return (*authz.BasicAuthorizer)(a).GetUserName(r)
}
// CheckPermission checks the user/method/path combination from the request.
// Returns true (permission granted) or false (permission forbidden)
func (a *BasicAuthorizer) CheckPermission(r *http.Request) bool {
return (*authz.BasicAuthorizer)(a).CheckPermission(r)
}
// RequirePermission returns the 403 Forbidden to the client
func (a *BasicAuthorizer) RequirePermission(w http.ResponseWriter) {
(*authz.BasicAuthorizer)(a).RequirePermission(w)
}

View File

@ -0,0 +1,14 @@
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

View File

@ -0,0 +1,7 @@
p, alice, /dataset1/*, GET
p, alice, /dataset1/resource1, POST
p, bob, /dataset2/resource1, *
p, bob, /dataset2/resource2, GET
p, bob, /dataset2/folder1/*, POST
p, dataset1_admin, /dataset1/*, *
g, cathy, dataset1_admin
1 p, alice, /dataset1/*, GET
2 p, alice, /dataset1/resource1, POST
3 p, bob, /dataset2/resource1, *
4 p, bob, /dataset2/resource2, GET
5 p, bob, /dataset2/folder1/*, POST
6 p, dataset1_admin, /dataset1/*, *
7 g, cathy, dataset1_admin

View File

@ -0,0 +1,108 @@
// 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 authz
import (
"net/http"
"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"
)
func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, path string, method string, code int) {
r, _ := http.NewRequest(method, path, nil)
r.SetBasicAuth(user, "123")
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != code {
t.Errorf("%s, %s, %s: %d, supposed to be %d", user, path, method, w.Code, code)
}
}
func TestBasic(t *testing.T) {
handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("alice", "123"))
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")))
handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200)
})
testRequest(t, handler, "alice", "/dataset1/resource1", "GET", 200)
testRequest(t, handler, "alice", "/dataset1/resource1", "POST", 200)
testRequest(t, handler, "alice", "/dataset1/resource2", "GET", 200)
testRequest(t, handler, "alice", "/dataset1/resource2", "POST", 403)
}
func TestPathWildcard(t *testing.T) {
handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("bob", "123"))
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")))
handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200)
})
testRequest(t, handler, "bob", "/dataset2/resource1", "GET", 200)
testRequest(t, handler, "bob", "/dataset2/resource1", "POST", 200)
testRequest(t, handler, "bob", "/dataset2/resource1", "DELETE", 200)
testRequest(t, handler, "bob", "/dataset2/resource2", "GET", 200)
testRequest(t, handler, "bob", "/dataset2/resource2", "POST", 403)
testRequest(t, handler, "bob", "/dataset2/resource2", "DELETE", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "GET", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "POST", 200)
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "DELETE", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "GET", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "POST", 200)
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "DELETE", 403)
}
func TestRBAC(t *testing.T) {
handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("cathy", "123"))
e := casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(e))
handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200)
})
// cathy can access all /dataset1/* resources via all methods because it has the dataset1_admin role.
testRequest(t, handler, "cathy", "/dataset1/item", "GET", 200)
testRequest(t, handler, "cathy", "/dataset1/item", "POST", 200)
testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 200)
testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403)
// delete all roles on user cathy, so cathy cannot access any resources now.
e.DeleteRolesForUser("cathy")
testRequest(t, handler, "cathy", "/dataset1/item", "GET", 403)
testRequest(t, handler, "cathy", "/dataset1/item", "POST", 403)
testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403)
}

View File

@ -0,0 +1,71 @@
// 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 cors provides handlers to enable CORS support.
// Usage
// import (
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/cors"
// )
//
// func main() {
// // CORS for https://foo.* origins, allowing:
// // - PUT and PATCH methods
// // - Origin header
// // - Credentials share
// beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
// AllowOrigins: []string{"https://*.foo.com"},
// AllowMethods: []string{"PUT", "PATCH"},
// AllowHeaders: []string{"Origin"},
// ExposeHeaders: []string{"Content-Length"},
// AllowCredentials: true,
// }))
// beego.Run()
// }
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"
"github.com/astaxie/beego/adapter/context"
)
// Options represents Access Control options.
type Options cors.Options
// Header converts options into CORS headers.
func (o *Options) Header(origin string) (headers map[string]string) {
return (*cors.Options)(o).Header(origin)
}
// PreflightHeader converts options into CORS headers for a preflight response.
func (o *Options) PreflightHeader(origin, rMethod, rHeaders string) (headers map[string]string) {
return (*cors.Options)(o).PreflightHeader(origin, rMethod, rHeaders)
}
// IsOriginAllowed looks up if the origin matches one of the patterns
// generated from Options.AllowOrigins patterns.
func (o *Options) IsOriginAllowed(origin string) bool {
return (*cors.Options)(o).IsOriginAllowed(origin)
}
// Allow enables CORS for requests those match the provided options.
func Allow(opts *Options) beego.FilterFunc {
f := cors.Allow((*cors.Options)(opts))
return func(c *context.Context) {
f((*beecontext.Context)(c))
}
}

57
adapter/policy.go Normal file
View File

@ -0,0 +1,57 @@
// Copyright 2016 beego authors. 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/context"
"github.com/astaxie/beego/server/web"
beecontext "github.com/astaxie/beego/server/web/context"
)
// PolicyFunc defines a policy function which is invoked before the controller handler is executed.
type PolicyFunc func(*context.Context)
// FindPolicy Find Router info for URL
func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc {
pf := (*web.ControllerRegister)(p).FindPolicy((*beecontext.Context)(cont))
npf := newToOldPolicyFunc(pf)
return npf
}
func newToOldPolicyFunc(pf []web.PolicyFunc) []PolicyFunc {
npf := make([]PolicyFunc, 0, len(pf))
for _, f := range pf {
npf = append(npf, func(c *context.Context) {
f((*beecontext.Context)(c))
})
}
return npf
}
func oldToNewPolicyFunc(pf []PolicyFunc) []web.PolicyFunc {
npf := make([]web.PolicyFunc, 0, len(pf))
for _, f := range pf {
npf = append(npf, func(c *beecontext.Context) {
f((*context.Context)(c))
})
}
return npf
}
// Policy Register new policy in beego
func Policy(pattern, method string, policy ...PolicyFunc) {
pf := oldToNewPolicyFunc(policy)
web.Policy(pattern, method, pf...)
}

282
adapter/router.go Normal file
View File

@ -0,0 +1,282 @@
// 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"
"time"
beecontext "github.com/astaxie/beego/adapter/context"
"github.com/astaxie/beego/server/web/context"
"github.com/astaxie/beego/server/web"
)
// default filter execution points
const (
BeforeStatic = web.BeforeStatic
BeforeRouter = web.BeforeRouter
BeforeExec = web.BeforeExec
AfterExec = web.AfterExec
FinishRouter = web.FinishRouter
)
var (
// HTTPMETHOD list the supported http methods.
HTTPMETHOD = web.HTTPMETHOD
// DefaultAccessLogFilter will skip the accesslog if return true
DefaultAccessLogFilter FilterHandler = &newToOldFtHdlAdapter{
delegate: web.DefaultAccessLogFilter,
}
)
// FilterHandler is an interface for
type FilterHandler interface {
Filter(*beecontext.Context) bool
}
type newToOldFtHdlAdapter struct {
delegate web.FilterHandler
}
func (n *newToOldFtHdlAdapter) Filter(ctx *beecontext.Context) bool {
return n.delegate.Filter((*context.Context)(ctx))
}
// ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
func ExceptMethodAppend(action string) {
web.ExceptMethodAppend(action)
}
// ControllerInfo holds information about the controller.
type ControllerInfo web.ControllerInfo
func (c *ControllerInfo) GetPattern() string {
return (*web.ControllerInfo)(c).GetPattern()
}
// ControllerRegister containers registered router rules, controller handlers and filters.
type ControllerRegister web.ControllerRegister
// NewControllerRegister returns a new ControllerRegister.
func NewControllerRegister() *ControllerRegister {
return (*ControllerRegister)(web.NewControllerRegister())
}
// Add controller handler and pattern rules to ControllerRegister.
// usage:
// default methods is the same name as method
// Add("/user",&UserController{})
// Add("/api/list",&RestController{},"*:ListFood")
// Add("/api/create",&RestController{},"post:CreateFood")
// Add("/api/update",&RestController{},"put:UpdateFood")
// 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) {
(*web.ControllerRegister)(p).Add(pattern, c, mappingMethods...)
}
// Include only when the Runmode is dev will generate router file in the router/auto.go from the controller
// Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
func (p *ControllerRegister) Include(cList ...ControllerInterface) {
nls := oldToNewCtrlIntfs(cList)
(*web.ControllerRegister)(p).Include(nls...)
}
// GetContext returns a context from pool, so usually you should remember to call Reset function to clean the context
// And don't forget to give back context to pool
// example:
// ctx := p.GetContext()
// ctx.Reset(w, q)
// defer p.GiveBackContext(ctx)
func (p *ControllerRegister) GetContext() *beecontext.Context {
return (*beecontext.Context)((*web.ControllerRegister)(p).GetContext())
}
// GiveBackContext put the ctx into pool so that it could be reuse
func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context) {
(*web.ControllerRegister)(p).GiveBackContext((*context.Context)(ctx))
}
// Get add get method
// usage:
// Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Get(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Post add post method
// usage:
// Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Post(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Put add put method
// usage:
// Put("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Put(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Delete add delete method
// usage:
// Delete("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Delete(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Head add head method
// usage:
// Head("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Head(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Patch add patch method
// usage:
// Patch("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Patch(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Options add options method
// usage:
// Options("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Options(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Any add all method
// usage:
// Any("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Any(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// AddMethod add http method router
// usage:
// AddMethod("get","/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).AddMethod(method, pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
})
}
// Handler add user defined Handler
func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) {
(*web.ControllerRegister)(p).Handler(pattern, h, options)
}
// AddAuto router to ControllerRegister.
// example beego.AddAuto(&MainContorlller{}),
// MainController has method List and Page.
// visit the url /main/list to execute List function
// /main/page to execute Page function.
func (p *ControllerRegister) AddAuto(c ControllerInterface) {
(*web.ControllerRegister)(p).AddAuto(c)
}
// AddAutoPrefix Add auto router to ControllerRegister with prefix.
// example beego.AddAutoPrefix("/admin",&MainContorlller{}),
// MainController has method List and Page.
// visit the url /admin/main/list to execute List function
// /admin/main/page to execute Page function.
func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) {
(*web.ControllerRegister)(p).AddAutoPrefix(prefix, c)
}
// InsertFilter Add a FilterFunc with pattern rule and action constant.
// params is for:
// 1. setting the returnOnOutput value (false allows multiple filters to execute)
// 2. determining whether or not params need to be reset.
func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
opts := oldToNewFilterOpts(params)
return (*web.ControllerRegister)(p).InsertFilter(pattern, pos, func(ctx *context.Context) {
filter((*beecontext.Context)(ctx))
}, opts...)
}
func oldToNewFilterOpts(params []bool) []web.FilterOpt {
opts := make([]web.FilterOpt, 0, 4)
if len(params) > 0 {
opts = append(opts, web.WithReturnOnOutput(params[0]))
} else {
// the default value should be true
opts = append(opts, web.WithReturnOnOutput(true))
}
if len(params) > 1 {
opts = append(opts, web.WithResetParams(params[1]))
}
return opts
}
// URLFor does another controller handler in this request function.
// it can access any controller method.
func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string {
return (*web.ControllerRegister)(p).URLFor(endpoint, values...)
}
// Implement http.Handler interface.
func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
(*web.ControllerRegister)(p).ServeHTTP(rw, r)
}
// FindRouter Find Router info for URL
func (p *ControllerRegister) FindRouter(ctx *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
r, ok := (*web.ControllerRegister)(p).FindRouter((*context.Context)(ctx))
return (*ControllerInfo)(r), ok
}
// LogAccess logging info HTTP Access
func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int) {
web.LogAccess((*context.Context)(ctx), startTime, statusCode)
}

View File

@ -0,0 +1,118 @@
// 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 couchbase for session provider
//
// depend on github.com/couchbaselabs/go-couchbasee
//
// go install github.com/couchbaselabs/go-couchbase
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/couchbase"
// "github.com/astaxie/beego/session"
// )
//
// func init() {
// globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``)
// go globalSessions.GC()
// }
//
// more docs: http://beego.me/docs/module/session.md
package couchbase
import (
"context"
"net/http"
"github.com/astaxie/beego/adapter/session"
beecb "github.com/astaxie/beego/server/web/session/couchbase"
)
// SessionStore store each session
type SessionStore beecb.SessionStore
// Provider couchabse provided
type Provider beecb.Provider
// Set value to couchabse session
func (cs *SessionStore) Set(key, value interface{}) error {
return (*beecb.SessionStore)(cs).Set(context.Background(), key, value)
}
// Get value from couchabse session
func (cs *SessionStore) Get(key interface{}) interface{} {
return (*beecb.SessionStore)(cs).Get(context.Background(), key)
}
// Delete value in couchbase session by given key
func (cs *SessionStore) Delete(key interface{}) error {
return (*beecb.SessionStore)(cs).Delete(context.Background(), key)
}
// Flush Clean all values in couchbase session
func (cs *SessionStore) Flush() error {
return (*beecb.SessionStore)(cs).Flush(context.Background())
}
// SessionID Get couchbase session store id
func (cs *SessionStore) SessionID() string {
return (*beecb.SessionStore)(cs).SessionID(context.Background())
}
// SessionRelease Write couchbase session with Gob string
func (cs *SessionStore) SessionRelease(w http.ResponseWriter) {
(*beecb.SessionStore)(cs).SessionRelease(context.Background(), w)
}
// SessionInit init couchbase session
// savepath like couchbase server REST/JSON URL
// e.g. http://host:port/, Pool, Bucket
func (cp *Provider) SessionInit(maxlifetime int64, savePath string) error {
return (*beecb.Provider)(cp).SessionInit(context.Background(), maxlifetime, savePath)
}
// SessionRead read couchbase session by sid
func (cp *Provider) SessionRead(sid string) (session.Store, error) {
s, err := (*beecb.Provider)(cp).SessionRead(context.Background(), sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionExist Check couchbase session exist.
// it checkes sid exist or not.
func (cp *Provider) SessionExist(sid string) bool {
res, _ := (*beecb.Provider)(cp).SessionExist(context.Background(), sid)
return res
}
// SessionRegenerate remove oldsid and use sid to generate new session
func (cp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
s, err := (*beecb.Provider)(cp).SessionRegenerate(context.Background(), oldsid, sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionDestroy Remove bucket in this couchbase
func (cp *Provider) SessionDestroy(sid string) error {
return (*beecb.Provider)(cp).SessionDestroy(context.Background(), sid)
}
// SessionGC Recycle
func (cp *Provider) SessionGC() {
(*beecb.Provider)(cp).SessionGC(context.Background())
}
// SessionAll return all active session
func (cp *Provider) SessionAll() int {
return (*beecb.Provider)(cp).SessionAll(context.Background())
}

View File

@ -0,0 +1,86 @@
// Package ledis provide session Provider
package ledis
import (
"context"
"net/http"
"github.com/astaxie/beego/adapter/session"
beeLedis "github.com/astaxie/beego/server/web/session/ledis"
)
// SessionStore ledis session store
type SessionStore beeLedis.SessionStore
// Set value in ledis session
func (ls *SessionStore) Set(key, value interface{}) error {
return (*beeLedis.SessionStore)(ls).Set(context.Background(), key, value)
}
// Get value in ledis session
func (ls *SessionStore) Get(key interface{}) interface{} {
return (*beeLedis.SessionStore)(ls).Get(context.Background(), key)
}
// Delete value in ledis session
func (ls *SessionStore) Delete(key interface{}) error {
return (*beeLedis.SessionStore)(ls).Delete(context.Background(), key)
}
// Flush clear all values in ledis session
func (ls *SessionStore) Flush() error {
return (*beeLedis.SessionStore)(ls).Flush(context.Background())
}
// SessionID get ledis session id
func (ls *SessionStore) SessionID() string {
return (*beeLedis.SessionStore)(ls).SessionID(context.Background())
}
// SessionRelease save session values to ledis
func (ls *SessionStore) SessionRelease(w http.ResponseWriter) {
(*beeLedis.SessionStore)(ls).SessionRelease(context.Background(), w)
}
// Provider ledis session provider
type Provider beeLedis.Provider
// SessionInit init ledis session
// savepath like ledis server saveDataPath,pool size
// e.g. 127.0.0.1:6379,100,astaxie
func (lp *Provider) SessionInit(maxlifetime int64, savePath string) error {
return (*beeLedis.Provider)(lp).SessionInit(context.Background(), maxlifetime, savePath)
}
// SessionRead read ledis session by sid
func (lp *Provider) SessionRead(sid string) (session.Store, error) {
s, err := (*beeLedis.Provider)(lp).SessionRead(context.Background(), sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionExist check ledis session exist by sid
func (lp *Provider) SessionExist(sid string) bool {
res, _ := (*beeLedis.Provider)(lp).SessionExist(context.Background(), sid)
return res
}
// SessionRegenerate generate new sid for ledis session
func (lp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
s, err := (*beeLedis.Provider)(lp).SessionRegenerate(context.Background(), oldsid, sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionDestroy delete ledis session by id
func (lp *Provider) SessionDestroy(sid string) error {
return (*beeLedis.Provider)(lp).SessionDestroy(context.Background(), sid)
}
// SessionGC Impelment method, no used.
func (lp *Provider) SessionGC() {
(*beeLedis.Provider)(lp).SessionGC(context.Background())
}
// SessionAll return all active session
func (lp *Provider) SessionAll() int {
return (*beeLedis.Provider)(lp).SessionAll(context.Background())
}

View File

@ -0,0 +1,118 @@
// 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 session provider
//
// depend on github.com/bradfitz/gomemcache/memcache
//
// go install github.com/bradfitz/gomemcache/memcache
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/memcache"
// "github.com/astaxie/beego/session"
// )
//
// func init() {
// globalSessions, _ = session.NewManager("memcache", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}``)
// go globalSessions.GC()
// }
//
// more docs: http://beego.me/docs/module/session.md
package memcache
import (
"context"
"net/http"
"github.com/astaxie/beego/adapter/session"
beemem "github.com/astaxie/beego/server/web/session/memcache"
)
// SessionStore memcache session store
type SessionStore beemem.SessionStore
// Set value in memcache session
func (rs *SessionStore) Set(key, value interface{}) error {
return (*beemem.SessionStore)(rs).Set(context.Background(), key, value)
}
// Get value in memcache session
func (rs *SessionStore) Get(key interface{}) interface{} {
return (*beemem.SessionStore)(rs).Get(context.Background(), key)
}
// Delete value in memcache session
func (rs *SessionStore) Delete(key interface{}) error {
return (*beemem.SessionStore)(rs).Delete(context.Background(), key)
}
// Flush clear all values in memcache session
func (rs *SessionStore) Flush() error {
return (*beemem.SessionStore)(rs).Flush(context.Background())
}
// SessionID get memcache session id
func (rs *SessionStore) SessionID() string {
return (*beemem.SessionStore)(rs).SessionID(context.Background())
}
// SessionRelease save session values to memcache
func (rs *SessionStore) SessionRelease(w http.ResponseWriter) {
(*beemem.SessionStore)(rs).SessionRelease(context.Background(), w)
}
// MemProvider memcache session provider
type MemProvider beemem.MemProvider
// SessionInit init memcache session
// savepath like
// e.g. 127.0.0.1:9090
func (rp *MemProvider) SessionInit(maxlifetime int64, savePath string) error {
return (*beemem.MemProvider)(rp).SessionInit(context.Background(), maxlifetime, savePath)
}
// SessionRead read memcache session by sid
func (rp *MemProvider) SessionRead(sid string) (session.Store, error) {
s, err := (*beemem.MemProvider)(rp).SessionRead(context.Background(), sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionExist check memcache session exist by sid
func (rp *MemProvider) SessionExist(sid string) bool {
res, _ := (*beemem.MemProvider)(rp).SessionExist(context.Background(), sid)
return res
}
// SessionRegenerate generate new sid for memcache session
func (rp *MemProvider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
s, err := (*beemem.MemProvider)(rp).SessionRegenerate(context.Background(), oldsid, sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionDestroy delete memcache session by id
func (rp *MemProvider) SessionDestroy(sid string) error {
return (*beemem.MemProvider)(rp).SessionDestroy(context.Background(), sid)
}
// SessionGC Impelment method, no used.
func (rp *MemProvider) SessionGC() {
(*beemem.MemProvider)(rp).SessionGC(context.Background())
}
// SessionAll return all activeSession
func (rp *MemProvider) SessionAll() int {
return (*beemem.MemProvider)(rp).SessionAll(context.Background())
}

View File

@ -0,0 +1,135 @@
// 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 mysql for session provider
//
// depends on github.com/go-sql-driver/mysql:
//
// go install github.com/go-sql-driver/mysql
//
// mysql session support need create table as sql:
// CREATE TABLE `session` (
// `session_key` char(64) NOT NULL,
// `session_data` blob,
// `session_expiry` int(11) unsigned NOT NULL,
// PRIMARY KEY (`session_key`)
// ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/mysql"
// "github.com/astaxie/beego/session"
// )
//
// func init() {
// globalSessions, _ = session.NewManager("mysql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}``)
// go globalSessions.GC()
// }
//
// more docs: http://beego.me/docs/module/session.md
package mysql
import (
"context"
"net/http"
"github.com/astaxie/beego/adapter/session"
"github.com/astaxie/beego/server/web/session/mysql"
// import mysql driver
_ "github.com/go-sql-driver/mysql"
)
var (
// TableName store the session in MySQL
TableName = mysql.TableName
mysqlpder = &Provider{}
)
// SessionStore mysql session store
type SessionStore mysql.SessionStore
// Set value in mysql session.
// it is temp value in map.
func (st *SessionStore) Set(key, value interface{}) error {
return (*mysql.SessionStore)(st).Set(context.Background(), key, value)
}
// Get value from mysql session
func (st *SessionStore) Get(key interface{}) interface{} {
return (*mysql.SessionStore)(st).Get(context.Background(), key)
}
// Delete value in mysql session
func (st *SessionStore) Delete(key interface{}) error {
return (*mysql.SessionStore)(st).Delete(context.Background(), key)
}
// Flush clear all values in mysql session
func (st *SessionStore) Flush() error {
return (*mysql.SessionStore)(st).Flush(context.Background())
}
// SessionID get session id of this mysql session store
func (st *SessionStore) SessionID() string {
return (*mysql.SessionStore)(st).SessionID(context.Background())
}
// SessionRelease save mysql session values to database.
// must call this method to save values to database.
func (st *SessionStore) SessionRelease(w http.ResponseWriter) {
(*mysql.SessionStore)(st).SessionRelease(context.Background(), w)
}
// Provider mysql session provider
type Provider mysql.Provider
// SessionInit init mysql session.
// savepath is the connection string of mysql.
func (mp *Provider) SessionInit(maxlifetime int64, savePath string) error {
return (*mysql.Provider)(mp).SessionInit(context.Background(), maxlifetime, savePath)
}
// SessionRead get mysql session by sid
func (mp *Provider) SessionRead(sid string) (session.Store, error) {
s, err := (*mysql.Provider)(mp).SessionRead(context.Background(), sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionExist check mysql session exist
func (mp *Provider) SessionExist(sid string) bool {
res, _ := (*mysql.Provider)(mp).SessionExist(context.Background(), sid)
return res
}
// SessionRegenerate generate new sid for mysql session
func (mp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
s, err := (*mysql.Provider)(mp).SessionRegenerate(context.Background(), oldsid, sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionDestroy delete mysql session by sid
func (mp *Provider) SessionDestroy(sid string) error {
return (*mysql.Provider)(mp).SessionDestroy(context.Background(), sid)
}
// SessionGC delete expired values in mysql session
func (mp *Provider) SessionGC() {
(*mysql.Provider)(mp).SessionGC(context.Background())
}
// SessionAll count values in mysql session
func (mp *Provider) SessionAll() int {
return (*mysql.Provider)(mp).SessionAll(context.Background())
}

View File

@ -0,0 +1,139 @@
// 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 postgres for session provider
//
// depends on github.com/lib/pq:
//
// go install github.com/lib/pq
//
//
// needs this table in your database:
//
// CREATE TABLE session (
// session_key char(64) NOT NULL,
// session_data bytea,
// session_expiry timestamp NOT NULL,
// CONSTRAINT session_key PRIMARY KEY(session_key)
// );
//
// will be activated with these settings in app.conf:
//
// SessionOn = true
// SessionProvider = postgresql
// SessionSavePath = "user=a password=b dbname=c sslmode=disable"
// SessionName = session
//
//
// Usage:
// import(
// _ "github.com/astaxie/beego/session/postgresql"
// "github.com/astaxie/beego/session"
// )
//
// func init() {
// globalSessions, _ = session.NewManager("postgresql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}``)
// go globalSessions.GC()
// }
//
// more docs: http://beego.me/docs/module/session.md
package postgres
import (
"context"
"net/http"
"github.com/astaxie/beego/adapter/session"
// import postgresql Driver
_ "github.com/lib/pq"
"github.com/astaxie/beego/server/web/session/postgres"
)
// SessionStore postgresql session store
type SessionStore postgres.SessionStore
// Set value in postgresql session.
// it is temp value in map.
func (st *SessionStore) Set(key, value interface{}) error {
return (*postgres.SessionStore)(st).Set(context.Background(), key, value)
}
// Get value from postgresql session
func (st *SessionStore) Get(key interface{}) interface{} {
return (*postgres.SessionStore)(st).Get(context.Background(), key)
}
// Delete value in postgresql session
func (st *SessionStore) Delete(key interface{}) error {
return (*postgres.SessionStore)(st).Delete(context.Background(), key)
}
// Flush clear all values in postgresql session
func (st *SessionStore) Flush() error {
return (*postgres.SessionStore)(st).Flush(context.Background())
}
// SessionID get session id of this postgresql session store
func (st *SessionStore) SessionID() string {
return (*postgres.SessionStore)(st).SessionID(context.Background())
}
// SessionRelease save postgresql session values to database.
// must call this method to save values to database.
func (st *SessionStore) SessionRelease(w http.ResponseWriter) {
(*postgres.SessionStore)(st).SessionRelease(context.Background(), w)
}
// Provider postgresql session provider
type Provider postgres.Provider
// SessionInit init postgresql session.
// savepath is the connection string of postgresql.
func (mp *Provider) SessionInit(maxlifetime int64, savePath string) error {
return (*postgres.Provider)(mp).SessionInit(context.Background(), maxlifetime, savePath)
}
// SessionRead get postgresql session by sid
func (mp *Provider) SessionRead(sid string) (session.Store, error) {
s, err := (*postgres.Provider)(mp).SessionRead(context.Background(), sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionExist check postgresql session exist
func (mp *Provider) SessionExist(sid string) bool {
res, _ := (*postgres.Provider)(mp).SessionExist(context.Background(), sid)
return res
}
// SessionRegenerate generate new sid for postgresql session
func (mp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
s, err := (*postgres.Provider)(mp).SessionRegenerate(context.Background(), oldsid, sid)
return session.CreateNewToOldStoreAdapter(s), err
}
// SessionDestroy delete postgresql session by sid
func (mp *Provider) SessionDestroy(sid string) error {
return (*postgres.Provider)(mp).SessionDestroy(context.Background(), sid)
}
// SessionGC delete expired values in postgresql session
func (mp *Provider) SessionGC() {
(*postgres.Provider)(mp).SessionGC(context.Background())
}
// SessionAll count values in postgresql session
func (mp *Provider) SessionAll() int {
return (*postgres.Provider)(mp).SessionAll(context.Background())
}

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