Compare commits
932 Commits
Author | SHA1 | Date | |
---|---|---|---|
0692f92890 | |||
41adcf9966 | |||
e6b42a4070 | |||
bc4780091b | |||
d8614e80e7 | |||
c83a2a0925 | |||
50a21d60c1 | |||
5a087b28d2 | |||
9b40271878 | |||
770dc702f0 | |||
e146100a23 | |||
2d94f7797b | |||
61ce608847 | |||
2fe559701c | |||
37fe175c26 | |||
fcc9d8c45f | |||
e51a9d6481 | |||
e9a1daa3ee | |||
44ea260db1 | |||
1d1ad69954 | |||
59773dfabe | |||
ccb61f0416 | |||
14629c214b | |||
a3888cef7f | |||
f6a1a6c9bf | |||
38ee43701d | |||
421b796f1a | |||
771179a3c6 | |||
c07b1d881b | |||
d8f2b05e08 | |||
7b2fe824d5 | |||
02301caac1 | |||
98c2307763 | |||
485c2e865c | |||
b390667374 | |||
f684de2385 | |||
35b4022ee0 | |||
77294a5881 | |||
7b39bd7042 | |||
01e4084587 | |||
bf429a3a20 | |||
f8ff79d77d | |||
e9487d3571 | |||
d7c3727f96 | |||
03eb1fc104 | |||
0a967875da | |||
6ae8bc1a16 | |||
e70537f8b3 | |||
9a583323a8 | |||
ff9c8d94e6 | |||
7f977a0c8c | |||
aaabeff44f | |||
f85ac088c3 | |||
26da23266a | |||
80274684e0 | |||
be005f9774 | |||
c16b7be9ac | |||
de87529387 | |||
c4fa17921e | |||
724137e605 | |||
a144769515 | |||
05089be427 | |||
7668c54d05 | |||
86752a55b6 | |||
e07d780dcf | |||
e566322643 | |||
51ee1e77c2 | |||
986e91b7d6 | |||
8b8638c507 | |||
d27c5c8daf | |||
86121deac4 | |||
6b02e1e9d4 | |||
83696d95c3 | |||
7be8114616 | |||
1dbbb89ad1 | |||
75904effd9 | |||
cd9e614a71 | |||
c1234e7c6d | |||
b611b9dab6 | |||
cad3da337a | |||
3969cd3b40 | |||
f4867aad5a | |||
17006cfb26 | |||
7d1b03ee5d | |||
84a4379f0d | |||
ab71201c96 | |||
c347dd9e7b | |||
75e2611cc4 | |||
d314d12c77 | |||
564c3bbeb5 | |||
31f0ac4ce3 | |||
57a9670b0a | |||
14cd9e51ac | |||
886bb782a5 | |||
d2119f715c | |||
f98b1810ab | |||
55a7711017 | |||
436edda926 | |||
1f1190fbc3 | |||
20463fa725 | |||
ae37f95239 | |||
da6726f3da | |||
32469cd69d | |||
e572f45296 | |||
efcaa3d934 | |||
5ecfe0c335 | |||
d325a66fee | |||
fe9017c819 | |||
b97279a74f | |||
6a78898bb1 | |||
f201859fa7 | |||
52fdfc5665 | |||
8ed6d06572 | |||
b5a2347e1d | |||
118e07158e | |||
7a376c32be | |||
3d74a1a436 | |||
00eac0e4cb | |||
58ac0d5ea4 | |||
2773fda883 | |||
99c03a2b9c | |||
b1b4dbb0e4 | |||
77e1f26dd4 | |||
2820f630c8 | |||
1f6c5599aa | |||
df8c73b23a | |||
ea6982fcea | |||
a3f40234ca | |||
2c420573d4 | |||
c0d3cc6fc5 | |||
3f7ecea089 | |||
f4147058fc | |||
1fb24aca34 | |||
885c0678ff | |||
d7a5281bda | |||
474a16a7a0 | |||
1d36b19cab | |||
deed251794 | |||
22ba252c8f | |||
289f050c04 | |||
bbd31131a4 | |||
008ae39ff6 | |||
0836b9e13f | |||
7a39a3c52f | |||
509af636b1 | |||
daf8b1101f | |||
428aec1c24 | |||
a804d242d9 | |||
7ddd20340b | |||
e7fcb824c1 | |||
ee9749d640 | |||
d7090689e8 | |||
52d153da87 | |||
6ce55e8884 | |||
91ee42ceeb | |||
d17f107fc4 | |||
ae8bb8ce82 | |||
38188098c5 | |||
c372328f88 | |||
a6ced64441 | |||
69094b2786 | |||
08397fef45 | |||
84da1c924a | |||
f733b5707a | |||
9d0798edc6 | |||
1858f3073b | |||
e6d6419a65 | |||
e52386b52d | |||
024817aacb | |||
9d0ad3f974 | |||
6357c88d97 | |||
9457e61a0c | |||
f657509a42 | |||
20e05a3908 | |||
77c40e6f7b | |||
ea2ed90ab0 | |||
15759f60ed | |||
0e3e22efbe | |||
a906bf1174 | |||
a6379481cf | |||
7d09ac252a | |||
0ff058bd25 | |||
dbe75f90d5 | |||
ca1fd96ea5 | |||
0b1b121db8 | |||
8683ee7c67 | |||
007db805be | |||
19c3a5b41c | |||
e635e274d4 | |||
46cde6e579 | |||
3bb4d6f013 | |||
cec151fda7 | |||
b6c4e27a75 | |||
2933d1fedd | |||
cbffcaa7a8 | |||
707c951302 | |||
fefd8ddb5b | |||
14dee37a21 | |||
17a9c3c3a9 | |||
8946f816f9 | |||
36ba1e49b1 | |||
34936dde35 | |||
aa004ed973 | |||
53353fce56 | |||
f92ce9af96 | |||
8b021c8ea1 | |||
34572193c6 | |||
4dde2c59ff | |||
c83c17d917 | |||
4994d36b66 | |||
a991b9dcde | |||
3fe9e6a28a | |||
62e9c89010 | |||
ac96c2b15e | |||
0f170a80da | |||
9c5348f690 | |||
90f91b10c5 | |||
a5a6a30744 | |||
1f6e689e5d | |||
7b7a95677a | |||
af4f153830 | |||
469f283b68 | |||
085c362ffb | |||
c3a07555c4 | |||
2b8e411174 | |||
720a77c1f9 | |||
b943b74fc5 | |||
67be7b532d | |||
8be83fe488 | |||
cff632f553 | |||
4990d88861 | |||
7075ad8a28 | |||
0e278ae358 | |||
e38a23b30e | |||
117904be73 | |||
3b807845f2 | |||
00b710e168 | |||
e25fcffbc0 | |||
c13141b8bf | |||
7a7ff735e3 | |||
3b934bb910 | |||
aa275fb5ce | |||
deb553be7f | |||
3db9633ebd | |||
2f8a70d548 | |||
7c0d0900ac | |||
6809c97611 | |||
675643c68d | |||
06f4bf493d | |||
4786fb0948 | |||
fdb5672b7a | |||
107a7a21c0 | |||
dbebf8df4b | |||
f7b01aab13 | |||
2570f075d9 | |||
21cb8ea4a3 | |||
6c8a7f1382 | |||
e00eab7f49 | |||
bfabcfcb6b | |||
f06ba52ede | |||
fcae000a79 | |||
3e4c015982 | |||
d689be30e8 | |||
7b110a0b73 | |||
e3033b57a6 | |||
bd537554ea | |||
ebb3b91df9 | |||
a65ad1a4bc | |||
bdc01f52a0 | |||
a673a85d4a | |||
61008fe75c | |||
5dee6b7d19 | |||
f6c7a6bd32 | |||
d2eece9a39 | |||
c3a23b28ee | |||
9083927c6a | |||
3f7e91e6a4 | |||
a2a6f47afa | |||
23229ef9ef | |||
0d17d974cd | |||
17104c25a2 | |||
8b374d7f90 | |||
fa3234147a | |||
33ad6c1370 | |||
04290dfc68 | |||
03080b3ef2 | |||
3f2a712ba8 | |||
f215aa4810 | |||
18a02d7d60 | |||
3f4d750dc4 | |||
9f01aeed31 | |||
b45f0b9bf6 | |||
cf04ade603 | |||
92f6181616 | |||
9270a0504a | |||
1da37f6ce1 | |||
ef6d9b9a94 | |||
c265786251 | |||
c5c806b58e | |||
e657dcfd5f | |||
2ed9b2bffd | |||
55ad951bce | |||
ef815bf5fc | |||
6082a0af3e | |||
be30fb7937 | |||
f4e7d63e65 | |||
14688f240f | |||
dce09837b9 | |||
3b9a404138 | |||
a6f55b59cf | |||
c188cbbcb4 | |||
4245521660 | |||
05e5baaa9f | |||
54b92e9599 | |||
aa68ffecec | |||
78991c81ab | |||
348ff13857 | |||
52817fb668 | |||
2c59ff1cc6 | |||
6bdf0838ce | |||
31a63c5d50 | |||
237aaadd65 | |||
34ddcef1dc | |||
f6ce2656db | |||
b647026dff | |||
568c0c47f0 | |||
2629de28f2 | |||
10d2c7c328 | |||
af7ac98bd6 | |||
6f78f1d4b2 | |||
9f95fd3309 | |||
74c309cefd | |||
b6d63c84ae | |||
bc2f1fb79d | |||
29e113a48a | |||
3caf1896d6 | |||
d5d5f23756 | |||
46641ef3b6 | |||
8ed459512f | |||
25768f0109 | |||
a56f67e073 | |||
8164f9821d | |||
b2a69f505c | |||
e307bd7ba9 | |||
b2bd829d39 | |||
f9b8617fa3 | |||
6c6e4ecfbc | |||
8bcf03c652 | |||
1ea449aa3a | |||
a99802b7d1 | |||
b212ec8dab | |||
3e16feb1e2 | |||
e50cbecf80 | |||
127b85bcaa | |||
89dde6cd9d | |||
5a52949761 | |||
a78162e9e4 | |||
931e6162ac | |||
1bb876f2df | |||
18f70e6ee4 | |||
82ca85dc65 | |||
f9cc9e9eb3 | |||
18fee2ad9a | |||
4124760706 | |||
3fe4f8c362 | |||
5a863b45f4 | |||
3ad30d48b5 | |||
3255a43568 | |||
73d757e3f4 | |||
deb28dd873 | |||
7f394feab5 | |||
8cbea70e07 | |||
f222f5b238 | |||
3f1de576e4 | |||
f48ca96a7e | |||
9421a21037 | |||
5c06cd090c | |||
fc982feeb9 | |||
31de651053 | |||
f4d62d3193 | |||
acbdeb62e8 | |||
d58e9e6e12 | |||
6497f29ed7 | |||
1705b42546 | |||
5505cc09ed | |||
12e1ab0f80 | |||
9c5ceb70cc | |||
bf0b1af64f | |||
9c959fba4d | |||
5588bfc35e | |||
2f4acf46c6 | |||
c7437d7590 | |||
4f819dbd9a | |||
3f5fee2dc6 | |||
c7f16b5d5a | |||
8d1268c0a9 | |||
c921b0aa5d | |||
589f97130c | |||
443aaadcce | |||
ff1938054a | |||
d79c297880 | |||
65631e0522 | |||
a879e412a1 | |||
4785ac14d7 | |||
50bc1ef757 | |||
7bacb25725 | |||
ad8418720f | |||
b59dae6fb8 | |||
4951314837 | |||
8188873216 | |||
5d392b76c7 | |||
c6a34b8efd | |||
95e67ba2c2 | |||
439b1afb85 | |||
745e9fb0fb | |||
769f7c751b | |||
a8c2deb014 | |||
624f6258ee | |||
43c977ab62 | |||
6c92ca2a16 | |||
0f015d75d2 | |||
217c3a2e87 | |||
ff6120cb93 | |||
53aaf3b4a9 | |||
d5b5c18cf9 | |||
cacdb3228d | |||
d0949b64c6 | |||
d49984d47d | |||
9f3af59250 | |||
57afd3d979 | |||
f7430a2ce1 | |||
7389f0507e | |||
ee889e9975 | |||
d8b9db8d3e | |||
9b498feac7 | |||
69982c62c8 | |||
b405e19f56 | |||
828235b4c1 | |||
430a0a971f | |||
5be22a99a8 | |||
5d02b18db4 | |||
97b68bdd66 | |||
5583fa2054 | |||
00a410ad1a | |||
6ca30386b8 | |||
03b17a2ca9 | |||
9957a867cd | |||
f3ba41a991 | |||
4befa1bc1b | |||
9e3ebc88c4 | |||
6e00cfb464 | |||
c358c18018 | |||
adf2a590fc | |||
edb8bac5bc | |||
47d7ac06b7 | |||
d05270d2ec | |||
04a19685ed | |||
62555771d0 | |||
9dc93cbab0 | |||
7f5fb871de | |||
03037170e1 | |||
002e0854ab | |||
2bc70f62ce | |||
8bf0e67b79 | |||
b310be1fcf | |||
a54353b51c | |||
04c2ba01bc | |||
296bcab425 | |||
060b321182 | |||
05a0a4b046 | |||
8906d3e77c | |||
e822642cb0 | |||
a38a4f0343 | |||
e8a22660e4 | |||
92196c602b | |||
76222ac8d0 | |||
a184c23603 | |||
1b778509c9 | |||
c4250872ca | |||
17dd72241b | |||
ce2984f09a | |||
846d766499 | |||
bbc71142d7 | |||
74804bc586 | |||
1d08a54f44 | |||
682544165f | |||
3f0ec5c0ca | |||
0e2872324f | |||
2fb575838d | |||
ab8f8d532a | |||
d93f112083 | |||
9384e87083 | |||
34eff4cc1f | |||
8296713ba4 | |||
d014ccfb8e | |||
190039b6f8 | |||
edf7982567 | |||
1509a6b681 | |||
11e6c2829b | |||
38f93a7ba9 | |||
6b5108ef92 | |||
828a306069 | |||
4c527dde65 | |||
f5a5ebe16b | |||
32799bc259 | |||
91d75e8925 | |||
3e40041219 | |||
7d5ee0d692 | |||
91cbe1f29b | |||
f419c12427 | |||
fee3c2b8f9 | |||
b016102d34 | |||
c20e1ab1e2 | |||
dc767b65df | |||
63f19974cd | |||
6e9ba0ea7f | |||
3b99f37aa1 | |||
e8f5c10488 | |||
cb55009c8b | |||
b64e70e7df | |||
8d79f8387b | |||
afadb3f6df | |||
844412c302 | |||
299cb9130b | |||
0b42e5573b | |||
a369b15ef2 | |||
e34f8c4634 | |||
d7f2c738c8 | |||
d06c04277f | |||
aa2fef0d36 | |||
b766f65c26 | |||
6f3a759ba5 | |||
338124e3fb | |||
31bdb793cf | |||
9cbd475701 | |||
481448fa90 | |||
95c65de97c | |||
ef79a2b484 | |||
20cfece1ab | |||
c433b7029f | |||
f5cf2876dd | |||
480aa521e5 | |||
d57557dc55 | |||
803d91c077 | |||
62ee48dcbf | |||
1e57587fe9 | |||
61c0b3e286 | |||
383a04f4c2 | |||
eea272482b | |||
94ad13c846 | |||
412a4a04de | |||
e0e8fa6e2a | |||
a1e29b0b75 | |||
984b0cbf31 | |||
3118c6c23f | |||
3a08eec1f9 | |||
ecfd11adb4 | |||
95dc670eb4 | |||
7a3d05ebf3 | |||
62f54cbbee | |||
4d7f7ffa37 | |||
cb876268b5 | |||
094f2fbab8 | |||
2d77c4dc49 | |||
f535916fae | |||
673993fa2b | |||
6f3803ce8c | |||
a1f6039d82 | |||
0183608a59 | |||
d0e2c5c67a | |||
5b1afcdb5a | |||
cfcfeb7b99 | |||
053e7a6aa6 | |||
62188a37c6 | |||
0b659961ba | |||
37aa2dc19f | |||
ba94479efd | |||
4a3902432a | |||
fc19f8f183 | |||
8c9320725b | |||
0eaa58e0ca | |||
2add87b829 | |||
ba3a9bee4c | |||
5260a60ad2 | |||
eb5d11c01b | |||
f96eec6dea | |||
e858f903a3 | |||
4037f952ec | |||
6cb3f588c7 | |||
8b0929b4bc | |||
fc339fc3e0 | |||
2c868a9557 | |||
8ba6dbb9a0 | |||
ff18ae2562 | |||
57781d1001 | |||
419c3fc772 | |||
2ad399db05 | |||
eb9b958309 | |||
ce332713c4 | |||
e18b9f0321 | |||
b459cf2347 | |||
933e98e4f2 | |||
3f3bf299a6 | |||
b08a4a86c1 | |||
3f0e55de56 | |||
235d2740c7 | |||
00020139c5 | |||
7aa307bd24 | |||
1c434dc6f4 | |||
8cc8b022ee | |||
05e197ffff | |||
d718d9c8ee | |||
f752c98d81 | |||
7c3d1d3402 | |||
764bbd9897 | |||
67b9c63528 | |||
b87e122ac4 | |||
dcaff38cb9 | |||
b68c814c50 | |||
9076ce7d17 | |||
c9ccb9cc71 | |||
0269a66940 | |||
e481671814 | |||
53b2a29b44 | |||
cb49be7815 | |||
68d4c2c0d8 | |||
de0113ae6a | |||
7242bc862e | |||
bc0d4ac7cb | |||
b346617dc1 | |||
b8ed790858 | |||
48cefc6767 | |||
079a41136e | |||
e01fbd497c | |||
9edf3143e1 | |||
00065f2b08 | |||
0869df5588 | |||
54c89c0d63 | |||
1c52f6834a | |||
c3bc2bedc0 | |||
7b27b7fed0 | |||
3a996c132d | |||
65b9011bc1 | |||
b9fdbdf7b5 | |||
436f9a7468 | |||
f8708d01bf | |||
7fd18ba639 | |||
55f638ac78 | |||
31f862c526 | |||
505fca93c3 | |||
849dbddc5a | |||
d24fbe8426 | |||
f841b5962b | |||
f26c19052d | |||
72af5ce582 | |||
aea3c68c98 | |||
8368360aec | |||
a5029cc4ca | |||
9995168f9a | |||
02eacb8e95 | |||
2a4459b98b | |||
d48b7e0101 | |||
495033b977 | |||
9c164408d3 | |||
9f2327ee57 | |||
68f2a5ddc7 | |||
b1374b6a08 | |||
19119e99f7 | |||
d603a6714d | |||
c8724d40d2 | |||
9ff937591b | |||
3c92cce9f4 | |||
fd78ea5c4a | |||
c3c49e9172 | |||
a43a1be0b4 | |||
98d1f79ca4 | |||
c3fcc72969 | |||
efd285a6c4 | |||
3a0b2e3b95 | |||
34ba7a8e6c | |||
b733b98408 | |||
b97d9896a4 | |||
52ebaece73 | |||
690ecb8168 | |||
830ccb6660 | |||
4fa625dea6 | |||
ce8a1be8d9 | |||
1ea18adce8 | |||
35d15b8977 | |||
48ad0202bf | |||
2220968a01 | |||
1611476288 | |||
0bdd400fe7 | |||
8cf34fce98 | |||
d79977977d | |||
de70732cd4 | |||
32d9d13dc7 | |||
7125bd8faa | |||
7196d6ede3 | |||
54ef08c039 | |||
c2079276eb | |||
b6bf712195 | |||
27a02082a3 | |||
39b2e07dc8 | |||
12a37f71be | |||
9f3058caad | |||
4181ea8620 | |||
cfc604b53d | |||
420e816bed | |||
fb6312a303 | |||
3c91360d72 | |||
983f20642c | |||
12ade02f2d | |||
ec745693dc | |||
9cac7504c9 | |||
75d09d138a | |||
07312e240c | |||
9c4414f995 | |||
8e7fe8bb66 | |||
0ba36763f5 | |||
3fce78c7cd | |||
a83a92cdab | |||
23ff7af0b7 | |||
9cc2e7237b | |||
63b82c438d | |||
ba5e393e99 | |||
690d77e985 | |||
bcc8f60677 | |||
6f93b2bcbe | |||
70dc9d7e14 | |||
01d87591e4 | |||
ff1b8588e0 | |||
54fb49ed95 | |||
fbd1c3f8b0 | |||
e823b6ea95 | |||
b16ef12ac0 | |||
f9e732b5ce | |||
ae2e25f4c2 | |||
7b405e9af7 | |||
e09e642a83 | |||
76c0636125 | |||
c7a0298546 | |||
b4fb657efd | |||
8c3b936c60 | |||
47fc32ba47 | |||
e5904443d9 | |||
4ee6cc3022 | |||
ceb4aa9e25 | |||
a0dff9148a | |||
c94189668f | |||
0122addd00 | |||
f52faf63f7 | |||
b9fb88f537 | |||
54185df46e | |||
16352579f3 | |||
c5eabcf469 | |||
b5b53b3849 | |||
ea513002c5 | |||
9776bb8a03 | |||
969464f8ad | |||
a9b6a0b81a | |||
2758c6da14 | |||
097bcb3b5b | |||
18335194bc | |||
6c13bdde25 | |||
a981dab536 | |||
6632c21d62 | |||
a5b5ae899c | |||
ac6108a87d | |||
2f75445520 | |||
43057a2fcb | |||
9446563e5b | |||
167ad203cb | |||
558738ade8 | |||
0fb7d4babb | |||
91c7635d0e | |||
2a81595c3e | |||
9e4d886a6c | |||
b644665952 | |||
9492e4131b | |||
2abda0954b | |||
dbf6ca2b4c | |||
bca6a33325 | |||
c8f86652a3 | |||
076bd0b440 | |||
a443a798e3 | |||
23d79b8b05 | |||
9ccdb31003 | |||
0adb864219 | |||
d39954c935 | |||
89c03870c8 | |||
1d44018128 | |||
d835b0c80f | |||
bc862e526d | |||
a4df6e403c | |||
290a9d184d | |||
00abdcd0a1 | |||
73a2081ae7 | |||
c6167ef184 | |||
4bcbc588fc | |||
5f4fe6d868 | |||
7131dec3af | |||
0ddde6fa9f | |||
5d54acba30 | |||
c1b2e1d0ca | |||
9fc4cd8958 | |||
742c432fd1 | |||
3ac5eec301 | |||
060631e952 | |||
57165f2fb5 | |||
5940fd4bbd | |||
13180c5a17 | |||
6ea8dd5999 | |||
2795ac6e6b | |||
83e6079ff7 | |||
d043ebcdd3 | |||
e11c40eee4 | |||
5d55ca19be | |||
3f91dfbca3 | |||
bf3830b6f0 | |||
278f8eb13e | |||
658a671b79 | |||
bf836a2126 | |||
35a136bcee | |||
aaf1490ff5 | |||
a62ed10ab3 | |||
e79d756d06 | |||
904b37032c | |||
8a37c30f35 | |||
c4edc13413 | |||
9ddbab59bb | |||
1eb87c5c59 | |||
fb1439dfb9 | |||
d393c329c3 | |||
bed0fe2218 | |||
02c2e16253 | |||
59a67720b4 | |||
93e1206d60 | |||
2249d745d9 | |||
f9ed74a9b2 | |||
65ec2db4e8 | |||
001e33f310 | |||
09aca2528a | |||
beecc5072e | |||
797bd98269 | |||
4a3d32dc1f | |||
048be29fcd | |||
4ce584c5a6 | |||
3c1d23bc62 | |||
95307a3d78 | |||
a85d91b4bd | |||
a616087cde | |||
198d6320dd | |||
1596aa7a34 | |||
8e8d39d3cb | |||
42958ddd41 | |||
0476da503e | |||
943fe971f1 | |||
9d84969bf6 | |||
3745bb7279 | |||
55fe3ba52f | |||
de2dd6e070 | |||
ffb347a2bb | |||
19862725f7 | |||
f502f84423 | |||
e788fb7239 | |||
72f5961dd8 | |||
9f6b803a10 | |||
0da2059f79 | |||
e904d26e08 | |||
1ff0a31d3f | |||
e7f08946d1 | |||
ea9c2cebfd | |||
02a03cec33 | |||
31fbd52462 | |||
a88750d2b3 | |||
da91565354 | |||
44f5c208b6 | |||
83e26fdc9b | |||
4a329db792 | |||
1f8022d4ad | |||
63da329468 | |||
acadea6afa | |||
bd61dd9ffc | |||
5b9ae54441 | |||
41dd6e580d | |||
22d2de9fc7 | |||
6064a7ab2a | |||
8f5ca303b5 | |||
dc8f932009 | |||
4922237847 | |||
2424618163 | |||
b96f7e2ef2 | |||
cde38fbe1a | |||
56a1603e1f | |||
f92973794e | |||
49bbca0ce3 | |||
6686d9235c | |||
7c72b2dca7 | |||
4c061feddf | |||
02d2990576 | |||
94f7ba8bdf | |||
7d7c9825e9 | |||
dee542df42 | |||
f2b4c29f83 | |||
28652c5d21 | |||
b104bfeb93 | |||
8af4ba8980 | |||
87f8fb0750 | |||
eaffabf388 | |||
ac8853dfd3 | |||
d2be74a4f2 | |||
17a99cfa81 | |||
fd677c45aa | |||
769735c207 | |||
b114f258d6 | |||
c38abf35da | |||
1fedaf21ec | |||
0b74db64eb | |||
f2222ba3c6 | |||
3cb8a96041 | |||
4f538e7fd2 | |||
e02f9a9931 | |||
aecf4af7f2 | |||
618cbf1e66 | |||
c81bbf9801 | |||
f02b286ad4 | |||
0372b817d1 | |||
a3363b0605 | |||
51e625debf | |||
1977d87d55 | |||
9cbefacf52 |
3
.gitignore
vendored
@ -1 +1,4 @@
|
||||
.idea
|
||||
.DS_Store
|
||||
*.swp
|
||||
*.swo
|
||||
|
16
.go_style
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"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"
|
||||
]
|
||||
}
|
13
LICENSE
Normal file
@ -0,0 +1,13 @@
|
||||
Copyright 2014 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.
|
42
README.md
@ -1,43 +1,37 @@
|
||||
## beego
|
||||
## Beego
|
||||
|
||||
[](https://drone.io/github.com/astaxie/beego/latest)
|
||||
[](https://godoc.org/github.com/astaxie/beego)
|
||||
|
||||
beego is a Go Framework which is inspired from tornado and sinatra.
|
||||
beego is an open-source, high-performance, modularity, full-stack web framework.
|
||||
|
||||
It is a simply & powerful web framework.
|
||||
More info [beego.me](http://beego.me)
|
||||
|
||||
more info [beego.me](http://beego.me)
|
||||
## Installation
|
||||
|
||||
go get github.com/astaxie/beego
|
||||
|
||||
## Features
|
||||
|
||||
* RESTFul support
|
||||
* RESTful support
|
||||
* MVC architecture
|
||||
* Session support (store in memory, file, Redis or MySQL)
|
||||
* Cache support (store in memory, Redis or Memcache)
|
||||
* Global Config
|
||||
* Intelligent routing
|
||||
* Thread-safe map
|
||||
* Friendly displaying of errors
|
||||
* Useful template functions
|
||||
|
||||
* Modularity
|
||||
* Auto API documents
|
||||
* Annotation router
|
||||
* Namespace
|
||||
* Powerful develop tools
|
||||
* Full stack for Web & API
|
||||
|
||||
## Documentation
|
||||
|
||||
[English](https://github.com/astaxie/beego/tree/master/docs/en)
|
||||
* [English](http://beego.me/docs/intro/)
|
||||
* [中文文档](http://beego.me/docs/intro/)
|
||||
|
||||
[API](http://gowalker.org/github.com/astaxie/beego)
|
||||
|
||||
[中文文档](https://github.com/astaxie/beego/tree/master/docs/zh)
|
||||
## Community
|
||||
|
||||
* [http://beego.me/community](http://beego.me/community)
|
||||
|
||||
## LICENSE
|
||||
|
||||
beego is licensed under the Apache Licence, Version 2.0
|
||||
(http://www.apache.org/licenses/LICENSE-2.0.html).
|
||||
|
||||
|
||||
## Use case
|
||||
|
||||
- Displaying API documentation: [gowalker](https://github.com/Unknwon/gowalker)
|
||||
- seocms: [seocms](https://github.com/chinakr/seocms)
|
||||
- CMS: [toropress](https://github.com/insionng/toropress)
|
||||
|
465
admin.go
Normal file
@ -0,0 +1,465 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/toolbox"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
// BeeAdminApp is the default adminApp used by admin module.
|
||||
var beeAdminApp *adminApp
|
||||
|
||||
// FilterMonitorFunc is default monitor filter when admin module is enable.
|
||||
// if this func returns, admin module records qbs for this request by condition of this function logic.
|
||||
// usage:
|
||||
// func MyFilterMonitor(method, requestPath string, t time.Duration) 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) bool
|
||||
|
||||
func init() {
|
||||
beeAdminApp = &adminApp{
|
||||
routers: make(map[string]http.HandlerFunc),
|
||||
}
|
||||
beeAdminApp.Route("/", adminIndex)
|
||||
beeAdminApp.Route("/qps", qpsIndex)
|
||||
beeAdminApp.Route("/prof", profIndex)
|
||||
beeAdminApp.Route("/healthcheck", healthcheck)
|
||||
beeAdminApp.Route("/task", taskStatus)
|
||||
beeAdminApp.Route("/listconf", listConf)
|
||||
FilterMonitorFunc = func(string, string, time.Duration) bool { return true }
|
||||
}
|
||||
|
||||
// AdminIndex is the default http.Handler for admin module.
|
||||
// it matches url pattern "/".
|
||||
func adminIndex(rw http.ResponseWriter, r *http.Request) {
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(indexTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
data := make(map[interface{}]interface{})
|
||||
tmpl.Execute(rw, data)
|
||||
}
|
||||
|
||||
// QpsIndex is the http.Handler for writing qbs statistics map result info in http.ResponseWriter.
|
||||
// it's registered with url pattern "/qbs" in admin module.
|
||||
func qpsIndex(rw http.ResponseWriter, r *http.Request) {
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(qpsTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
data := make(map[interface{}]interface{})
|
||||
data["Content"] = toolbox.StatisticsMap.GetMap()
|
||||
|
||||
tmpl.Execute(rw, data)
|
||||
|
||||
}
|
||||
|
||||
// ListConf is the http.Handler of displaying all beego configuration values as key/value pair.
|
||||
// it's registered with url pattern "/listconf" in admin module.
|
||||
func listConf(rw http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
command := r.Form.Get("command")
|
||||
if command != "" {
|
||||
data := make(map[interface{}]interface{})
|
||||
switch command {
|
||||
case "conf":
|
||||
m := make(map[string]interface{})
|
||||
|
||||
m["AppName"] = AppName
|
||||
m["AppPath"] = AppPath
|
||||
m["AppConfigPath"] = AppConfigPath
|
||||
m["StaticDir"] = StaticDir
|
||||
m["StaticExtensionsToGzip"] = StaticExtensionsToGzip
|
||||
m["HttpAddr"] = HttpAddr
|
||||
m["HttpPort"] = HttpPort
|
||||
m["HttpTLS"] = EnableHttpTLS
|
||||
m["HttpCertFile"] = HttpCertFile
|
||||
m["HttpKeyFile"] = HttpKeyFile
|
||||
m["RecoverPanic"] = RecoverPanic
|
||||
m["AutoRender"] = AutoRender
|
||||
m["ViewsPath"] = ViewsPath
|
||||
m["RunMode"] = RunMode
|
||||
m["SessionOn"] = SessionOn
|
||||
m["SessionProvider"] = SessionProvider
|
||||
m["SessionName"] = SessionName
|
||||
m["SessionGCMaxLifetime"] = SessionGCMaxLifetime
|
||||
m["SessionSavePath"] = SessionSavePath
|
||||
m["SessionHashFunc"] = SessionHashFunc
|
||||
m["SessionHashKey"] = SessionHashKey
|
||||
m["SessionCookieLifeTime"] = SessionCookieLifeTime
|
||||
m["UseFcgi"] = UseFcgi
|
||||
m["MaxMemory"] = MaxMemory
|
||||
m["EnableGzip"] = EnableGzip
|
||||
m["DirectoryIndex"] = DirectoryIndex
|
||||
m["HttpServerTimeOut"] = HttpServerTimeOut
|
||||
m["ErrorsShow"] = ErrorsShow
|
||||
m["XSRFKEY"] = XSRFKEY
|
||||
m["EnableXSRF"] = EnableXSRF
|
||||
m["XSRFExpire"] = XSRFExpire
|
||||
m["CopyRequestBody"] = CopyRequestBody
|
||||
m["TemplateLeft"] = TemplateLeft
|
||||
m["TemplateRight"] = TemplateRight
|
||||
m["BeegoServerName"] = BeegoServerName
|
||||
m["EnableAdmin"] = EnableAdmin
|
||||
m["AdminHttpAddr"] = AdminHttpAddr
|
||||
m["AdminHttpPort"] = AdminHttpPort
|
||||
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(configTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
|
||||
data["Content"] = m
|
||||
|
||||
tmpl.Execute(rw, data)
|
||||
|
||||
case "router":
|
||||
content := make(map[string]interface{})
|
||||
|
||||
var fields = []string{
|
||||
fmt.Sprintf("Router Pattern"),
|
||||
fmt.Sprintf("Methods"),
|
||||
fmt.Sprintf("Controller"),
|
||||
}
|
||||
content["Fields"] = fields
|
||||
|
||||
methods := []string{}
|
||||
methodsData := make(map[string]interface{})
|
||||
for method, t := range BeeApp.Handlers.routers {
|
||||
|
||||
resultList := new([][]string)
|
||||
|
||||
printTree(resultList, t)
|
||||
|
||||
methods = append(methods, method)
|
||||
methodsData[method] = resultList
|
||||
}
|
||||
|
||||
content["Data"] = methodsData
|
||||
content["Methods"] = methods
|
||||
data["Content"] = content
|
||||
data["Title"] = "Routers"
|
||||
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(routerAndFilterTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
tmpl.Execute(rw, data)
|
||||
case "filter":
|
||||
content := make(map[string]interface{})
|
||||
|
||||
var fields = []string{
|
||||
fmt.Sprintf("Router Pattern"),
|
||||
fmt.Sprintf("Filter Function"),
|
||||
}
|
||||
content["Fields"] = fields
|
||||
|
||||
filterTypes := []string{}
|
||||
filterTypeData := make(map[string]interface{})
|
||||
|
||||
if BeeApp.Handlers.enableFilter {
|
||||
var filterType string
|
||||
|
||||
if bf, ok := BeeApp.Handlers.filters[BeforeRouter]; ok {
|
||||
filterType = "Before Router"
|
||||
filterTypes = append(filterTypes, filterType)
|
||||
resultList := new([][]string)
|
||||
for _, f := range bf {
|
||||
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", f.pattern),
|
||||
fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
filterTypeData[filterType] = resultList
|
||||
}
|
||||
|
||||
if bf, ok := BeeApp.Handlers.filters[BeforeExec]; ok {
|
||||
filterType = "Before Exec"
|
||||
filterTypes = append(filterTypes, filterType)
|
||||
resultList := new([][]string)
|
||||
for _, f := range bf {
|
||||
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", f.pattern),
|
||||
fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
filterTypeData[filterType] = resultList
|
||||
}
|
||||
|
||||
if bf, ok := BeeApp.Handlers.filters[AfterExec]; ok {
|
||||
filterType = "After Exec"
|
||||
filterTypes = append(filterTypes, filterType)
|
||||
resultList := new([][]string)
|
||||
for _, f := range bf {
|
||||
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", f.pattern),
|
||||
fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
filterTypeData[filterType] = resultList
|
||||
}
|
||||
|
||||
if bf, ok := BeeApp.Handlers.filters[FinishRouter]; ok {
|
||||
filterType = "Finish Router"
|
||||
filterTypes = append(filterTypes, filterType)
|
||||
resultList := new([][]string)
|
||||
for _, f := range bf {
|
||||
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", f.pattern),
|
||||
fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
filterTypeData[filterType] = resultList
|
||||
}
|
||||
}
|
||||
|
||||
content["Data"] = filterTypeData
|
||||
content["Methods"] = filterTypes
|
||||
|
||||
data["Content"] = content
|
||||
data["Title"] = "Filters"
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(routerAndFilterTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
tmpl.Execute(rw, data)
|
||||
|
||||
default:
|
||||
rw.Write([]byte("command not support"))
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
func printTree(resultList *[][]string, t *Tree) {
|
||||
for _, tr := range t.fixrouters {
|
||||
printTree(resultList, tr)
|
||||
}
|
||||
if t.wildcard != nil {
|
||||
printTree(resultList, t.wildcard)
|
||||
}
|
||||
for _, l := range t.leaves {
|
||||
if v, ok := l.runObject.(*controllerInfo); ok {
|
||||
if v.routerType == routerTypeBeego {
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", v.pattern),
|
||||
fmt.Sprintf("%s", v.methods),
|
||||
fmt.Sprintf("%s", v.controllerType),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
} else if v.routerType == routerTypeRESTFul {
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", v.pattern),
|
||||
fmt.Sprintf("%s", v.methods),
|
||||
fmt.Sprintf(""),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
} else if v.routerType == routerTypeHandler {
|
||||
var result = []string{
|
||||
fmt.Sprintf("%s", v.pattern),
|
||||
fmt.Sprintf(""),
|
||||
fmt.Sprintf(""),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ProfIndex is a http.Handler for showing profile command.
|
||||
// it's in url pattern "/prof" in admin module.
|
||||
func profIndex(rw http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
command := r.Form.Get("command")
|
||||
format := r.Form.Get("format")
|
||||
data := make(map[string]interface{})
|
||||
|
||||
var result bytes.Buffer
|
||||
if command != "" {
|
||||
toolbox.ProcessInput(command, &result)
|
||||
data["Content"] = result.String()
|
||||
|
||||
if format == "json" && command == "gc summary" {
|
||||
dataJson, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
rw.Write(dataJson)
|
||||
return
|
||||
}
|
||||
|
||||
data["Title"] = command
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(profillingTpl))
|
||||
if command == "gc summary" {
|
||||
tmpl = template.Must(tmpl.Parse(gcAjaxTpl))
|
||||
} else {
|
||||
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
}
|
||||
tmpl.Execute(rw, data)
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
// Healthcheck is a http.Handler calling health checking and showing the result.
|
||||
// it's in "/healthcheck" pattern in admin module.
|
||||
func healthcheck(rw http.ResponseWriter, req *http.Request) {
|
||||
data := make(map[interface{}]interface{})
|
||||
|
||||
var result = []string{}
|
||||
fields := []string{
|
||||
fmt.Sprintf("Name"),
|
||||
fmt.Sprintf("Message"),
|
||||
fmt.Sprintf("Status"),
|
||||
}
|
||||
resultList := new([][]string)
|
||||
|
||||
content := make(map[string]interface{})
|
||||
|
||||
for name, h := range toolbox.AdminCheckList {
|
||||
if err := h.Check(); err != nil {
|
||||
result = []string{
|
||||
fmt.Sprintf("error"),
|
||||
fmt.Sprintf("%s", name),
|
||||
fmt.Sprintf("%s", err.Error()),
|
||||
}
|
||||
|
||||
} else {
|
||||
result = []string{
|
||||
fmt.Sprintf("success"),
|
||||
fmt.Sprintf("%s", name),
|
||||
fmt.Sprintf("OK"),
|
||||
}
|
||||
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
|
||||
content["Fields"] = fields
|
||||
content["Data"] = resultList
|
||||
data["Content"] = content
|
||||
data["Title"] = "Health Check"
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(healthCheckTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
tmpl.Execute(rw, data)
|
||||
|
||||
}
|
||||
|
||||
// TaskStatus is a http.Handler with running task status (task name, status and the last execution).
|
||||
// it's in "/task" pattern in admin module.
|
||||
func taskStatus(rw http.ResponseWriter, req *http.Request) {
|
||||
data := make(map[interface{}]interface{})
|
||||
|
||||
// Run Task
|
||||
req.ParseForm()
|
||||
taskname := req.Form.Get("taskname")
|
||||
if taskname != "" {
|
||||
|
||||
if t, ok := toolbox.AdminTaskList[taskname]; ok {
|
||||
err := t.Run()
|
||||
if err != nil {
|
||||
data["Message"] = []string{"error", fmt.Sprintf("%s", err)}
|
||||
}
|
||||
data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is %s", taskname, t.GetStatus())}
|
||||
} else {
|
||||
data["Message"] = []string{"warning", fmt.Sprintf("there's no task which named: %s", taskname)}
|
||||
}
|
||||
}
|
||||
|
||||
// List Tasks
|
||||
content := make(map[string]interface{})
|
||||
resultList := new([][]string)
|
||||
var result = []string{}
|
||||
var fields = []string{
|
||||
fmt.Sprintf("Task Name"),
|
||||
fmt.Sprintf("Task Spec"),
|
||||
fmt.Sprintf("Task Function"),
|
||||
fmt.Sprintf(""),
|
||||
}
|
||||
for tname, tk := range toolbox.AdminTaskList {
|
||||
result = []string{
|
||||
fmt.Sprintf("%s", tname),
|
||||
fmt.Sprintf("%s", tk.GetStatus()),
|
||||
fmt.Sprintf("%s", tk.GetPrev().String()),
|
||||
}
|
||||
*resultList = append(*resultList, result)
|
||||
}
|
||||
|
||||
content["Fields"] = fields
|
||||
content["Data"] = resultList
|
||||
data["Content"] = content
|
||||
data["Title"] = "Tasks"
|
||||
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
|
||||
tmpl = template.Must(tmpl.Parse(tasksTpl))
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
tmpl.Execute(rw, data)
|
||||
}
|
||||
|
||||
// adminApp is an http.HandlerFunc map used as beeAdminApp.
|
||||
type adminApp struct {
|
||||
routers map[string]http.HandlerFunc
|
||||
}
|
||||
|
||||
// Route adds http.HandlerFunc to adminApp with url pattern.
|
||||
func (admin *adminApp) Route(pattern string, f http.HandlerFunc) {
|
||||
admin.routers[pattern] = f
|
||||
}
|
||||
|
||||
// Run adminApp http server.
|
||||
// Its addr is defined in configuration file as adminhttpaddr and adminhttpport.
|
||||
func (admin *adminApp) Run() {
|
||||
if len(toolbox.AdminTaskList) > 0 {
|
||||
toolbox.StartTask()
|
||||
}
|
||||
addr := AdminHttpAddr
|
||||
|
||||
if AdminHttpPort != 0 {
|
||||
addr = fmt.Sprintf("%s:%d", AdminHttpAddr, AdminHttpPort)
|
||||
}
|
||||
for p, f := range admin.routers {
|
||||
http.Handle(p, f)
|
||||
}
|
||||
err := http.ListenAndServe(addr, nil)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("Admin ListenAndServe: ", err)
|
||||
}
|
||||
}
|
355
adminui.go
Normal file
104
app.go
Normal file
@ -0,0 +1,104 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/fcgi"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
)
|
||||
|
||||
// FilterFunc defines filter function type.
|
||||
type FilterFunc func(*context.Context)
|
||||
|
||||
// App defines beego application with a new PatternServeMux.
|
||||
type App struct {
|
||||
Handlers *ControllerRegistor
|
||||
Server *http.Server
|
||||
}
|
||||
|
||||
// NewApp returns a new beego application.
|
||||
func NewApp() *App {
|
||||
cr := NewControllerRegister()
|
||||
app := &App{Handlers: cr, Server: &http.Server{}}
|
||||
return app
|
||||
}
|
||||
|
||||
// Run beego application.
|
||||
func (app *App) Run() {
|
||||
addr := HttpAddr
|
||||
|
||||
if HttpPort != 0 {
|
||||
addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
|
||||
}
|
||||
|
||||
BeeLogger.Info("Running on %s", addr)
|
||||
|
||||
var (
|
||||
err error
|
||||
l net.Listener
|
||||
)
|
||||
endRunning := make(chan bool, 1)
|
||||
|
||||
if UseFcgi {
|
||||
if HttpPort == 0 {
|
||||
l, err = net.Listen("unix", addr)
|
||||
} else {
|
||||
l, err = net.Listen("tcp", addr)
|
||||
}
|
||||
if err != nil {
|
||||
BeeLogger.Critical("Listen: ", err)
|
||||
}
|
||||
err = fcgi.Serve(l, app.Handlers)
|
||||
} else {
|
||||
app.Server.Addr = addr
|
||||
app.Server.Handler = app.Handlers
|
||||
app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
|
||||
if EnableHttpTLS {
|
||||
go func() {
|
||||
time.Sleep(20 * time.Microsecond)
|
||||
if HttpsPort != 0 {
|
||||
app.Server.Addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort)
|
||||
}
|
||||
err := app.Server.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServeTLS: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if EnableHttpListen {
|
||||
go func() {
|
||||
app.Server.Addr = addr
|
||||
err := app.Server.ListenAndServe()
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
<-endRunning
|
||||
}
|
570
beego.go
@ -1,304 +1,428 @@
|
||||
// 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.
|
||||
|
||||
// beego is an open-source, high-performance, modularity, full-stack web framework
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// import "github.com/astaxie/beego"
|
||||
//
|
||||
// func main() {
|
||||
// beego.Run()
|
||||
// }
|
||||
//
|
||||
// more infomation: http://beego.me
|
||||
package beego
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/astaxie/beego/session"
|
||||
"html/template"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/fcgi"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"time"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/session"
|
||||
)
|
||||
|
||||
const VERSION = "0.9.0"
|
||||
// beego web framework version.
|
||||
const VERSION = "1.4.1"
|
||||
|
||||
var (
|
||||
BeeApp *App
|
||||
AppName string
|
||||
AppPath string
|
||||
AppConfigPath string
|
||||
StaticDir map[string]string
|
||||
TemplateCache map[string]*template.Template
|
||||
HttpAddr string
|
||||
HttpPort int
|
||||
RecoverPanic bool
|
||||
AutoRender bool
|
||||
PprofOn bool
|
||||
ViewsPath string
|
||||
RunMode string //"dev" or "prod"
|
||||
AppConfig *Config
|
||||
//related to session
|
||||
GlobalSessions *session.Manager //GlobalSessions
|
||||
SessionOn bool // wheather auto start session,default is false
|
||||
SessionProvider string // default session provider memory mysql redis
|
||||
SessionName string // sessionName cookie's name
|
||||
SessionGCMaxLifetime int64 // session's gc maxlifetime
|
||||
SessionSavePath string // session savepath if use mysql/redis/file this set to the connectinfo
|
||||
UseFcgi bool
|
||||
MaxMemory int64
|
||||
EnableGzip bool // enable gzip
|
||||
DirectoryIndex bool //ebable DirectoryIndex default is false
|
||||
EnbaleHotUpdate bool //enable HotUpdate default is false
|
||||
HttpServerTimeOut int64 //set httpserver timeout
|
||||
ErrorsShow bool //set weather show errors
|
||||
XSRFKEY string //set XSRF
|
||||
EnableXSRF bool
|
||||
XSRFExpire int
|
||||
CopyRequestBody bool //When in raw application, You want to the reqeustbody
|
||||
)
|
||||
type hookfunc func() error //hook function to run
|
||||
var hooks []hookfunc //hook function slice to store the hookfunc
|
||||
|
||||
func init() {
|
||||
os.Chdir(path.Dir(os.Args[0]))
|
||||
BeeApp = NewApp()
|
||||
AppPath, _ = os.Getwd()
|
||||
StaticDir = make(map[string]string)
|
||||
TemplateCache = make(map[string]*template.Template)
|
||||
HttpAddr = ""
|
||||
HttpPort = 8080
|
||||
AppName = "beego"
|
||||
RunMode = "dev" //default runmod
|
||||
AutoRender = true
|
||||
RecoverPanic = true
|
||||
PprofOn = false
|
||||
ViewsPath = "views"
|
||||
SessionOn = false
|
||||
SessionProvider = "memory"
|
||||
SessionName = "beegosessionID"
|
||||
SessionGCMaxLifetime = 3600
|
||||
SessionSavePath = ""
|
||||
UseFcgi = false
|
||||
MaxMemory = 1 << 26 //64MB
|
||||
EnableGzip = false
|
||||
StaticDir["/static"] = "static"
|
||||
AppConfigPath = path.Join(AppPath, "conf", "app.conf")
|
||||
HttpServerTimeOut = 0
|
||||
ErrorsShow = true
|
||||
XSRFKEY = "beegoxsrf"
|
||||
XSRFExpire = 60
|
||||
ParseConfig()
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
type groupRouter struct {
|
||||
pattern string
|
||||
controller ControllerInterface
|
||||
mappingMethods string
|
||||
}
|
||||
|
||||
type App struct {
|
||||
Handlers *ControllerRegistor
|
||||
// RouterGroups which will store routers
|
||||
type GroupRouters []groupRouter
|
||||
|
||||
// Get a new GroupRouters
|
||||
func NewGroupRouters() GroupRouters {
|
||||
return make(GroupRouters, 0)
|
||||
}
|
||||
|
||||
// New returns a new PatternServeMux.
|
||||
func NewApp() *App {
|
||||
cr := NewControllerRegistor()
|
||||
app := &App{Handlers: cr}
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) Run() {
|
||||
addr := fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
|
||||
var (
|
||||
err error
|
||||
l net.Listener
|
||||
)
|
||||
if UseFcgi {
|
||||
l, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
BeeLogger.Fatal("Listen: ", err)
|
||||
// Add Router in the GroupRouters
|
||||
// it is for plugin or module to register router
|
||||
func (gr *GroupRouters) AddRouter(pattern string, c ControllerInterface, mappingMethod ...string) {
|
||||
var newRG groupRouter
|
||||
if len(mappingMethod) > 0 {
|
||||
newRG = groupRouter{
|
||||
pattern,
|
||||
c,
|
||||
mappingMethod[0],
|
||||
}
|
||||
err = fcgi.Serve(l, app.Handlers)
|
||||
} else {
|
||||
if EnbaleHotUpdate {
|
||||
server := &http.Server{
|
||||
Handler: app.Handlers,
|
||||
ReadTimeout: time.Duration(HttpServerTimeOut) * time.Second,
|
||||
WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
|
||||
newRG = groupRouter{
|
||||
pattern,
|
||||
c,
|
||||
"",
|
||||
}
|
||||
laddr, err := net.ResolveTCPAddr("tcp", addr)
|
||||
if nil != err {
|
||||
BeeLogger.Fatal("ResolveTCPAddr:", err)
|
||||
}
|
||||
l, err = GetInitListner(laddr)
|
||||
theStoppable = newStoppable(l)
|
||||
err = server.Serve(theStoppable)
|
||||
theStoppable.wg.Wait()
|
||||
CloseSelf()
|
||||
*gr = append(*gr, newRG)
|
||||
}
|
||||
|
||||
func (gr *GroupRouters) AddAuto(c ControllerInterface) {
|
||||
newRG := groupRouter{
|
||||
"",
|
||||
c,
|
||||
"",
|
||||
}
|
||||
*gr = append(*gr, newRG)
|
||||
}
|
||||
|
||||
// AddGroupRouter with the prefix
|
||||
// it will register the router in BeeApp
|
||||
// the follow code is write in modules:
|
||||
// GR:=NewGroupRouters()
|
||||
// GR.AddRouter("/login",&UserController,"get:Login")
|
||||
// GR.AddRouter("/logout",&UserController,"get:Logout")
|
||||
// GR.AddRouter("/register",&UserController,"get:Reg")
|
||||
// the follow code is write in app:
|
||||
// import "github.com/beego/modules/auth"
|
||||
// AddRouterGroup("/admin", auth.GR)
|
||||
func AddGroupRouter(prefix string, groups GroupRouters) *App {
|
||||
for _, v := range groups {
|
||||
if v.pattern == "" {
|
||||
BeeApp.Handlers.AddAutoPrefix(prefix, v.controller)
|
||||
} else if v.mappingMethods != "" {
|
||||
BeeApp.Handlers.Add(prefix+v.pattern, v.controller, v.mappingMethods)
|
||||
} else {
|
||||
s := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: app.Handlers,
|
||||
ReadTimeout: time.Duration(HttpServerTimeOut) * time.Second,
|
||||
WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
|
||||
}
|
||||
err = s.ListenAndServe()
|
||||
BeeApp.Handlers.Add(prefix+v.pattern, v.controller)
|
||||
}
|
||||
|
||||
}
|
||||
if err != nil {
|
||||
BeeLogger.Fatal("ListenAndServe: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) Router(path string, c ControllerInterface, mappingMethods ...string) *App {
|
||||
app.Handlers.Add(path, c, mappingMethods...)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) AutoRouter(c ControllerInterface) *App {
|
||||
app.Handlers.AddAuto(c)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) Filter(filter http.HandlerFunc) *App {
|
||||
app.Handlers.Filter(filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) FilterParam(param string, filter http.HandlerFunc) *App {
|
||||
app.Handlers.FilterParam(param, filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) FilterPrefixPath(path string, filter http.HandlerFunc) *App {
|
||||
app.Handlers.FilterPrefixPath(path, filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) FilterAfter(filter http.HandlerFunc) *App {
|
||||
app.Handlers.FilterAfter(filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) FilterParamAfter(param string, filter http.HandlerFunc) *App {
|
||||
app.Handlers.FilterParamAfter(param, filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) FilterPrefixPathAfter(path string, filter http.HandlerFunc) *App {
|
||||
app.Handlers.FilterPrefixPathAfter(path, filter)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) SetViewsPath(path string) *App {
|
||||
ViewsPath = path
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) SetStaticPath(url string, path string) *App {
|
||||
StaticDir[url] = path
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) DelStaticPath(url string) *App {
|
||||
delete(StaticDir, url)
|
||||
return app
|
||||
}
|
||||
|
||||
func (app *App) ErrorLog(ctx *Context) {
|
||||
BeeLogger.Printf("[ERR] host: '%s', request: '%s %s', proto: '%s', ua: '%s', remote: '%s'\n", ctx.Request.Host, ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.Proto, ctx.Request.UserAgent(), ctx.Request.RemoteAddr)
|
||||
}
|
||||
|
||||
func (app *App) AccessLog(ctx *Context) {
|
||||
BeeLogger.Printf("[ACC] host: '%s', request: '%s %s', proto: '%s', ua: '%s', remote: '%s'\n", ctx.Request.Host, ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.Proto, ctx.Request.UserAgent(), ctx.Request.RemoteAddr)
|
||||
}
|
||||
|
||||
func RegisterController(path string, c ControllerInterface) *App {
|
||||
BeeApp.Router(path, c)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// Router adds a patterned controller handler to BeeApp.
|
||||
// it's an alias method of App.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 {
|
||||
BeeApp.Router(rootpath, c, mappingMethods...)
|
||||
BeeApp.Handlers.Add(rootpath, c, mappingMethods...)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// Router add list from
|
||||
// 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 {
|
||||
BeeApp.Handlers.Include(cList...)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
Router(rootpath, c)
|
||||
Router(path.Join(rootpath, ":objectId"), c)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// AutoRouter adds defined controller handler to BeeApp.
|
||||
// it's same to App.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 {
|
||||
BeeApp.AutoRouter(c)
|
||||
BeeApp.Handlers.AddAuto(c)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func RouterHandler(path string, c http.Handler) *App {
|
||||
BeeApp.Handlers.AddHandler(path, c)
|
||||
// AutoPrefix adds controller handler to BeeApp with prefix.
|
||||
// it's same to App.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 {
|
||||
BeeApp.Handlers.AddAutoPrefix(prefix, c)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// register router for Get method
|
||||
// usage:
|
||||
// beego.Get("/", func(ctx *context.Context){
|
||||
// ctx.Output.Body("hello world")
|
||||
// })
|
||||
func Get(rootpath string, f FilterFunc) *App {
|
||||
BeeApp.Handlers.Get(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Post(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Delete(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Put(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Head(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Options(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// 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 {
|
||||
BeeApp.Handlers.Patch(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// register router for all method
|
||||
// usage:
|
||||
// beego.Any("/api", func(ctx *context.Context){
|
||||
// ctx.Output.Body("hello world")
|
||||
// })
|
||||
func Any(rootpath string, f FilterFunc) *App {
|
||||
BeeApp.Handlers.Any(rootpath, f)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// register router for own Handler
|
||||
// usage:
|
||||
// beego.Handler("/api", func(ctx *context.Context){
|
||||
// ctx.Output.Body("hello world")
|
||||
// })
|
||||
func Handler(rootpath string, h http.Handler, options ...interface{}) *App {
|
||||
BeeApp.Handlers.Handler(rootpath, h, options...)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// ErrorHandler registers http.HandlerFunc to each http err code string.
|
||||
// usage:
|
||||
// beego.ErrorHandler("404",NotFound)
|
||||
// beego.ErrorHandler("500",InternalServerError)
|
||||
func Errorhandler(err string, h http.HandlerFunc) *App {
|
||||
ErrorMaps[err] = h
|
||||
middleware.Errorhandler(err, h)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// SetViewsPath sets view directory path in beego application.
|
||||
func SetViewsPath(path string) *App {
|
||||
BeeApp.SetViewsPath(path)
|
||||
ViewsPath = path
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// SetStaticPath sets static directory path and proper url pattern in beego application.
|
||||
// if beego.SetStaticPath("static","public"), visit /static/* to load static file in folder "public".
|
||||
func SetStaticPath(url string, path string) *App {
|
||||
if !strings.HasPrefix(url, "/") {
|
||||
url = "/" + url
|
||||
}
|
||||
url = strings.TrimRight(url, "/")
|
||||
StaticDir[url] = path
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// DelStaticPath removes the static folder setting in this url pattern in beego application.
|
||||
func DelStaticPath(url string) *App {
|
||||
delete(StaticDir, url)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func Filter(filter http.HandlerFunc) *App {
|
||||
BeeApp.Filter(filter)
|
||||
// InsertFilter adds a FilterFunc with pattern condition and action constant.
|
||||
// The pos means action constant including
|
||||
// beego.BeforeRouter, beego.AfterStatic, beego.BeforeExec, beego.AfterExec and beego.FinishRouter.
|
||||
func InsertFilter(pattern string, pos int, filter FilterFunc) *App {
|
||||
BeeApp.Handlers.InsertFilter(pattern, pos, filter)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func FilterParam(param string, filter http.HandlerFunc) *App {
|
||||
BeeApp.FilterParam(param, filter)
|
||||
return BeeApp
|
||||
// The hookfunc will run in beego.Run()
|
||||
// such as sessionInit, middlerware start, buildtemplate, admin start
|
||||
func AddAPPStartHook(hf hookfunc) {
|
||||
hooks = append(hooks, hf)
|
||||
}
|
||||
|
||||
func FilterPrefixPath(path string, filter http.HandlerFunc) *App {
|
||||
BeeApp.FilterPrefixPath(path, filter)
|
||||
return BeeApp
|
||||
// Run beego application.
|
||||
// beego.Run() default run on HttpPort
|
||||
// beego.Run(":8089")
|
||||
// beego.Run("127.0.0.1:8089")
|
||||
func Run(params ...string) {
|
||||
if len(params) > 0 && params[0] != "" {
|
||||
strs := strings.Split(params[0], ":")
|
||||
if len(strs) > 0 && strs[0] != "" {
|
||||
HttpAddr = strs[0]
|
||||
}
|
||||
if len(strs) > 1 && strs[1] != "" {
|
||||
HttpPort, _ = strconv.Atoi(strs[1])
|
||||
}
|
||||
}
|
||||
initBeforeHttpRun()
|
||||
|
||||
if EnableAdmin {
|
||||
go beeAdminApp.Run()
|
||||
}
|
||||
|
||||
BeeApp.Run()
|
||||
}
|
||||
|
||||
func FilterAfter(filter http.HandlerFunc) *App {
|
||||
BeeApp.FilterAfter(filter)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func FilterParamAfter(param string, filter http.HandlerFunc) *App {
|
||||
BeeApp.FilterParamAfter(param, filter)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func FilterPrefixPathAfter(path string, filter http.HandlerFunc) *App {
|
||||
BeeApp.FilterPrefixPathAfter(path, filter)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
func Run() {
|
||||
if AppConfigPath != path.Join(AppPath, "conf", "app.conf") {
|
||||
func initBeforeHttpRun() {
|
||||
// if AppConfigPath not In the conf/app.conf reParse config
|
||||
if AppConfigPath != filepath.Join(AppPath, "conf", "app.conf") {
|
||||
err := ParseConfig()
|
||||
if err != nil && AppConfigPath != filepath.Join(workPath, "conf", "app.conf") {
|
||||
// configuration is critical to app, panic here if parse failed
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// do hooks function
|
||||
for _, hk := range hooks {
|
||||
err := hk()
|
||||
if err != nil {
|
||||
if RunMode == "dev" {
|
||||
Warn(err)
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if PprofOn {
|
||||
BeeApp.Router(`/debug/pprof`, &ProfController{})
|
||||
BeeApp.Router(`/debug/pprof/:pp([\w]+)`, &ProfController{})
|
||||
}
|
||||
|
||||
if SessionOn {
|
||||
GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime, SessionSavePath)
|
||||
var err error
|
||||
sessionConfig := AppConfig.String("sessionConfig")
|
||||
if sessionConfig == "" {
|
||||
sessionConfig = `{"cookieName":"` + SessionName + `",` +
|
||||
`"gclifetime":` + strconv.FormatInt(SessionGCMaxLifetime, 10) + `,` +
|
||||
`"providerConfig":"` + SessionSavePath + `",` +
|
||||
`"secure":` + strconv.FormatBool(EnableHttpTLS) + `,` +
|
||||
`"sessionIDHashFunc":"` + SessionHashFunc + `",` +
|
||||
`"sessionIDHashKey":"` + SessionHashKey + `",` +
|
||||
`"enableSetCookie":` + strconv.FormatBool(SessionAutoSetCookie) + `,` +
|
||||
`"domain":"` + SessionDomain + `",` +
|
||||
`"cookieLifeTime":` + strconv.Itoa(SessionCookieLifeTime) + `}`
|
||||
}
|
||||
GlobalSessions, err = session.NewManager(SessionProvider,
|
||||
sessionConfig)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
go GlobalSessions.GC()
|
||||
}
|
||||
|
||||
err := BuildTemplate(ViewsPath)
|
||||
if err != nil {
|
||||
if RunMode == "dev" {
|
||||
Warn(err)
|
||||
}
|
||||
}
|
||||
registerErrorHander()
|
||||
BeeApp.Run()
|
||||
|
||||
middleware.VERSION = VERSION
|
||||
middleware.AppName = AppName
|
||||
middleware.RegisterErrorHandler()
|
||||
|
||||
if EnableDocs {
|
||||
Get("/docs", serverDocs)
|
||||
Get("/docs/*", serverDocs)
|
||||
}
|
||||
|
||||
//init mime
|
||||
AddAPPStartHook(initMime)
|
||||
}
|
||||
|
||||
// this function is for test package init
|
||||
func TestBeegoInit(apppath string) {
|
||||
AppPath = apppath
|
||||
RunMode = "test"
|
||||
AppConfigPath = filepath.Join(AppPath, "conf", "app.conf")
|
||||
err := ParseConfig()
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
// for init if doesn't have app.conf will not panic
|
||||
Info(err)
|
||||
}
|
||||
os.Chdir(AppPath)
|
||||
initBeforeHttpRun()
|
||||
}
|
||||
|
||||
func init() {
|
||||
hooks = make([]hookfunc, 0)
|
||||
}
|
||||
|
133
cache.go
@ -1,133 +0,0 @@
|
||||
package beego
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultEvery int = 60 // 1 minute
|
||||
)
|
||||
|
||||
type BeeItem struct {
|
||||
val interface{}
|
||||
Lastaccess time.Time
|
||||
expired int
|
||||
}
|
||||
|
||||
func (itm *BeeItem) Access() interface{} {
|
||||
itm.Lastaccess = time.Now()
|
||||
return itm.val
|
||||
}
|
||||
|
||||
type BeeCache struct {
|
||||
lock sync.RWMutex
|
||||
dur time.Duration
|
||||
items map[string]*BeeItem
|
||||
Every int // Run an expiration check Every seconds
|
||||
}
|
||||
|
||||
// NewDefaultCache returns a new FileCache with sane defaults.
|
||||
func NewBeeCache() *BeeCache {
|
||||
cache := BeeCache{dur: time.Since(time.Now()),
|
||||
Every: DefaultEvery}
|
||||
return &cache
|
||||
}
|
||||
|
||||
func (bc *BeeCache) Get(name string) interface{} {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
itm, ok := bc.items[name]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return itm.Access()
|
||||
}
|
||||
|
||||
func (bc *BeeCache) Put(name string, value interface{}, expired int) error {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
t := BeeItem{val: value, Lastaccess: time.Now(), expired: expired}
|
||||
if _, ok := bc.items[name]; ok {
|
||||
return errors.New("the key is exist")
|
||||
} else {
|
||||
bc.items[name] = &t
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bc *BeeCache) Delete(name string) (ok bool, err error) {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
if _, ok = bc.items[name]; !ok {
|
||||
return
|
||||
}
|
||||
delete(bc.items, name)
|
||||
_, valid := bc.items[name]
|
||||
if valid {
|
||||
ok = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Return all of the item in a BeeCache
|
||||
func (bc *BeeCache) Items() map[string]*BeeItem {
|
||||
return bc.items
|
||||
}
|
||||
|
||||
func (bc *BeeCache) IsExist(name string) bool {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
_, ok := bc.items[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Start activates the file cache; it will
|
||||
func (bc *BeeCache) Start() error {
|
||||
dur, err := time.ParseDuration(fmt.Sprintf("%ds", bc.Every))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bc.dur = dur
|
||||
bc.items = make(map[string]*BeeItem, 0)
|
||||
go bc.vaccuum()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bc *BeeCache) vaccuum() {
|
||||
if bc.Every < 1 {
|
||||
return
|
||||
}
|
||||
for {
|
||||
<-time.After(time.Duration(bc.dur))
|
||||
if bc.items == nil {
|
||||
return
|
||||
}
|
||||
for name, _ := range bc.items {
|
||||
bc.item_expired(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// item_expired returns true if an item is expired.
|
||||
func (bc *BeeCache) item_expired(name string) bool {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
itm, ok := bc.items[name]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
dur := time.Now().Sub(itm.Lastaccess)
|
||||
sec, err := strconv.Atoi(fmt.Sprintf("%0.0f", dur.Seconds()))
|
||||
if err != nil {
|
||||
delete(bc.items, name)
|
||||
return true
|
||||
} else if sec >= itm.expired {
|
||||
delete(bc.items, name)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
4
cache/README.md
vendored
@ -22,7 +22,7 @@ First you must import it
|
||||
|
||||
Then init a Cache (example with memory adapter)
|
||||
|
||||
bm, err := NewCache("memory", `{"interval":60}`)
|
||||
bm, err := cache.NewCache("memory", `{"interval":60}`)
|
||||
|
||||
Use it like this:
|
||||
|
||||
@ -43,7 +43,7 @@ interval means the gc time. The cache will check at each time interval, whether
|
||||
|
||||
## Memcache adapter
|
||||
|
||||
memory adapter use the vitess's [Memcache](http://code.google.com/p/vitess/go/memcache) client.
|
||||
Memcache adapter use the vitess's [Memcache](http://code.google.com/p/vitess/go/memcache) client.
|
||||
|
||||
Configure like this:
|
||||
|
||||
|
66
cache/cache.go
vendored
@ -1,17 +1,65 @@
|
||||
// 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.
|
||||
|
||||
// Usage:
|
||||
//
|
||||
// import(
|
||||
// "github.com/astaxie/beego/cache"
|
||||
// )
|
||||
//
|
||||
// bm, err := cache.NewCache("memory", `{"interval":60}`)
|
||||
//
|
||||
// Use it like this:
|
||||
//
|
||||
// bm.Put("astaxie", 1, 10)
|
||||
// bm.Get("astaxie")
|
||||
// bm.IsExist("astaxie")
|
||||
// bm.Delete("astaxie")
|
||||
//
|
||||
// more docs http://beego.me/docs/module/cache.md
|
||||
package cache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Cache interface contains all behaviors for cache adapter.
|
||||
// usage:
|
||||
// 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)
|
||||
// v := c.Get("key")
|
||||
//
|
||||
// c.Incr("counter") // now is 1
|
||||
// c.Incr("counter") // now is 2
|
||||
// count := c.Get("counter").(int)
|
||||
type Cache interface {
|
||||
// get cached value by key.
|
||||
Get(key string) interface{}
|
||||
// set cached value with key and expire time.
|
||||
Put(key string, val interface{}, timeout int64) error
|
||||
// delete cached value by key.
|
||||
Delete(key string) error
|
||||
// increase cached int value by key, as a counter.
|
||||
Incr(key string) error
|
||||
// decrease cached int value by key, as a counter.
|
||||
Decr(key string) error
|
||||
// check if cached value exists or not.
|
||||
IsExist(key string) bool
|
||||
// clear all cache.
|
||||
ClearAll() error
|
||||
// start gc routine based on config string settings.
|
||||
StartAndGC(config string) error
|
||||
}
|
||||
|
||||
@ -24,18 +72,24 @@ func Register(name string, adapter Cache) {
|
||||
if adapter == nil {
|
||||
panic("cache: Register adapter is nil")
|
||||
}
|
||||
if _, dup := adapters[name]; dup {
|
||||
if _, ok := adapters[name]; ok {
|
||||
panic("cache: Register called twice for adapter " + name)
|
||||
}
|
||||
adapters[name] = adapter
|
||||
}
|
||||
|
||||
// config need to be correct JSON as string: {"interval":360}
|
||||
func NewCache(adapterName, config string) (Cache, error) {
|
||||
// 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]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cache: unknown adaptername %q (forgotten import?)", adapterName)
|
||||
e = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName)
|
||||
return
|
||||
}
|
||||
adapter.StartAndGC(config)
|
||||
return adapter, nil
|
||||
err := adapter.StartAndGC(config)
|
||||
if err != nil {
|
||||
adapter = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
66
cache/cache_test.go
vendored
@ -1,3 +1,17 @@
|
||||
// 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 (
|
||||
@ -5,7 +19,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func Test_cache(t *testing.T) {
|
||||
func TestCache(t *testing.T) {
|
||||
bm, err := NewCache("memory", `{"interval":20}`)
|
||||
if err != nil {
|
||||
t.Error("init err")
|
||||
@ -40,7 +54,7 @@ func Test_cache(t *testing.T) {
|
||||
}
|
||||
|
||||
if err = bm.Decr("astaxie"); err != nil {
|
||||
t.Error("Incr Error", err)
|
||||
t.Error("Decr Error", err)
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(int) != 1 {
|
||||
@ -51,3 +65,51 @@ func Test_cache(t *testing.T) {
|
||||
t.Error("delete err")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileCache(t *testing.T) {
|
||||
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 {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(int) != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Incr("astaxie"); err != nil {
|
||||
t.Error("Incr Error", err)
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(int) != 2 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Decr("astaxie"); err != nil {
|
||||
t.Error("Decr Error", err)
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(int) != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
bm.Delete("astaxie")
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
//test string
|
||||
if err = bm.Put("astaxie", "author", 10); 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")
|
||||
}
|
||||
}
|
||||
|
112
cache/conv.go
vendored
Normal file
@ -0,0 +1,112 @@
|
||||
// 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 (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// convert interface to string.
|
||||
func GetString(v interface{}) string {
|
||||
switch result := v.(type) {
|
||||
case string:
|
||||
return result
|
||||
case []byte:
|
||||
return string(result)
|
||||
default:
|
||||
if v != nil {
|
||||
return fmt.Sprintf("%v", result)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// convert interface to int.
|
||||
func GetInt(v interface{}) int {
|
||||
switch result := v.(type) {
|
||||
case int:
|
||||
return result
|
||||
case int32:
|
||||
return int(result)
|
||||
case int64:
|
||||
return int(result)
|
||||
default:
|
||||
if d := GetString(v); d != "" {
|
||||
value, _ := strconv.Atoi(d)
|
||||
return value
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// convert interface to int64.
|
||||
func GetInt64(v interface{}) int64 {
|
||||
switch result := v.(type) {
|
||||
case int:
|
||||
return int64(result)
|
||||
case int32:
|
||||
return int64(result)
|
||||
case int64:
|
||||
return result
|
||||
default:
|
||||
|
||||
if d := GetString(v); d != "" {
|
||||
value, _ := strconv.ParseInt(d, 10, 64)
|
||||
return value
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// convert interface to float64.
|
||||
func GetFloat64(v interface{}) float64 {
|
||||
switch result := v.(type) {
|
||||
case float64:
|
||||
return result
|
||||
default:
|
||||
if d := GetString(v); d != "" {
|
||||
value, _ := strconv.ParseFloat(d, 64)
|
||||
return value
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// convert interface to bool.
|
||||
func GetBool(v interface{}) bool {
|
||||
switch result := v.(type) {
|
||||
case bool:
|
||||
return result
|
||||
default:
|
||||
if d := GetString(v); d != "" {
|
||||
value, _ := strconv.ParseBool(d)
|
||||
return value
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// convert interface to byte slice.
|
||||
func getByteArray(v interface{}) []byte {
|
||||
switch result := v.(type) {
|
||||
case []byte:
|
||||
return result
|
||||
case string:
|
||||
return []byte(result)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
158
cache/conv_test.go
vendored
Normal file
@ -0,0 +1,158 @@
|
||||
// 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 (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetString(t *testing.T) {
|
||||
var t1 = "test1"
|
||||
if "test1" != GetString(t1) {
|
||||
t.Error("get string from string error")
|
||||
}
|
||||
var t2 = []byte("test2")
|
||||
if "test2" != GetString(t2) {
|
||||
t.Error("get string from byte array error")
|
||||
}
|
||||
var t3 int = 1
|
||||
if "1" != GetString(t3) {
|
||||
t.Error("get string from int error")
|
||||
}
|
||||
var t4 int64 = 1
|
||||
if "1" != GetString(t4) {
|
||||
t.Error("get string from int64 error")
|
||||
}
|
||||
var t5 float64 = 1.1
|
||||
if "1.1" != GetString(t5) {
|
||||
t.Error("get string from float64 error")
|
||||
}
|
||||
|
||||
if "" != GetString(nil) {
|
||||
t.Error("get string from nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInt(t *testing.T) {
|
||||
var t1 int = 1
|
||||
if 1 != GetInt(t1) {
|
||||
t.Error("get int from int error")
|
||||
}
|
||||
var t2 int32 = 32
|
||||
if 32 != GetInt(t2) {
|
||||
t.Error("get int from int32 error")
|
||||
}
|
||||
var t3 int64 = 64
|
||||
if 64 != GetInt(t3) {
|
||||
t.Error("get int from int64 error")
|
||||
}
|
||||
var t4 = "128"
|
||||
if 128 != GetInt(t4) {
|
||||
t.Error("get int from num string error")
|
||||
}
|
||||
if 0 != GetInt(nil) {
|
||||
t.Error("get int from nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInt64(t *testing.T) {
|
||||
var i int64 = 1
|
||||
var t1 int = 1
|
||||
if i != GetInt64(t1) {
|
||||
t.Error("get int64 from int error")
|
||||
}
|
||||
var t2 int32 = 1
|
||||
if i != GetInt64(t2) {
|
||||
t.Error("get int64 from int32 error")
|
||||
}
|
||||
var t3 int64 = 1
|
||||
if i != GetInt64(t3) {
|
||||
t.Error("get int64 from int64 error")
|
||||
}
|
||||
var t4 = "1"
|
||||
if i != GetInt64(t4) {
|
||||
t.Error("get int64 from num string error")
|
||||
}
|
||||
if 0 != GetInt64(nil) {
|
||||
t.Error("get int64 from nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFloat64(t *testing.T) {
|
||||
var f float64 = 1.11
|
||||
var t1 float32 = 1.11
|
||||
if f != GetFloat64(t1) {
|
||||
t.Error("get float64 from float32 error")
|
||||
}
|
||||
var t2 float64 = 1.11
|
||||
if f != GetFloat64(t2) {
|
||||
t.Error("get float64 from float64 error")
|
||||
}
|
||||
var t3 = "1.11"
|
||||
if f != GetFloat64(t3) {
|
||||
t.Error("get float64 from string error")
|
||||
}
|
||||
|
||||
var f2 float64 = 1
|
||||
var t4 int = 1
|
||||
if f2 != GetFloat64(t4) {
|
||||
t.Error("get float64 from int error")
|
||||
}
|
||||
|
||||
if 0 != GetFloat64(nil) {
|
||||
t.Error("get float64 from nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBool(t *testing.T) {
|
||||
var t1 = true
|
||||
if true != GetBool(t1) {
|
||||
t.Error("get bool from bool error")
|
||||
}
|
||||
var t2 = "true"
|
||||
if true != GetBool(t2) {
|
||||
t.Error("get bool from string error")
|
||||
}
|
||||
if false != 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
|
||||
}
|
||||
for i, v := range a {
|
||||
if v != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
265
cache/file.go
vendored
Normal file
@ -0,0 +1,265 @@
|
||||
// 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 (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/gob"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("file", NewFileCache())
|
||||
}
|
||||
|
||||
// FileCacheItem is basic unit of file cache adapter.
|
||||
// it contains data and expire time.
|
||||
type FileCacheItem struct {
|
||||
Data interface{}
|
||||
Lastaccess int64
|
||||
Expired int64
|
||||
}
|
||||
|
||||
var (
|
||||
FileCachePath string = "cache" // cache directory
|
||||
FileCacheFileSuffix string = ".bin" // cache file suffix
|
||||
FileCacheDirectoryLevel int = 2 // cache file deep level if auto generated cache files.
|
||||
FileCacheEmbedExpiry int64 = 0 // cache expire time, default is no expire forever.
|
||||
)
|
||||
|
||||
// FileCache is cache adapter for file storage.
|
||||
type FileCache struct {
|
||||
CachePath string
|
||||
FileSuffix string
|
||||
DirectoryLevel int
|
||||
EmbedExpiry int
|
||||
}
|
||||
|
||||
// Create new file cache with no config.
|
||||
// the level and expiry need set in method StartAndGC as config string.
|
||||
func NewFileCache() *FileCache {
|
||||
// return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix}
|
||||
return &FileCache{}
|
||||
}
|
||||
|
||||
// Start and begin gc for file cache.
|
||||
// the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}
|
||||
func (fc *FileCache) StartAndGC(config string) error {
|
||||
|
||||
var cfg map[string]string
|
||||
json.Unmarshal([]byte(config), &cfg)
|
||||
if _, ok := cfg["CachePath"]; !ok {
|
||||
cfg["CachePath"] = FileCachePath
|
||||
}
|
||||
if _, ok := cfg["FileSuffix"]; !ok {
|
||||
cfg["FileSuffix"] = FileCacheFileSuffix
|
||||
}
|
||||
if _, ok := cfg["DirectoryLevel"]; !ok {
|
||||
cfg["DirectoryLevel"] = strconv.Itoa(FileCacheDirectoryLevel)
|
||||
}
|
||||
if _, ok := cfg["EmbedExpiry"]; !ok {
|
||||
cfg["EmbedExpiry"] = strconv.FormatInt(FileCacheEmbedExpiry, 10)
|
||||
}
|
||||
fc.CachePath = cfg["CachePath"]
|
||||
fc.FileSuffix = cfg["FileSuffix"]
|
||||
fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"])
|
||||
fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"])
|
||||
|
||||
fc.Init()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Init will make new dir for file cache if not exist.
|
||||
func (fc *FileCache) Init() {
|
||||
app := filepath.Dir(os.Args[0])
|
||||
fc.CachePath = filepath.Join(app, fc.CachePath)
|
||||
if ok, _ := exists(fc.CachePath); !ok { // todo : error handle
|
||||
_ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle
|
||||
}
|
||||
}
|
||||
|
||||
// get cached file name. it's md5 encoded.
|
||||
func (fc *FileCache) getCacheFileName(key string) string {
|
||||
m := md5.New()
|
||||
io.WriteString(m, key)
|
||||
keyMd5 := hex.EncodeToString(m.Sum(nil))
|
||||
cachePath := fc.CachePath
|
||||
switch fc.DirectoryLevel {
|
||||
case 2:
|
||||
cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4])
|
||||
case 1:
|
||||
cachePath = filepath.Join(cachePath, keyMd5[0:2])
|
||||
}
|
||||
|
||||
if ok, _ := exists(cachePath); !ok { // todo : error handle
|
||||
_ = os.MkdirAll(cachePath, os.ModePerm) // todo : error handle
|
||||
}
|
||||
|
||||
return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix))
|
||||
}
|
||||
|
||||
// Get value from file cache.
|
||||
// if non-exist or expired, return empty string.
|
||||
func (fc *FileCache) Get(key string) interface{} {
|
||||
fileData, err := File_get_contents(fc.getCacheFileName(key))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var to FileCacheItem
|
||||
Gob_decode(fileData, &to)
|
||||
if to.Expired < time.Now().Unix() {
|
||||
return ""
|
||||
}
|
||||
return to.Data
|
||||
}
|
||||
|
||||
// Put value into file cache.
|
||||
// timeout means how long to keep this file, unit of ms.
|
||||
// if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever.
|
||||
func (fc *FileCache) Put(key string, val interface{}, timeout int64) error {
|
||||
gob.Register(val)
|
||||
|
||||
item := FileCacheItem{Data: val}
|
||||
if timeout == FileCacheEmbedExpiry {
|
||||
item.Expired = time.Now().Unix() + (86400 * 365 * 10) // ten years
|
||||
} else {
|
||||
item.Expired = time.Now().Unix() + timeout
|
||||
}
|
||||
item.Lastaccess = time.Now().Unix()
|
||||
data, err := Gob_encode(item)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return File_put_contents(fc.getCacheFileName(key), data)
|
||||
}
|
||||
|
||||
// Delete file cache value.
|
||||
func (fc *FileCache) Delete(key string) error {
|
||||
filename := fc.getCacheFileName(key)
|
||||
if ok, _ := exists(filename); ok {
|
||||
return os.Remove(filename)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Increase cached int value.
|
||||
// fc value is saving forever unless Delete.
|
||||
func (fc *FileCache) Incr(key string) error {
|
||||
data := fc.Get(key)
|
||||
var incr int
|
||||
if reflect.TypeOf(data).Name() != "int" {
|
||||
incr = 0
|
||||
} else {
|
||||
incr = data.(int) + 1
|
||||
}
|
||||
fc.Put(key, incr, FileCacheEmbedExpiry)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Decrease cached int value.
|
||||
func (fc *FileCache) Decr(key string) error {
|
||||
data := fc.Get(key)
|
||||
var decr int
|
||||
if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 {
|
||||
decr = 0
|
||||
} else {
|
||||
decr = data.(int) - 1
|
||||
}
|
||||
fc.Put(key, decr, FileCacheEmbedExpiry)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check value is exist.
|
||||
func (fc *FileCache) IsExist(key string) bool {
|
||||
ret, _ := exists(fc.getCacheFileName(key))
|
||||
return ret
|
||||
}
|
||||
|
||||
// Clean cached files.
|
||||
// not implemented.
|
||||
func (fc *FileCache) ClearAll() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check file exist.
|
||||
func exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Get bytes to file.
|
||||
// if non-exist, create this file.
|
||||
func File_get_contents(filename string) (data []byte, e error) {
|
||||
f, e := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
stat, e := f.Stat()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
data = make([]byte, stat.Size())
|
||||
result, e := f.Read(data)
|
||||
if e != nil || int64(result) != stat.Size() {
|
||||
return nil, e
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Put bytes to file.
|
||||
// if non-exist, create this file.
|
||||
func File_put_contents(filename string, content []byte) error {
|
||||
fp, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fp.Close()
|
||||
_, err = fp.Write(content)
|
||||
return err
|
||||
}
|
||||
|
||||
// Gob encodes file cache item.
|
||||
func Gob_encode(data interface{}) ([]byte, error) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
enc := gob.NewEncoder(buf)
|
||||
err := enc.Encode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), err
|
||||
}
|
||||
|
||||
// Gob decodes file cache item.
|
||||
func Gob_decode(data []byte, to *FileCacheItem) error {
|
||||
buf := bytes.NewBuffer(data)
|
||||
dec := gob.NewDecoder(buf)
|
||||
return dec.Decode(&to)
|
||||
}
|
114
cache/memcache.go
vendored
@ -1,114 +0,0 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"code.google.com/p/vitess/go/memcache"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type MemcacheCache struct {
|
||||
c *memcache.Connection
|
||||
conninfo string
|
||||
}
|
||||
|
||||
func NewMemCache() *MemcacheCache {
|
||||
return &MemcacheCache{}
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) Get(key string) interface{} {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
v, err := rc.c.Get(key)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var contain interface{}
|
||||
if len(v) > 0 {
|
||||
contain = string(v[0].Value)
|
||||
} else {
|
||||
contain = nil
|
||||
}
|
||||
return contain
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) Put(key string, val interface{}, timeout int64) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
v, ok := val.(string)
|
||||
if !ok {
|
||||
return errors.New("val must string")
|
||||
}
|
||||
stored, err := rc.c.Set(key, 0, uint64(timeout), []byte(v))
|
||||
if err == nil && stored == false {
|
||||
return errors.New("stored fail")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) Delete(key string) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := rc.c.Delete(key)
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) Incr(key string) error {
|
||||
return errors.New("not support in memcache")
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) Decr(key string) error {
|
||||
return errors.New("not support in memcache")
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) IsExist(key string) bool {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
v, err := rc.c.Get(key)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if len(v) == 0 {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) ClearAll() error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
err := rc.c.FlushAll()
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) StartAndGC(config string) error {
|
||||
var cf map[string]string
|
||||
json.Unmarshal([]byte(config), &cf)
|
||||
if _, ok := cf["conn"]; !ok {
|
||||
return errors.New("config has no conn key")
|
||||
}
|
||||
rc.conninfo = cf["conn"]
|
||||
rc.c = rc.connectInit()
|
||||
if rc.c == nil {
|
||||
return errors.New("dial tcp conn error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *MemcacheCache) connectInit() *memcache.Connection {
|
||||
c, err := memcache.Connect(rc.conninfo)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("memcache", NewMemCache())
|
||||
}
|
163
cache/memcache/memcache.go
vendored
Normal file
@ -0,0 +1,163 @@
|
||||
// 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 memcahe 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 (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/bradfitz/gomemcache/memcache"
|
||||
|
||||
"github.com/astaxie/beego/cache"
|
||||
)
|
||||
|
||||
// Memcache adapter.
|
||||
type MemcacheCache struct {
|
||||
conn *memcache.Client
|
||||
conninfo []string
|
||||
}
|
||||
|
||||
// create new memcache adapter.
|
||||
func NewMemCache() *MemcacheCache {
|
||||
return &MemcacheCache{}
|
||||
}
|
||||
|
||||
// get value from memcache.
|
||||
func (rc *MemcacheCache) Get(key string) interface{} {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if item, err := rc.conn.Get(key); err == nil {
|
||||
return string(item.Value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// put value to memcache. only support string.
|
||||
func (rc *MemcacheCache) Put(key string, val interface{}, timeout int64) error {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
v, ok := val.(string)
|
||||
if !ok {
|
||||
return errors.New("val must string")
|
||||
}
|
||||
item := memcache.Item{Key: key, Value: []byte(v), Expiration: int32(timeout)}
|
||||
return rc.conn.Set(&item)
|
||||
}
|
||||
|
||||
// delete value in memcache.
|
||||
func (rc *MemcacheCache) Delete(key string) error {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rc.conn.Delete(key)
|
||||
}
|
||||
|
||||
// increase counter.
|
||||
func (rc *MemcacheCache) Incr(key string) error {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := rc.conn.Increment(key, 1)
|
||||
return err
|
||||
}
|
||||
|
||||
// decrease counter.
|
||||
func (rc *MemcacheCache) Decr(key string) error {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := rc.conn.Decrement(key, 1)
|
||||
return err
|
||||
}
|
||||
|
||||
// check value exists in memcache.
|
||||
func (rc *MemcacheCache) IsExist(key string) bool {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
_, err := rc.conn.Get(key)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// clear all cached in memcache.
|
||||
func (rc *MemcacheCache) ClearAll() error {
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rc.conn.FlushAll()
|
||||
}
|
||||
|
||||
// start memcache adapter.
|
||||
// config string is like {"conn":"connection info"}.
|
||||
// if connecting error, return.
|
||||
func (rc *MemcacheCache) StartAndGC(config string) error {
|
||||
var cf map[string]string
|
||||
json.Unmarshal([]byte(config), &cf)
|
||||
if _, ok := cf["conn"]; !ok {
|
||||
return errors.New("config has no conn key")
|
||||
}
|
||||
rc.conninfo = strings.Split(cf["conn"], ";")
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// connect to memcache and keep the connection.
|
||||
func (rc *MemcacheCache) connectInit() error {
|
||||
rc.conn = memcache.New(rc.conninfo...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
cache.Register("memcache", NewMemCache())
|
||||
}
|
71
cache/memory.go
vendored
@ -1,3 +1,17 @@
|
||||
// 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 (
|
||||
@ -9,58 +23,61 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// clock time of recycling the expired cache items in memory.
|
||||
DefaultEvery int = 60 // 1 minute
|
||||
)
|
||||
|
||||
// Memory cache item.
|
||||
type MemoryItem struct {
|
||||
val interface{}
|
||||
Lastaccess time.Time
|
||||
expired int64
|
||||
}
|
||||
|
||||
// Memory cache adapter.
|
||||
// it contains a RW locker for safe map storage.
|
||||
type MemoryCache struct {
|
||||
lock sync.RWMutex
|
||||
dur time.Duration
|
||||
items map[string]*MemoryItem
|
||||
Every int // Run an expiration check Every seconds
|
||||
Every int // run an expiration check Every clock time
|
||||
}
|
||||
|
||||
// NewDefaultCache returns a new FileCache with sane defaults.
|
||||
// NewMemoryCache returns a new MemoryCache.
|
||||
func NewMemoryCache() *MemoryCache {
|
||||
cache := MemoryCache{items: make(map[string]*MemoryItem)}
|
||||
return &cache
|
||||
}
|
||||
|
||||
// Get cache from memory.
|
||||
// if non-existed or expired, return nil.
|
||||
func (bc *MemoryCache) Get(name string) interface{} {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
itm, ok := bc.items[name]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if itm, ok := bc.items[name]; ok {
|
||||
if (time.Now().Unix() - itm.Lastaccess.Unix()) > itm.expired {
|
||||
go bc.Delete(name)
|
||||
return nil
|
||||
}
|
||||
return itm.val
|
||||
}
|
||||
|
||||
func (bc *MemoryCache) Put(name string, value interface{}, expired int64) error {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
t := MemoryItem{
|
||||
val: value,
|
||||
Lastaccess: time.Now(),
|
||||
expired: expired,
|
||||
}
|
||||
if _, ok := bc.items[name]; ok {
|
||||
return errors.New("the key is exist")
|
||||
} else {
|
||||
bc.items[name] = &t
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put cache to memory.
|
||||
// if expired is 0, it will be cleaned by next gc operation ( default gc clock is 1 minute).
|
||||
func (bc *MemoryCache) Put(name string, value interface{}, expired int64) error {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
bc.items[name] = &MemoryItem{
|
||||
val: value,
|
||||
Lastaccess: time.Now(),
|
||||
expired: expired,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Delete cache in memory.
|
||||
func (bc *MemoryCache) Delete(name string) error {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
@ -68,13 +85,14 @@ func (bc *MemoryCache) Delete(name string) error {
|
||||
return errors.New("key not exist")
|
||||
}
|
||||
delete(bc.items, name)
|
||||
_, valid := bc.items[name]
|
||||
if valid {
|
||||
if _, ok := bc.items[name]; ok {
|
||||
return errors.New("delete key error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Increase cache counter in memory.
|
||||
// it supports int,int64,int32,uint,uint64,uint32.
|
||||
func (bc *MemoryCache) Incr(key string) error {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
@ -101,6 +119,7 @@ func (bc *MemoryCache) Incr(key string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Decrease counter in memory.
|
||||
func (bc *MemoryCache) Decr(key string) error {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
@ -139,6 +158,7 @@ func (bc *MemoryCache) Decr(key string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check cache exist in memory.
|
||||
func (bc *MemoryCache) IsExist(name string) bool {
|
||||
bc.lock.RLock()
|
||||
defer bc.lock.RUnlock()
|
||||
@ -146,6 +166,7 @@ func (bc *MemoryCache) IsExist(name string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// delete all cache in memory.
|
||||
func (bc *MemoryCache) ClearAll() error {
|
||||
bc.lock.Lock()
|
||||
defer bc.lock.Unlock()
|
||||
@ -153,7 +174,7 @@ func (bc *MemoryCache) ClearAll() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start activates the file cache; it will
|
||||
// start memory cache. it will check expiration in every clock time.
|
||||
func (bc *MemoryCache) StartAndGC(config string) error {
|
||||
var cf map[string]int
|
||||
json.Unmarshal([]byte(config), &cf)
|
||||
@ -171,6 +192,7 @@ func (bc *MemoryCache) StartAndGC(config string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check expiration.
|
||||
func (bc *MemoryCache) vaccuum() {
|
||||
if bc.Every < 1 {
|
||||
return
|
||||
@ -194,8 +216,7 @@ func (bc *MemoryCache) item_expired(name string) bool {
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sec := time.Now().Unix() - itm.Lastaccess.Unix()
|
||||
if sec >= itm.expired {
|
||||
if time.Now().Unix()-itm.Lastaccess.Unix() >= itm.expired {
|
||||
delete(bc.items, name)
|
||||
return true
|
||||
}
|
||||
|
119
cache/redis.go
vendored
@ -1,119 +0,0 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultKey string = "beecacheRedis"
|
||||
)
|
||||
|
||||
type RedisCache struct {
|
||||
c redis.Conn
|
||||
conninfo string
|
||||
key string
|
||||
}
|
||||
|
||||
func NewRedisCache() *RedisCache {
|
||||
return &RedisCache{key: DefaultKey}
|
||||
}
|
||||
|
||||
func (rc *RedisCache) Get(key string) interface{} {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
v, err := rc.c.Do("HGET", rc.key, key)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (rc *RedisCache) Put(key string, val interface{}, timeout int64) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := rc.c.Do("HSET", rc.key, key, val)
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *RedisCache) Delete(key string) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := rc.c.Do("HDEL", rc.key, key)
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *RedisCache) IsExist(key string) bool {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
v, err := redis.Bool(rc.c.Do("HEXISTS", rc.key, key))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (rc *RedisCache) Incr(key string) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := redis.Bool(rc.c.Do("HINCRBY", rc.key, key, 1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *RedisCache) Decr(key string) error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := redis.Bool(rc.c.Do("HINCRBY", rc.key, key, -1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *RedisCache) ClearAll() error {
|
||||
if rc.c == nil {
|
||||
rc.c = rc.connectInit()
|
||||
}
|
||||
_, err := rc.c.Do("DEL", rc.key)
|
||||
return err
|
||||
}
|
||||
|
||||
func (rc *RedisCache) StartAndGC(config string) error {
|
||||
var cf map[string]string
|
||||
json.Unmarshal([]byte(config), &cf)
|
||||
if _, ok := cf["key"]; !ok {
|
||||
cf["key"] = DefaultKey
|
||||
}
|
||||
if _, ok := cf["conn"]; !ok {
|
||||
return errors.New("config has no conn key")
|
||||
}
|
||||
rc.key = cf["key"]
|
||||
rc.conninfo = cf["conn"]
|
||||
rc.c = rc.connectInit()
|
||||
if rc.c == nil {
|
||||
return errors.New("dial tcp conn error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *RedisCache) connectInit() redis.Conn {
|
||||
c, err := redis.Dial("tcp", rc.conninfo)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("redis", NewRedisCache())
|
||||
}
|
182
cache/redis/redis.go
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
// 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/garyburd/redigo/redis
|
||||
//
|
||||
// go install github.com/garyburd/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 (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
|
||||
"github.com/astaxie/beego/cache"
|
||||
)
|
||||
|
||||
var (
|
||||
// the collection name of redis for cache adapter.
|
||||
DefaultKey string = "beecacheRedis"
|
||||
)
|
||||
|
||||
// Redis cache adapter.
|
||||
type RedisCache struct {
|
||||
p *redis.Pool // redis connection pool
|
||||
conninfo string
|
||||
key string
|
||||
}
|
||||
|
||||
// create new redis cache with default collection name.
|
||||
func NewRedisCache() *RedisCache {
|
||||
return &RedisCache{key: DefaultKey}
|
||||
}
|
||||
|
||||
// actually do the redis cmds
|
||||
func (rc *RedisCache) do(commandName string, args ...interface{}) (reply interface{}, err error) {
|
||||
c := rc.p.Get()
|
||||
defer c.Close()
|
||||
|
||||
return c.Do(commandName, args...)
|
||||
}
|
||||
|
||||
// Get cache from redis.
|
||||
func (rc *RedisCache) Get(key string) interface{} {
|
||||
if v, err := rc.do("GET", key); err == nil {
|
||||
return v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// put cache to redis.
|
||||
func (rc *RedisCache) Put(key string, val interface{}, timeout int64) error {
|
||||
var err error
|
||||
if _, err = rc.do("SET", key, val); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err = rc.do("HSET", rc.key, key, true); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = rc.do("EXPIRE", key, timeout)
|
||||
return err
|
||||
}
|
||||
|
||||
// delete cache in redis.
|
||||
func (rc *RedisCache) Delete(key string) error {
|
||||
var err error
|
||||
if _, err = rc.do("DEL", key); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = rc.do("HDEL", rc.key, key)
|
||||
return err
|
||||
}
|
||||
|
||||
// check cache's existence in redis.
|
||||
func (rc *RedisCache) IsExist(key string) bool {
|
||||
v, err := redis.Bool(rc.do("EXISTS", key))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if v == false {
|
||||
if _, err = rc.do("HDEL", rc.key, key); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// increase counter in redis.
|
||||
func (rc *RedisCache) Incr(key string) error {
|
||||
_, err := redis.Bool(rc.do("INCRBY", key, 1))
|
||||
return err
|
||||
}
|
||||
|
||||
// decrease counter in redis.
|
||||
func (rc *RedisCache) Decr(key string) error {
|
||||
_, err := redis.Bool(rc.do("INCRBY", key, -1))
|
||||
return err
|
||||
}
|
||||
|
||||
// clean all cache in redis. delete this redis collection.
|
||||
func (rc *RedisCache) ClearAll() error {
|
||||
cachedKeys, err := redis.Strings(rc.do("HKEYS", rc.key))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, str := range cachedKeys {
|
||||
if _, err = rc.do("DEL", str); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = rc.do("DEL", rc.key)
|
||||
return err
|
||||
}
|
||||
|
||||
// start redis cache adapter.
|
||||
// config is like {"key":"collection key","conn":"connection info"}
|
||||
// the cache item in redis are stored forever,
|
||||
// so no gc operation.
|
||||
func (rc *RedisCache) StartAndGC(config string) error {
|
||||
var cf map[string]string
|
||||
json.Unmarshal([]byte(config), &cf)
|
||||
|
||||
if _, ok := cf["key"]; !ok {
|
||||
cf["key"] = DefaultKey
|
||||
}
|
||||
|
||||
if _, ok := cf["conn"]; !ok {
|
||||
return errors.New("config has no conn key")
|
||||
}
|
||||
|
||||
rc.key = cf["key"]
|
||||
rc.conninfo = cf["conn"]
|
||||
rc.connectInit()
|
||||
|
||||
c := rc.p.Get()
|
||||
defer c.Close()
|
||||
|
||||
return c.Err()
|
||||
}
|
||||
|
||||
// connect to redis.
|
||||
func (rc *RedisCache) connectInit() {
|
||||
dialFunc := func() (c redis.Conn, err error) {
|
||||
c, err = redis.Dial("tcp", rc.conninfo)
|
||||
return
|
||||
}
|
||||
// initialize a new pool
|
||||
rc.p = &redis.Pool{
|
||||
MaxIdle: 3,
|
||||
IdleTimeout: 180 * time.Second,
|
||||
Dial: dialFunc,
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cache.Register("redis", NewRedisCache())
|
||||
}
|
85
cache/redis/redis_test.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// 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
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
|
||||
"github.com/astaxie/beego/cache"
|
||||
)
|
||||
|
||||
func TestRedisCache(t *testing.T) {
|
||||
bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`)
|
||||
if err != nil {
|
||||
t.Error("init err")
|
||||
}
|
||||
if err = bm.Put("astaxie", 1, 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
if err = bm.Put("astaxie", 1, 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
|
||||
if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Incr("astaxie"); err != nil {
|
||||
t.Error("Incr Error", err)
|
||||
}
|
||||
|
||||
if v, _ := redis.Int(bm.Get("astaxie"), err); v != 2 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Decr("astaxie"); err != nil {
|
||||
t.Error("Decr Error", err)
|
||||
}
|
||||
|
||||
if v, _ := redis.Int(bm.Get("astaxie"), err); 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", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" {
|
||||
t.Error("get err")
|
||||
}
|
||||
// test clear all
|
||||
if err = bm.ClearAll(); err != nil {
|
||||
t.Error("clear all err")
|
||||
}
|
||||
}
|
542
config.go
@ -1,203 +1,433 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"os"
|
||||
"strconv"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
|
||||
"github.com/astaxie/beego/config"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/astaxie/beego/session"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
var (
|
||||
bComment = []byte{'#'}
|
||||
bEmpty = []byte{}
|
||||
bEqual = []byte{'='}
|
||||
bDQuote = []byte{'"'}
|
||||
BeeApp *App // beego application
|
||||
AppName string
|
||||
AppPath string
|
||||
workPath string
|
||||
AppConfigPath string
|
||||
StaticDir map[string]string
|
||||
TemplateCache map[string]*template.Template // template caching map
|
||||
StaticExtensionsToGzip []string // files with should be compressed with gzip (.js,.css,etc)
|
||||
EnableHttpListen bool
|
||||
HttpAddr string
|
||||
HttpPort int
|
||||
EnableHttpTLS bool
|
||||
HttpsPort int
|
||||
HttpCertFile string
|
||||
HttpKeyFile string
|
||||
RecoverPanic bool // flag of auto recover panic
|
||||
AutoRender bool // flag of render template automatically
|
||||
ViewsPath string
|
||||
RunMode string // run mode, "dev" or "prod"
|
||||
AppConfig config.ConfigContainer
|
||||
GlobalSessions *session.Manager // global session mananger
|
||||
SessionOn bool // flag of starting session auto. default is false.
|
||||
SessionProvider string // default session provider, memory, mysql , redis ,etc.
|
||||
SessionName string // the cookie name when saving session id into cookie.
|
||||
SessionGCMaxLifetime int64 // session gc time for auto cleaning expired session.
|
||||
SessionSavePath string // if use mysql/redis/file provider, define save path to connection info.
|
||||
SessionHashFunc string // session hash generation func.
|
||||
SessionHashKey string // session hash salt string.
|
||||
SessionCookieLifeTime int // the life time of session id in cookie.
|
||||
SessionAutoSetCookie bool // auto setcookie
|
||||
SessionDomain string // the cookie domain default is empty
|
||||
UseFcgi bool
|
||||
MaxMemory int64
|
||||
EnableGzip bool // flag of enable gzip
|
||||
DirectoryIndex bool // flag of display directory index. default is false.
|
||||
HttpServerTimeOut int64
|
||||
ErrorsShow bool // flag of show errors in page. if true, show error and trace info in page rendered with error template.
|
||||
XSRFKEY string // xsrf hash salt string.
|
||||
EnableXSRF bool // flag of enable xsrf.
|
||||
XSRFExpire int // the expiry of xsrf value.
|
||||
CopyRequestBody bool // flag of copy raw request body in context.
|
||||
TemplateLeft string
|
||||
TemplateRight string
|
||||
BeegoServerName string // beego server name exported in response header.
|
||||
EnableAdmin bool // flag of enable admin module to log every request info.
|
||||
AdminHttpAddr string // http server configurations for admin module.
|
||||
AdminHttpPort int
|
||||
FlashName string // name of the flash variable found in response header and cookie
|
||||
FlashSeperator string // used to seperate flash key:value
|
||||
AppConfigProvider string // config provider
|
||||
EnableDocs bool // enable generate docs & server docs API Swagger
|
||||
)
|
||||
|
||||
// A Config represents the configuration.
|
||||
type Config struct {
|
||||
filename string
|
||||
comment map[int][]string // id: []{comment, key...}; id 1 is for main comment.
|
||||
data map[string]string // key: value
|
||||
offset map[string]int64 // key: offset; for editing.
|
||||
sync.RWMutex
|
||||
}
|
||||
func init() {
|
||||
// create beego application
|
||||
BeeApp = NewApp()
|
||||
|
||||
// ParseFile creates a new Config and parses the file configuration from the
|
||||
// named file.
|
||||
func LoadConfig(name string) (*Config, error) {
|
||||
file, err := os.Open(name)
|
||||
workPath, _ = os.Getwd()
|
||||
workPath, _ = filepath.Abs(workPath)
|
||||
// initialize default configurations
|
||||
AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
|
||||
|
||||
AppConfigPath = filepath.Join(AppPath, "conf", "app.conf")
|
||||
|
||||
if workPath != AppPath {
|
||||
if utils.FileExists(AppConfigPath) {
|
||||
os.Chdir(AppPath)
|
||||
} else {
|
||||
AppConfigPath = filepath.Join(workPath, "conf", "app.conf")
|
||||
}
|
||||
}
|
||||
|
||||
AppConfigProvider = "ini"
|
||||
|
||||
StaticDir = make(map[string]string)
|
||||
StaticDir["/static"] = "static"
|
||||
|
||||
StaticExtensionsToGzip = []string{".css", ".js"}
|
||||
|
||||
TemplateCache = make(map[string]*template.Template)
|
||||
|
||||
// set this to 0.0.0.0 to make this app available to externally
|
||||
EnableHttpListen = true //default enable http Listen
|
||||
|
||||
HttpAddr = ""
|
||||
HttpPort = 8080
|
||||
|
||||
HttpsPort = 10443
|
||||
|
||||
AppName = "beego"
|
||||
|
||||
RunMode = "dev" //default runmod
|
||||
|
||||
AutoRender = true
|
||||
|
||||
RecoverPanic = true
|
||||
|
||||
ViewsPath = "views"
|
||||
|
||||
SessionOn = false
|
||||
SessionProvider = "memory"
|
||||
SessionName = "beegosessionID"
|
||||
SessionGCMaxLifetime = 3600
|
||||
SessionSavePath = ""
|
||||
SessionHashFunc = "sha1"
|
||||
SessionHashKey = "beegoserversessionkey"
|
||||
SessionCookieLifeTime = 0 //set cookie default is the brower life
|
||||
SessionAutoSetCookie = true
|
||||
|
||||
UseFcgi = false
|
||||
|
||||
MaxMemory = 1 << 26 //64MB
|
||||
|
||||
EnableGzip = false
|
||||
|
||||
HttpServerTimeOut = 0
|
||||
|
||||
ErrorsShow = true
|
||||
|
||||
XSRFKEY = "beegoxsrf"
|
||||
XSRFExpire = 0
|
||||
|
||||
TemplateLeft = "{{"
|
||||
TemplateRight = "}}"
|
||||
|
||||
BeegoServerName = "beegoServer:" + VERSION
|
||||
|
||||
EnableAdmin = false
|
||||
AdminHttpAddr = "127.0.0.1"
|
||||
AdminHttpPort = 8088
|
||||
|
||||
FlashName = "BEEGO_FLASH"
|
||||
FlashSeperator = "BEEGOFLASH"
|
||||
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
|
||||
// init BeeLogger
|
||||
BeeLogger = logs.NewLogger(10000)
|
||||
err := BeeLogger.SetLogger("console", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
fmt.Println("init console log error:", err)
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
file.Name(),
|
||||
make(map[int][]string),
|
||||
make(map[string]string),
|
||||
make(map[string]int64),
|
||||
sync.RWMutex{},
|
||||
err = ParseConfig()
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
// for init if doesn't have app.conf will not panic
|
||||
Info(err)
|
||||
}
|
||||
cfg.Lock()
|
||||
defer cfg.Unlock()
|
||||
defer file.Close()
|
||||
|
||||
var comment bytes.Buffer
|
||||
buf := bufio.NewReader(file)
|
||||
|
||||
for nComment, off := 0, int64(1); ; {
|
||||
line, _, err := buf.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if bytes.Equal(line, bEmpty) {
|
||||
continue
|
||||
}
|
||||
|
||||
off += int64(len(line))
|
||||
|
||||
if bytes.HasPrefix(line, bComment) {
|
||||
line = bytes.TrimLeft(line, "#")
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
comment.Write(line)
|
||||
comment.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
if comment.Len() != 0 {
|
||||
cfg.comment[nComment] = []string{comment.String()}
|
||||
comment.Reset()
|
||||
nComment++
|
||||
}
|
||||
|
||||
val := bytes.SplitN(line, bEqual, 2)
|
||||
if bytes.HasPrefix([]byte(strings.TrimSpace(string(val[1]))), bDQuote) {
|
||||
val[1] = bytes.Trim([]byte(strings.TrimSpace(string(val[1]))), `"`)
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(string(val[0]))
|
||||
cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
|
||||
cfg.data[key] = strings.TrimSpace(string(val[1]))
|
||||
cfg.offset[key] = off
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *Config) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.data[key])
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *Config) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.data[key])
|
||||
}
|
||||
|
||||
func (c *Config) Int64(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.data[key], 10, 64)
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *Config) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.data[key], 64)
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *Config) String(key string) string {
|
||||
return c.data[key]
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
func (c *Config) SetValue(key, value string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
if _, found := c.data[key]; !found {
|
||||
return errors.New("key not found: " + key)
|
||||
}
|
||||
|
||||
c.data[key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseConfig parsed default config file.
|
||||
// now only support ini, next will support json.
|
||||
func ParseConfig() (err error) {
|
||||
AppConfig, err = LoadConfig(AppConfigPath)
|
||||
AppConfig, err = config.NewConfig(AppConfigProvider, AppConfigPath)
|
||||
if err != nil {
|
||||
AppConfig = config.NewFakeConfig()
|
||||
return err
|
||||
} else {
|
||||
HttpAddr = AppConfig.String("httpaddr")
|
||||
if v, err := AppConfig.Int("httpport"); err == nil {
|
||||
HttpPort = v
|
||||
|
||||
if v, err := GetConfig("string", "HttpAddr"); err == nil {
|
||||
HttpAddr = v.(string)
|
||||
}
|
||||
if maxmemory, err := AppConfig.Int64("maxmemory"); err == nil {
|
||||
MaxMemory = maxmemory
|
||||
|
||||
if v, err := GetConfig("int", "HttpPort"); err == nil {
|
||||
HttpPort = v.(int)
|
||||
}
|
||||
AppName = AppConfig.String("appname")
|
||||
if runmode := AppConfig.String("runmode"); runmode != "" {
|
||||
RunMode = runmode
|
||||
|
||||
if v, err := GetConfig("bool", "EnableHttpListen"); err == nil {
|
||||
EnableHttpListen = v.(bool)
|
||||
}
|
||||
if autorender, err := AppConfig.Bool("autorender"); err == nil {
|
||||
AutoRender = autorender
|
||||
|
||||
if maxmemory, err := GetConfig("int64", "MaxMemory"); err == nil {
|
||||
MaxMemory = maxmemory.(int64)
|
||||
}
|
||||
if autorecover, err := AppConfig.Bool("autorecover"); err == nil {
|
||||
RecoverPanic = autorecover
|
||||
|
||||
if appname, _ := GetConfig("string", "AppName"); appname != "" {
|
||||
AppName = appname.(string)
|
||||
}
|
||||
if pprofon, err := AppConfig.Bool("pprofon"); err == nil {
|
||||
PprofOn = pprofon
|
||||
|
||||
if runmode, _ := GetConfig("string", "RunMode"); runmode != "" {
|
||||
RunMode = runmode.(string)
|
||||
}
|
||||
if views := AppConfig.String("viewspath"); views != "" {
|
||||
ViewsPath = views
|
||||
|
||||
if autorender, err := GetConfig("bool", "AutoRender"); err == nil {
|
||||
AutoRender = autorender.(bool)
|
||||
}
|
||||
if sessionon, err := AppConfig.Bool("sessionon"); err == nil {
|
||||
SessionOn = sessionon
|
||||
|
||||
if autorecover, err := GetConfig("bool", "RecoverPanic"); err == nil {
|
||||
RecoverPanic = autorecover.(bool)
|
||||
}
|
||||
if sessProvider := AppConfig.String("sessionprovider"); sessProvider != "" {
|
||||
SessionProvider = sessProvider
|
||||
|
||||
if views, _ := GetConfig("string", "ViewsPath"); views != "" {
|
||||
ViewsPath = views.(string)
|
||||
}
|
||||
if sessName := AppConfig.String("sessionname"); sessName != "" {
|
||||
SessionName = sessName
|
||||
|
||||
if sessionon, err := GetConfig("bool", "SessionOn"); err == nil {
|
||||
SessionOn = sessionon.(bool)
|
||||
}
|
||||
if sesssavepath := AppConfig.String("sessionsavepath"); sesssavepath != "" {
|
||||
SessionSavePath = sesssavepath
|
||||
|
||||
if sessProvider, _ := GetConfig("string", "SessionProvider"); sessProvider != "" {
|
||||
SessionProvider = sessProvider.(string)
|
||||
}
|
||||
if sessMaxLifeTime, err := AppConfig.Int("sessiongcmaxlifetime"); err == nil && sessMaxLifeTime != 0 {
|
||||
int64val, _ := strconv.ParseInt(strconv.Itoa(sessMaxLifeTime), 10, 64)
|
||||
SessionGCMaxLifetime = int64val
|
||||
|
||||
if sessName, _ := GetConfig("string", "SessionName"); sessName != "" {
|
||||
SessionName = sessName.(string)
|
||||
}
|
||||
if usefcgi, err := AppConfig.Bool("usefcgi"); err == nil {
|
||||
UseFcgi = usefcgi
|
||||
|
||||
if sesssavepath, _ := GetConfig("string", "SessionSavePath"); sesssavepath != "" {
|
||||
SessionSavePath = sesssavepath.(string)
|
||||
}
|
||||
if enablegzip, err := AppConfig.Bool("enablegzip"); err == nil {
|
||||
EnableGzip = enablegzip
|
||||
|
||||
if sesshashfunc, _ := GetConfig("string", "SessionHashFunc"); sesshashfunc != "" {
|
||||
SessionHashFunc = sesshashfunc.(string)
|
||||
}
|
||||
if directoryindex, err := AppConfig.Bool("directoryindex"); err == nil {
|
||||
DirectoryIndex = directoryindex
|
||||
|
||||
if sesshashkey, _ := GetConfig("string", "SessionHashKey"); sesshashkey != "" {
|
||||
SessionHashKey = sesshashkey.(string)
|
||||
}
|
||||
if hotupdate, err := AppConfig.Bool("hotupdate"); err == nil {
|
||||
EnbaleHotUpdate = hotupdate
|
||||
|
||||
if sessMaxLifeTime, err := GetConfig("int64", "SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
|
||||
SessionGCMaxLifetime = sessMaxLifeTime.(int64)
|
||||
}
|
||||
if timeout, err := AppConfig.Int64("httpservertimeout"); err == nil {
|
||||
HttpServerTimeOut = timeout
|
||||
|
||||
if sesscookielifetime, err := GetConfig("int", "SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
|
||||
SessionCookieLifeTime = sesscookielifetime.(int)
|
||||
}
|
||||
if errorsshow, err := AppConfig.Bool("errorsshow"); err == nil {
|
||||
ErrorsShow = errorsshow
|
||||
|
||||
if usefcgi, err := GetConfig("bool", "UseFcgi"); err == nil {
|
||||
UseFcgi = usefcgi.(bool)
|
||||
}
|
||||
if copyrequestbody, err := AppConfig.Bool("copyrequestbody"); err == nil {
|
||||
CopyRequestBody = copyrequestbody
|
||||
|
||||
if enablegzip, err := GetConfig("bool", "EnableGzip"); err == nil {
|
||||
EnableGzip = enablegzip.(bool)
|
||||
}
|
||||
if xsrfkey := AppConfig.String("xsrfkey"); xsrfkey != "" {
|
||||
XSRFKEY = xsrfkey
|
||||
|
||||
if directoryindex, err := GetConfig("bool", "DirectoryIndex"); err == nil {
|
||||
DirectoryIndex = directoryindex.(bool)
|
||||
}
|
||||
if enablexsrf, err := AppConfig.Bool("enablexsrf"); err == nil {
|
||||
EnableXSRF = enablexsrf
|
||||
|
||||
if timeout, err := GetConfig("int64", "HttpServerTimeOut"); err == nil {
|
||||
HttpServerTimeOut = timeout.(int64)
|
||||
}
|
||||
if expire, err := AppConfig.Int("xsrfexpire"); err == nil {
|
||||
XSRFExpire = expire
|
||||
|
||||
if errorsshow, err := GetConfig("bool", "ErrorsShow"); err == nil {
|
||||
ErrorsShow = errorsshow.(bool)
|
||||
}
|
||||
|
||||
if copyrequestbody, err := GetConfig("bool", "CopyRequestBody"); err == nil {
|
||||
CopyRequestBody = copyrequestbody.(bool)
|
||||
}
|
||||
|
||||
if xsrfkey, _ := GetConfig("string", "XSRFKEY"); xsrfkey != "" {
|
||||
XSRFKEY = xsrfkey.(string)
|
||||
}
|
||||
|
||||
if enablexsrf, err := GetConfig("bool", "EnableXSRF"); err == nil {
|
||||
EnableXSRF = enablexsrf.(bool)
|
||||
}
|
||||
|
||||
if expire, err := GetConfig("int", "XSRFExpire"); err == nil {
|
||||
XSRFExpire = expire.(int)
|
||||
}
|
||||
|
||||
if tplleft, _ := GetConfig("string", "TemplateLeft"); tplleft != "" {
|
||||
TemplateLeft = tplleft.(string)
|
||||
}
|
||||
|
||||
if tplright, _ := GetConfig("string", "TemplateRight"); tplright != "" {
|
||||
TemplateRight = tplright.(string)
|
||||
}
|
||||
|
||||
if httptls, err := GetConfig("bool", "EnableHttpTLS"); err == nil {
|
||||
EnableHttpTLS = httptls.(bool)
|
||||
}
|
||||
|
||||
if httpsport, err := GetConfig("int", "HttpsPort"); err == nil {
|
||||
HttpsPort = httpsport.(int)
|
||||
}
|
||||
|
||||
if certfile, _ := GetConfig("string", "HttpCertFile"); certfile != "" {
|
||||
HttpCertFile = certfile.(string)
|
||||
}
|
||||
|
||||
if keyfile, _ := GetConfig("string", "HttpKeyFile"); keyfile != "" {
|
||||
HttpKeyFile = keyfile.(string)
|
||||
}
|
||||
|
||||
if serverName, _ := GetConfig("string", "BeegoServerName"); serverName != "" {
|
||||
BeegoServerName = serverName.(string)
|
||||
}
|
||||
|
||||
if flashname, _ := GetConfig("string", "FlashName"); flashname != "" {
|
||||
FlashName = flashname.(string)
|
||||
}
|
||||
|
||||
if flashseperator, _ := GetConfig("string", "FlashSeperator"); flashseperator != "" {
|
||||
FlashSeperator = flashseperator.(string)
|
||||
}
|
||||
|
||||
if sd, _ := GetConfig("string", "StaticDir"); sd != "" {
|
||||
for k := range StaticDir {
|
||||
delete(StaticDir, k)
|
||||
}
|
||||
sds := strings.Fields(sd.(string))
|
||||
for _, v := range sds {
|
||||
if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 {
|
||||
StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[1]
|
||||
} else {
|
||||
StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sgz, _ := GetConfig("string", "StaticExtensionsToGzip"); sgz != "" {
|
||||
extensions := strings.Split(sgz.(string), ",")
|
||||
if len(extensions) > 0 {
|
||||
StaticExtensionsToGzip = []string{}
|
||||
for _, ext := range extensions {
|
||||
if len(ext) == 0 {
|
||||
continue
|
||||
}
|
||||
extWithDot := ext
|
||||
if extWithDot[:1] != "." {
|
||||
extWithDot = "." + extWithDot
|
||||
}
|
||||
StaticExtensionsToGzip = append(StaticExtensionsToGzip, extWithDot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if enableadmin, err := GetConfig("bool", "EnableAdmin"); err == nil {
|
||||
EnableAdmin = enableadmin.(bool)
|
||||
}
|
||||
|
||||
if adminhttpaddr, _ := GetConfig("string", "AdminHttpAddr"); adminhttpaddr != "" {
|
||||
AdminHttpAddr = adminhttpaddr.(string)
|
||||
}
|
||||
|
||||
if adminhttpport, err := GetConfig("int", "AdminHttpPort"); err == nil {
|
||||
AdminHttpPort = adminhttpport.(int)
|
||||
}
|
||||
|
||||
if enabledocs, err := GetConfig("bool", "EnableDocs"); err == nil {
|
||||
EnableDocs = enabledocs.(bool)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Getconfig throw the Runmode
|
||||
// [dev]
|
||||
// name = astaixe
|
||||
// IsEnable = false
|
||||
// [prod]
|
||||
// name = slene
|
||||
// IsEnable = true
|
||||
//
|
||||
// usage:
|
||||
// GetConfig("string", "name")
|
||||
// GetConfig("bool", "IsEnable")
|
||||
func GetConfig(typ, key string) (interface{}, error) {
|
||||
switch typ {
|
||||
case "string":
|
||||
v := AppConfig.String(RunMode + "::" + key)
|
||||
if v == "" {
|
||||
v = AppConfig.String(key)
|
||||
}
|
||||
return v, nil
|
||||
case "strings":
|
||||
v := AppConfig.Strings(RunMode + "::" + key)
|
||||
if len(v) == 0 {
|
||||
v = AppConfig.Strings(key)
|
||||
}
|
||||
return v, nil
|
||||
case "int":
|
||||
v, err := AppConfig.Int(RunMode + "::" + key)
|
||||
if err != nil || v == 0 {
|
||||
return AppConfig.Int(key)
|
||||
}
|
||||
return v, nil
|
||||
case "bool":
|
||||
v, err := AppConfig.Bool(RunMode + "::" + key)
|
||||
if err != nil {
|
||||
return AppConfig.Bool(key)
|
||||
}
|
||||
return v, nil
|
||||
case "int64":
|
||||
v, err := AppConfig.Int64(RunMode + "::" + key)
|
||||
if err != nil || v == 0 {
|
||||
return AppConfig.Int64(key)
|
||||
}
|
||||
return v, nil
|
||||
case "float":
|
||||
v, err := AppConfig.Float(RunMode + "::" + key)
|
||||
if err != nil || v == 0 {
|
||||
return AppConfig.Float(key)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
return "", errors.New("not support type")
|
||||
}
|
||||
|
107
config/config.go
Normal file
@ -0,0 +1,107 @@
|
||||
// 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.
|
||||
|
||||
// Usage:
|
||||
// import(
|
||||
// "github.com/astaxie/beego/config"
|
||||
// )
|
||||
//
|
||||
// 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 (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ConfigContainer defines how to get and set value from configuration raw data.
|
||||
type ConfigContainer 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 ConfigContainer.
|
||||
type Config interface {
|
||||
Parse(key string) (ConfigContainer, error)
|
||||
ParseData(data []byte) (ConfigContainer, 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) {
|
||||
if adapter == nil {
|
||||
panic("config: Register adapter is nil")
|
||||
}
|
||||
if _, ok := adapters[name]; ok {
|
||||
panic("config: Register called twice for adapter " + name)
|
||||
}
|
||||
adapters[name] = adapter
|
||||
}
|
||||
|
||||
// adapterName is ini/json/xml/yaml.
|
||||
// filename is the config file path.
|
||||
func NewConfig(adapterName, fileaname string) (ConfigContainer, error) {
|
||||
adapter, ok := adapters[adapterName]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("config: unknown adaptername %q (forgotten import?)", adapterName)
|
||||
}
|
||||
return adapter.Parse(fileaname)
|
||||
}
|
||||
|
||||
// adapterName is ini/json/xml/yaml.
|
||||
// data is the config data.
|
||||
func NewConfigData(adapterName string, data []byte) (ConfigContainer, error) {
|
||||
adapter, ok := adapters[adapterName]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("config: unknown adaptername %q (forgotten import?)", adapterName)
|
||||
}
|
||||
return adapter.ParseData(data)
|
||||
}
|
129
config/fake.go
Normal 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 config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type fakeConfigContainer struct {
|
||||
data map[string]string
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) getData(key string) string {
|
||||
return c.data[strings.ToLower(key)]
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Set(key, val string) error {
|
||||
c.data[strings.ToLower(key)] = val
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) String(key string) string {
|
||||
return c.getData(key)
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.getData(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Strings(key string) []string {
|
||||
return strings.Split(c.getData(key), ";")
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.getData(key))
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Int64(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.getData(key), 10, 64)
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.getData(key))
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.getData(key), 64)
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) DIY(key string) (interface{}, error) {
|
||||
if v, ok := c.data[strings.ToLower(key)]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, errors.New("key not find")
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
return nil, errors.New("not implement in the fakeConfigContainer")
|
||||
}
|
||||
|
||||
func (c *fakeConfigContainer) SaveConfigFile(filename string) error {
|
||||
return errors.New("not implement in the fakeConfigContainer")
|
||||
}
|
||||
|
||||
var _ ConfigContainer = new(fakeConfigContainer)
|
||||
|
||||
func NewFakeConfig() ConfigContainer {
|
||||
return &fakeConfigContainer{
|
||||
data: make(map[string]string),
|
||||
}
|
||||
}
|
367
config/ini.go
Normal file
@ -0,0 +1,367 @@
|
||||
// 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 (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var (
|
||||
DEFAULT_SECTION = "default" // default section means if some ini items not in a section, make them in default section,
|
||||
bNumComment = []byte{'#'} // number signal
|
||||
bSemComment = []byte{';'} // semicolon signal
|
||||
bEmpty = []byte{}
|
||||
bEqual = []byte{'='} // equal signal
|
||||
bDQuote = []byte{'"'} // quote signal
|
||||
sectionStart = []byte{'['} // section start signal
|
||||
sectionEnd = []byte{']'} // section end signal
|
||||
lineBreak = "\n"
|
||||
)
|
||||
|
||||
// IniConfig implements Config to parse ini file.
|
||||
type IniConfig struct {
|
||||
}
|
||||
|
||||
// ParseFile creates a new Config and parses the file configuration from the named file.
|
||||
func (ini *IniConfig) Parse(name string) (ConfigContainer, error) {
|
||||
file, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &IniConfigContainer{
|
||||
file.Name(),
|
||||
make(map[string]map[string]string),
|
||||
make(map[string]string),
|
||||
make(map[string]string),
|
||||
sync.RWMutex{},
|
||||
}
|
||||
cfg.Lock()
|
||||
defer cfg.Unlock()
|
||||
defer file.Close()
|
||||
|
||||
var comment bytes.Buffer
|
||||
buf := bufio.NewReader(file)
|
||||
section := DEFAULT_SECTION
|
||||
for {
|
||||
line, _, err := buf.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if bytes.Equal(line, bEmpty) {
|
||||
continue
|
||||
}
|
||||
line = bytes.TrimSpace(line)
|
||||
|
||||
var bComment []byte
|
||||
switch {
|
||||
case bytes.HasPrefix(line, bNumComment):
|
||||
bComment = bNumComment
|
||||
case bytes.HasPrefix(line, bSemComment):
|
||||
bComment = bSemComment
|
||||
}
|
||||
if bComment != nil {
|
||||
line = bytes.TrimLeft(line, string(bComment))
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
comment.Write(line)
|
||||
comment.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
if bytes.HasPrefix(line, sectionStart) && bytes.HasSuffix(line, sectionEnd) {
|
||||
section = strings.ToLower(string(line[1 : len(line)-1])) // section name case insensitive
|
||||
if comment.Len() > 0 {
|
||||
cfg.sectionComment[section] = comment.String()
|
||||
comment.Reset()
|
||||
}
|
||||
if _, ok := cfg.data[section]; !ok {
|
||||
cfg.data[section] = make(map[string]string)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if _, ok := cfg.data[section]; !ok {
|
||||
cfg.data[section] = make(map[string]string)
|
||||
}
|
||||
keyValue := bytes.SplitN(line, bEqual, 2)
|
||||
val := bytes.TrimSpace(keyValue[1])
|
||||
if bytes.HasPrefix(val, bDQuote) {
|
||||
val = bytes.Trim(val, `"`)
|
||||
}
|
||||
|
||||
key := string(bytes.TrimSpace(keyValue[0])) // key name case insensitive
|
||||
key = strings.ToLower(key)
|
||||
cfg.data[section][key] = string(val)
|
||||
if comment.Len() > 0 {
|
||||
cfg.keyComment[section+"."+key] = comment.String()
|
||||
comment.Reset()
|
||||
}
|
||||
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (ini *IniConfig) ParseData(data []byte) (ConfigContainer, error) {
|
||||
// Save memory data to temporary file
|
||||
tmpName := path.Join(os.TempDir(), "beego", fmt.Sprintf("%d", time.Now().Nanosecond()))
|
||||
os.MkdirAll(path.Dir(tmpName), os.ModePerm)
|
||||
if err := ioutil.WriteFile(tmpName, data, 0655); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ini.Parse(tmpName)
|
||||
}
|
||||
|
||||
// A Config represents the ini configuration.
|
||||
// When set and get value, support key as section:name type.
|
||||
type IniConfigContainer struct {
|
||||
filename string
|
||||
data map[string]map[string]string // section=> key:val
|
||||
sectionComment map[string]string // section : comment
|
||||
keyComment map[string]string // id: []{comment, key...}; id 1 is for main comment.
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *IniConfigContainer) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.getdata(key))
|
||||
}
|
||||
|
||||
// DefaultBool returns the boolean value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *IniConfigContainer) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.getdata(key))
|
||||
}
|
||||
|
||||
// DefaultInt returns the integer value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int64 returns the int64 value for a given key.
|
||||
func (c *IniConfigContainer) Int64(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.getdata(key), 10, 64)
|
||||
}
|
||||
|
||||
// DefaultInt64 returns the int64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *IniConfigContainer) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.getdata(key), 64)
|
||||
}
|
||||
|
||||
// DefaultFloat returns the float64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *IniConfigContainer) String(key string) string {
|
||||
return c.getdata(key)
|
||||
}
|
||||
|
||||
// DefaultString returns the string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.String(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns the []string value for a given key.
|
||||
func (c *IniConfigContainer) Strings(key string) []string {
|
||||
return strings.Split(c.String(key), ";")
|
||||
}
|
||||
|
||||
// DefaultStrings returns the []string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *IniConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// GetSection returns map for the given section
|
||||
func (c *IniConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
if v, ok := c.data[section]; ok {
|
||||
return v, nil
|
||||
} else {
|
||||
return nil, errors.New("not exist setction")
|
||||
}
|
||||
}
|
||||
|
||||
// SaveConfigFile save the config into file
|
||||
func (c *IniConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
// Write configuration file by filename.
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
for section, dt := range c.data {
|
||||
// Write section comments.
|
||||
if v, ok := c.sectionComment[section]; ok {
|
||||
if _, err = buf.WriteString(string(bNumComment) + v + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if section != DEFAULT_SECTION {
|
||||
// Write section name.
|
||||
if _, err = buf.WriteString(string(sectionStart) + section + string(sectionEnd) + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for key, val := range dt {
|
||||
if key != " " {
|
||||
// Write key comments.
|
||||
if v, ok := c.keyComment[key]; ok {
|
||||
if _, err = buf.WriteString(string(bNumComment) + v + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Write key and value.
|
||||
if _, err = buf.WriteString(key + string(bEqual) + val + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Put a line between sections.
|
||||
if _, err = buf.WriteString(lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = buf.WriteTo(f); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
// if write to one section, the key need be "section::key".
|
||||
// if the section is not existed, it panics.
|
||||
func (c *IniConfigContainer) Set(key, value string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if len(key) == 0 {
|
||||
return errors.New("key is empty")
|
||||
}
|
||||
|
||||
var (
|
||||
section, k string
|
||||
sectionKey []string = strings.Split(key, "::")
|
||||
)
|
||||
|
||||
if len(sectionKey) >= 2 {
|
||||
section = sectionKey[0]
|
||||
k = sectionKey[1]
|
||||
} else {
|
||||
section = DEFAULT_SECTION
|
||||
k = sectionKey[0]
|
||||
}
|
||||
|
||||
if _, ok := c.data[section]; !ok {
|
||||
c.data[section] = make(map[string]string)
|
||||
}
|
||||
c.data[section][k] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// DIY returns the raw value by a given key.
|
||||
func (c *IniConfigContainer) DIY(key string) (v interface{}, err error) {
|
||||
if v, ok := c.data[strings.ToLower(key)]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return v, errors.New("key not find")
|
||||
}
|
||||
|
||||
// section.key or key
|
||||
func (c *IniConfigContainer) getdata(key string) string {
|
||||
if len(key) == 0 {
|
||||
return ""
|
||||
}
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
|
||||
var (
|
||||
section, k string
|
||||
sectionKey []string = strings.Split(strings.ToLower(key), "::")
|
||||
)
|
||||
if len(sectionKey) >= 2 {
|
||||
section = sectionKey[0]
|
||||
k = sectionKey[1]
|
||||
} else {
|
||||
section = DEFAULT_SECTION
|
||||
k = sectionKey[0]
|
||||
}
|
||||
if v, ok := c.data[section]; ok {
|
||||
if vv, ok := v[k]; ok {
|
||||
return vv
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("ini", &IniConfig{})
|
||||
}
|
103
config/ini_test.go
Normal file
@ -0,0 +1,103 @@
|
||||
// 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 (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var inicontext = `
|
||||
;comment one
|
||||
#comment two
|
||||
appname = beeapi
|
||||
httpport = 8080
|
||||
mysqlport = 3600
|
||||
PI = 3.1415976
|
||||
runmode = "dev"
|
||||
autorender = false
|
||||
copyrequestbody = true
|
||||
[demo]
|
||||
key1="asta"
|
||||
key2 = "xie"
|
||||
CaseInsensitive = true
|
||||
peers = one;two;three
|
||||
`
|
||||
|
||||
func TestIni(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
if iniconf.String("appname") != "beeapi" {
|
||||
t.Fatal("appname not equal to beeapi")
|
||||
}
|
||||
if port, err := iniconf.Int("httpport"); err != nil || port != 8080 {
|
||||
t.Error(port)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if port, err := iniconf.Int64("mysqlport"); err != nil || port != 3600 {
|
||||
t.Error(port)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pi, err := iniconf.Float("PI"); err != nil || pi != 3.1415976 {
|
||||
t.Error(pi)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if iniconf.String("runmode") != "dev" {
|
||||
t.Fatal("runmode not equal to dev")
|
||||
}
|
||||
if v, err := iniconf.Bool("autorender"); err != nil || v != false {
|
||||
t.Error(v)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, err := iniconf.Bool("copyrequestbody"); err != nil || v != true {
|
||||
t.Error(v)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = iniconf.Set("name", "astaxie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if iniconf.String("name") != "astaxie" {
|
||||
t.Fatal("get name error")
|
||||
}
|
||||
if iniconf.String("demo::key1") != "asta" {
|
||||
t.Fatal("get demo.key1 error")
|
||||
}
|
||||
if iniconf.String("demo::key2") != "xie" {
|
||||
t.Fatal("get demo.key2 error")
|
||||
}
|
||||
if v, err := iniconf.Bool("demo::caseinsensitive"); err != nil || v != true {
|
||||
t.Fatal("get demo.caseinsensitive error")
|
||||
}
|
||||
|
||||
if data := iniconf.Strings("demo::peers"); len(data) != 3 {
|
||||
t.Fatal("get strings error", data)
|
||||
} else if data[0] != "one" {
|
||||
t.Fatal("get first params error not equat to one")
|
||||
}
|
||||
|
||||
}
|
272
config/json.go
Normal file
@ -0,0 +1,272 @@
|
||||
// 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 (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// JsonConfig is a json config parser and implements Config interface.
|
||||
type JsonConfig struct {
|
||||
}
|
||||
|
||||
// Parse returns a ConfigContainer with parsed json config map.
|
||||
func (js *JsonConfig) Parse(filename string) (ConfigContainer, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
content, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &JsonConfigContainer{
|
||||
data: make(map[string]interface{}),
|
||||
}
|
||||
err = json.Unmarshal(content, &x.data)
|
||||
if err != nil {
|
||||
var wrappingArray []interface{}
|
||||
err2 := json.Unmarshal(content, &wrappingArray)
|
||||
if err2 != nil {
|
||||
return nil, err
|
||||
}
|
||||
x.data["rootArray"] = wrappingArray
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
func (js *JsonConfig) ParseData(data []byte) (ConfigContainer, error) {
|
||||
// Save memory data to temporary file
|
||||
tmpName := path.Join(os.TempDir(), "beego", fmt.Sprintf("%d", time.Now().Nanosecond()))
|
||||
os.MkdirAll(path.Dir(tmpName), os.ModePerm)
|
||||
if err := ioutil.WriteFile(tmpName, data, 0655); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return js.Parse(tmpName)
|
||||
}
|
||||
|
||||
// A Config represents the json configuration.
|
||||
// Only when get value, support key as section:name type.
|
||||
type JsonConfigContainer struct {
|
||||
data map[string]interface{}
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *JsonConfigContainer) Bool(key string) (bool, error) {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
if v, ok := val.(bool); ok {
|
||||
return v, nil
|
||||
}
|
||||
return false, errors.New("not bool value")
|
||||
}
|
||||
return false, errors.New("not exist key:" + key)
|
||||
}
|
||||
|
||||
// DefaultBool return the bool value if has no error
|
||||
// otherwise return the defaultval
|
||||
func (c *JsonConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *JsonConfigContainer) Int(key string) (int, error) {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
if v, ok := val.(float64); ok {
|
||||
return int(v), nil
|
||||
}
|
||||
return 0, errors.New("not int value")
|
||||
}
|
||||
return 0, errors.New("not exist key:" + key)
|
||||
}
|
||||
|
||||
// DefaultInt returns the integer value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int64 returns the int64 value for a given key.
|
||||
func (c *JsonConfigContainer) Int64(key string) (int64, error) {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
if v, ok := val.(float64); ok {
|
||||
return int64(v), nil
|
||||
}
|
||||
return 0, errors.New("not int64 value")
|
||||
}
|
||||
return 0, errors.New("not exist key:" + key)
|
||||
}
|
||||
|
||||
// DefaultInt64 returns the int64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *JsonConfigContainer) Float(key string) (float64, error) {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
if v, ok := val.(float64); ok {
|
||||
return v, nil
|
||||
}
|
||||
return 0.0, errors.New("not float64 value")
|
||||
}
|
||||
return 0.0, errors.New("not exist key:" + key)
|
||||
}
|
||||
|
||||
// DefaultFloat returns the float64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *JsonConfigContainer) String(key string) string {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
if v, ok := val.(string); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// DefaultString returns the string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.String(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns the []string value for a given key.
|
||||
func (c *JsonConfigContainer) Strings(key string) []string {
|
||||
return strings.Split(c.String(key), ";")
|
||||
}
|
||||
|
||||
// DefaultStrings returns the []string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// GetSection returns map for the given section
|
||||
func (c *JsonConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
if v, ok := c.data[section]; ok {
|
||||
return v.(map[string]string), nil
|
||||
} else {
|
||||
return nil, errors.New("not exist setction")
|
||||
}
|
||||
}
|
||||
|
||||
// SaveConfigFile save the config into file
|
||||
func (c *JsonConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
// Write configuration file by filename.
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := json.MarshalIndent(c.data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
func (c *JsonConfigContainer) Set(key, val string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.data[key] = val
|
||||
return nil
|
||||
}
|
||||
|
||||
// DIY returns the raw value by a given key.
|
||||
func (c *JsonConfigContainer) DIY(key string) (v interface{}, err error) {
|
||||
val := c.getData(key)
|
||||
if val != nil {
|
||||
return val, nil
|
||||
}
|
||||
return nil, errors.New("not exist key")
|
||||
}
|
||||
|
||||
// section.key or key
|
||||
func (c *JsonConfigContainer) getData(key string) interface{} {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
if len(key) == 0 {
|
||||
return nil
|
||||
}
|
||||
sectionKey := strings.Split(key, "::")
|
||||
if len(sectionKey) >= 2 {
|
||||
curValue, ok := c.data[sectionKey[0]]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, key := range sectionKey[1:] {
|
||||
if v, ok := curValue.(map[string]interface{}); ok {
|
||||
if curValue, ok = v[key]; !ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return curValue
|
||||
}
|
||||
if v, ok := c.data[key]; ok {
|
||||
return v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("json", &JsonConfig{})
|
||||
}
|
182
config/json_test.go
Normal file
@ -0,0 +1,182 @@
|
||||
// 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 (
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
var jsoncontextwitharray = `[
|
||||
{
|
||||
"url": "user",
|
||||
"serviceAPI": "http://www.test.com/user"
|
||||
},
|
||||
{
|
||||
"url": "employee",
|
||||
"serviceAPI": "http://www.test.com/employee"
|
||||
}
|
||||
]`
|
||||
|
||||
func TestJsonStartsWithArray(t *testing.T) {
|
||||
f, err := os.Create("testjsonWithArray.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = f.WriteString(jsoncontextwitharray)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
defer os.Remove("testjsonWithArray.conf")
|
||||
jsonconf, err := NewConfig("json", "testjsonWithArray.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rootArray, err := jsonconf.DIY("rootArray")
|
||||
if err != nil {
|
||||
t.Error("array does not exist as element")
|
||||
}
|
||||
rootArrayCasted := rootArray.([]interface{})
|
||||
if rootArrayCasted == nil {
|
||||
t.Error("array from root is nil")
|
||||
} else {
|
||||
elem := rootArrayCasted[0].(map[string]interface{})
|
||||
if elem["url"] != "user" || elem["serviceAPI"] != "http://www.test.com/user" {
|
||||
t.Error("array[0] values are not valid")
|
||||
}
|
||||
|
||||
elem2 := rootArrayCasted[1].(map[string]interface{})
|
||||
if elem2["url"] != "employee" || elem2["serviceAPI"] != "http://www.test.com/employee" {
|
||||
t.Error("array[1] values are not valid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJson(t *testing.T) {
|
||||
f, err := os.Create("testjson.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = f.WriteString(jsoncontext)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
defer os.Remove("testjson.conf")
|
||||
jsonconf, err := NewConfig("json", "testjson.conf")
|
||||
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)
|
||||
}
|
||||
if err = jsonconf.Set("name", "astaxie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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 {
|
||||
t.Log(db)
|
||||
t.Fatal("db not map[string]interface{}")
|
||||
} else {
|
||||
if m["host"].(string) != "host" {
|
||||
t.Fatal("get host err")
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := jsonconf.Int("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting an Int")
|
||||
}
|
||||
|
||||
if _, err := jsonconf.Int64("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting an Int64")
|
||||
}
|
||||
|
||||
if _, err := jsonconf.Float("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting a Float")
|
||||
}
|
||||
|
||||
if _, err := jsonconf.DIY("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting an interface{}")
|
||||
}
|
||||
|
||||
if val := jsonconf.String("unknown"); val != "" {
|
||||
t.Error("unknown keys should return an empty string when expecting a String")
|
||||
}
|
||||
|
||||
if _, err := jsonconf.Bool("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting a Bool")
|
||||
}
|
||||
}
|
228
config/xml/xml.go
Normal file
@ -0,0 +1,228 @@
|
||||
// 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 (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/config"
|
||||
"github.com/beego/x2j"
|
||||
)
|
||||
|
||||
// XmlConfig is a xml config parser and implements Config interface.
|
||||
// xml configurations should be included in <config></config> tag.
|
||||
// only support key/value pair as <key>value</key> as each item.
|
||||
type XMLConfig struct{}
|
||||
|
||||
// Parse returns a ConfigContainer with parsed xml config map.
|
||||
func (xc *XMLConfig) Parse(filename string) (config.ConfigContainer, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
x := &XMLConfigContainer{data: make(map[string]interface{})}
|
||||
content, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d, err := x2j.DocToMap(string(content))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
x.data = d["config"].(map[string]interface{})
|
||||
return x, nil
|
||||
}
|
||||
|
||||
func (x *XMLConfig) ParseData(data []byte) (config.ConfigContainer, error) {
|
||||
// Save memory data to temporary file
|
||||
tmpName := path.Join(os.TempDir(), "beego", fmt.Sprintf("%d", time.Now().Nanosecond()))
|
||||
os.MkdirAll(path.Dir(tmpName), os.ModePerm)
|
||||
if err := ioutil.WriteFile(tmpName, data, 0655); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x.Parse(tmpName)
|
||||
}
|
||||
|
||||
// A Config represents the xml configuration.
|
||||
type XMLConfigContainer struct {
|
||||
data map[string]interface{}
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *XMLConfigContainer) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.data[key].(string))
|
||||
}
|
||||
|
||||
// DefaultBool return the bool value if has no error
|
||||
// otherwise return the defaultval
|
||||
func (c *XMLConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *XMLConfigContainer) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.data[key].(string))
|
||||
}
|
||||
|
||||
// DefaultInt returns the integer value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *XMLConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int64 returns the int64 value for a given key.
|
||||
func (c *XMLConfigContainer) Int64(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.data[key].(string), 10, 64)
|
||||
}
|
||||
|
||||
// DefaultInt64 returns the int64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *XMLConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *XMLConfigContainer) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.data[key].(string), 64)
|
||||
}
|
||||
|
||||
// DefaultFloat returns the float64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *XMLConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *XMLConfigContainer) String(key string) string {
|
||||
if v, ok := c.data[key].(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// DefaultString returns the string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *XMLConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.String(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns the []string value for a given key.
|
||||
func (c *XMLConfigContainer) Strings(key string) []string {
|
||||
return strings.Split(c.String(key), ";")
|
||||
}
|
||||
|
||||
// DefaultStrings returns the []string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *XMLConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// GetSection returns map for the given section
|
||||
func (c *XMLConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
if v, ok := c.data[section]; ok {
|
||||
return v.(map[string]string), nil
|
||||
} else {
|
||||
return nil, errors.New("not exist setction")
|
||||
}
|
||||
}
|
||||
|
||||
// SaveConfigFile save the config into file
|
||||
func (c *XMLConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
// Write configuration file by filename.
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := xml.MarshalIndent(c.data, " ", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
func (c *XMLConfigContainer) Set(key, val string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.data[key] = val
|
||||
return nil
|
||||
}
|
||||
|
||||
// DIY returns the raw value by a given key.
|
||||
func (c *XMLConfigContainer) DIY(key string) (v interface{}, err error) {
|
||||
if v, ok := c.data[key]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, errors.New("not exist key")
|
||||
}
|
||||
|
||||
func init() {
|
||||
config.Register("xml", &XMLConfig{})
|
||||
}
|
85
config/xml/xml_test.go
Normal file
@ -0,0 +1,85 @@
|
||||
// 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 (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/astaxie/beego/config"
|
||||
)
|
||||
|
||||
//xml parse should incluce in <config></config> tags
|
||||
var 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>
|
||||
</config>
|
||||
`
|
||||
|
||||
func TestXML(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
if xmlconf.String("appname") != "beeapi" {
|
||||
t.Fatal("appname not equal to beeapi")
|
||||
}
|
||||
if port, err := xmlconf.Int("httpport"); err != nil || port != 8080 {
|
||||
t.Error(port)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if port, err := xmlconf.Int64("mysqlport"); err != nil || port != 3600 {
|
||||
t.Error(port)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pi, err := xmlconf.Float("PI"); err != nil || pi != 3.1415976 {
|
||||
t.Error(pi)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if xmlconf.String("runmode") != "dev" {
|
||||
t.Fatal("runmode not equal to dev")
|
||||
}
|
||||
if v, err := xmlconf.Bool("autorender"); err != nil || v != false {
|
||||
t.Error(v)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, err := xmlconf.Bool("copyrequestbody"); err != nil || v != true {
|
||||
t.Error(v)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = xmlconf.Set("name", "astaxie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if xmlconf.String("name") != "astaxie" {
|
||||
t.Fatal("get name error")
|
||||
}
|
||||
}
|
265
config/yaml/yaml.go
Normal file
@ -0,0 +1,265 @@
|
||||
// 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 (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/config"
|
||||
"github.com/beego/goyaml2"
|
||||
)
|
||||
|
||||
// YAMLConfig is a yaml config parser and implements Config interface.
|
||||
type YAMLConfig struct{}
|
||||
|
||||
// Parse returns a ConfigContainer with parsed yaml config map.
|
||||
func (yaml *YAMLConfig) Parse(filename string) (y config.ConfigContainer, err error) {
|
||||
cnf, err := ReadYmlReader(filename)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
y = &YAMLConfigContainer{
|
||||
data: cnf,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (yaml *YAMLConfig) ParseData(data []byte) (config.ConfigContainer, error) {
|
||||
// Save memory data to temporary file
|
||||
tmpName := path.Join(os.TempDir(), "beego", fmt.Sprintf("%d", time.Now().Nanosecond()))
|
||||
os.MkdirAll(path.Dir(tmpName), os.ModePerm)
|
||||
if err := ioutil.WriteFile(tmpName, data, 0655); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return yaml.Parse(tmpName)
|
||||
}
|
||||
|
||||
// Read yaml file to map.
|
||||
// if json like, use json package, unless goyaml2 package.
|
||||
func ReadYmlReader(path string) (cnf map[string]interface{}, err error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
buf, err := ioutil.ReadAll(f)
|
||||
if err != nil || len(buf) < 3 {
|
||||
return
|
||||
}
|
||||
|
||||
if string(buf[0:1]) == "{" {
|
||||
log.Println("Look like a Json, try json umarshal")
|
||||
err = json.Unmarshal(buf, &cnf)
|
||||
if err == nil {
|
||||
log.Println("It is Json Map")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
data, err := goyaml2.Read(bytes.NewBuffer(buf))
|
||||
if err != nil {
|
||||
log.Println("Goyaml2 ERR>", string(buf), err)
|
||||
return
|
||||
}
|
||||
|
||||
if data == nil {
|
||||
log.Println("Goyaml2 output nil? Pls report bug\n" + string(buf))
|
||||
return
|
||||
}
|
||||
cnf, ok := data.(map[string]interface{})
|
||||
if !ok {
|
||||
log.Println("Not a Map? >> ", string(buf), data)
|
||||
cnf = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// A Config represents the yaml configuration.
|
||||
type YAMLConfigContainer struct {
|
||||
data map[string]interface{}
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *YAMLConfigContainer) Bool(key string) (bool, error) {
|
||||
if v, ok := c.data[key].(bool); ok {
|
||||
return v, nil
|
||||
}
|
||||
return false, errors.New("not bool value")
|
||||
}
|
||||
|
||||
// DefaultBool return the bool value if has no error
|
||||
// otherwise return the defaultval
|
||||
func (c *YAMLConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *YAMLConfigContainer) Int(key string) (int, error) {
|
||||
if v, ok := c.data[key].(int64); ok {
|
||||
return int(v), nil
|
||||
}
|
||||
return 0, errors.New("not int value")
|
||||
}
|
||||
|
||||
// DefaultInt returns the integer value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *YAMLConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Int64 returns the int64 value for a given key.
|
||||
func (c *YAMLConfigContainer) Int64(key string) (int64, error) {
|
||||
if v, ok := c.data[key].(int64); ok {
|
||||
return v, nil
|
||||
}
|
||||
return 0, errors.New("not bool value")
|
||||
}
|
||||
|
||||
// DefaultInt64 returns the int64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *YAMLConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *YAMLConfigContainer) Float(key string) (float64, error) {
|
||||
if v, ok := c.data[key].(float64); ok {
|
||||
return v, nil
|
||||
}
|
||||
return 0.0, errors.New("not float64 value")
|
||||
}
|
||||
|
||||
// DefaultFloat returns the float64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *YAMLConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *YAMLConfigContainer) String(key string) string {
|
||||
if v, ok := c.data[key].(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// DefaultString returns the string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *YAMLConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.String(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns the []string value for a given key.
|
||||
func (c *YAMLConfigContainer) Strings(key string) []string {
|
||||
return strings.Split(c.String(key), ";")
|
||||
}
|
||||
|
||||
// DefaultStrings returns the []string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *YAMLConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// GetSection returns map for the given section
|
||||
func (c *YAMLConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
if v, ok := c.data[section]; ok {
|
||||
return v.(map[string]string), nil
|
||||
} else {
|
||||
return nil, errors.New("not exist setction")
|
||||
}
|
||||
}
|
||||
|
||||
// SaveConfigFile save the config into file
|
||||
func (c *YAMLConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
// Write configuration file by filename.
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
err = goyaml2.Write(f, c.data)
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
func (c *YAMLConfigContainer) Set(key, val string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.data[key] = val
|
||||
return nil
|
||||
}
|
||||
|
||||
// DIY returns the raw value by a given key.
|
||||
func (c *YAMLConfigContainer) DIY(key string) (v interface{}, err error) {
|
||||
if v, ok := c.data[key]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, errors.New("not exist key")
|
||||
}
|
||||
|
||||
func init() {
|
||||
config.Register("yaml", &YAMLConfig{})
|
||||
}
|
82
config/yaml/yaml_test.go
Normal file
@ -0,0 +1,82 @@
|
||||
// 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
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/astaxie/beego/config"
|
||||
)
|
||||
|
||||
var yamlcontext = `
|
||||
"appname": beeapi
|
||||
"httpport": 8080
|
||||
"mysqlport": 3600
|
||||
"PI": 3.1415976
|
||||
"runmode": dev
|
||||
"autorender": false
|
||||
"copyrequestbody": true
|
||||
`
|
||||
|
||||
func TestYaml(t *testing.T) {
|
||||
f, err := os.Create("testyaml.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = f.WriteString(yamlcontext)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
defer os.Remove("testyaml.conf")
|
||||
yamlconf, err := config.NewConfig("yaml", "testyaml.conf")
|
||||
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)
|
||||
}
|
||||
if err = yamlconf.Set("name", "astaxie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if yamlconf.String("name") != "astaxie" {
|
||||
t.Fatal("get name error")
|
||||
}
|
||||
}
|
29
config_test.go
Normal file
@ -0,0 +1,29 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
if FlashName != "BEEGO_FLASH" {
|
||||
t.Errorf("FlashName was not set to default.")
|
||||
}
|
||||
|
||||
if FlashSeperator != "BEEGOFLASH" {
|
||||
t.Errorf("FlashName was not set to default.")
|
||||
}
|
||||
}
|
119
context.go
@ -1,119 +0,0 @@
|
||||
package beego
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
ResponseWriter http.ResponseWriter
|
||||
Request *http.Request
|
||||
RequestBody []byte
|
||||
Params map[string]string
|
||||
}
|
||||
|
||||
func (ctx *Context) WriteString(content string) {
|
||||
ctx.ResponseWriter.Write([]byte(content))
|
||||
}
|
||||
|
||||
func (ctx *Context) Abort(status int, body string) {
|
||||
ctx.ResponseWriter.WriteHeader(status)
|
||||
ctx.ResponseWriter.Write([]byte(body))
|
||||
}
|
||||
|
||||
func (ctx *Context) Redirect(status int, url_ string) {
|
||||
ctx.ResponseWriter.Header().Set("Location", url_)
|
||||
ctx.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (ctx *Context) NotModified() {
|
||||
ctx.ResponseWriter.WriteHeader(304)
|
||||
}
|
||||
|
||||
func (ctx *Context) NotFound(message string) {
|
||||
ctx.ResponseWriter.WriteHeader(404)
|
||||
ctx.ResponseWriter.Write([]byte(message))
|
||||
}
|
||||
|
||||
//Sets the content type by extension, as defined in the mime package.
|
||||
//For example, ctx.ContentType("json") sets the content-type to "application/json"
|
||||
func (ctx *Context) ContentType(ext string) {
|
||||
if !strings.HasPrefix(ext, ".") {
|
||||
ext = "." + ext
|
||||
}
|
||||
ctype := mime.TypeByExtension(ext)
|
||||
if ctype != "" {
|
||||
ctx.ResponseWriter.Header().Set("Content-Type", ctype)
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx *Context) SetHeader(hdr string, val string, unique bool) {
|
||||
if unique {
|
||||
ctx.ResponseWriter.Header().Set(hdr, val)
|
||||
} else {
|
||||
ctx.ResponseWriter.Header().Add(hdr, val)
|
||||
}
|
||||
}
|
||||
|
||||
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever
|
||||
|
||||
//params:
|
||||
//string name
|
||||
//string value
|
||||
//int64 expire = 0
|
||||
//string $path
|
||||
//string $domain
|
||||
//bool $secure = false
|
||||
//bool $httponly = false
|
||||
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
|
||||
if len(others) > 0 {
|
||||
switch others[0].(type) {
|
||||
case int:
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", others[0].(int))
|
||||
case int64:
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", others[0].(int64))
|
||||
case int32:
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", others[0].(int32))
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
if len(others) > 1 {
|
||||
fmt.Fprintf(&b, "; Path=%s", sanitizeValue(others[1].(string)))
|
||||
}
|
||||
if len(others) > 2 {
|
||||
fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(others[2].(string)))
|
||||
}
|
||||
if len(others) > 3 {
|
||||
fmt.Fprintf(&b, "; Secure")
|
||||
}
|
||||
if len(others) > 4 {
|
||||
fmt.Fprintf(&b, "; HttpOnly")
|
||||
}
|
||||
ctx.SetHeader("Set-Cookie", b.String(), false)
|
||||
}
|
||||
|
||||
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
|
||||
|
||||
func sanitizeName(n string) string {
|
||||
return cookieNameSanitizer.Replace(n)
|
||||
}
|
||||
|
||||
var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ")
|
||||
|
||||
func sanitizeValue(v string) string {
|
||||
return cookieValueSanitizer.Replace(v)
|
||||
}
|
||||
|
||||
func (ctx *Context) GetCookie(key string) string {
|
||||
keycookie, err := ctx.Request.Cookie(key)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return keycookie.Value
|
||||
}
|
161
context/context.go
Normal file
@ -0,0 +1,161 @@
|
||||
// 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.
|
||||
|
||||
// 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 (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
// 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 struct {
|
||||
Input *BeegoInput
|
||||
Output *BeegoOutput
|
||||
Request *http.Request
|
||||
ResponseWriter http.ResponseWriter
|
||||
_xsrf_token string
|
||||
}
|
||||
|
||||
// Redirect does redirection to localurl with http header status code.
|
||||
// It sends http response header directly.
|
||||
func (ctx *Context) Redirect(status int, localurl string) {
|
||||
ctx.Output.Header("Location", localurl)
|
||||
ctx.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
// Abort stops this request.
|
||||
// if middleware.ErrorMaps exists, panic body.
|
||||
// if middleware.HTTPExceptionMaps exists, panic HTTPException struct with status and body string.
|
||||
func (ctx *Context) Abort(status int, body string) {
|
||||
ctx.ResponseWriter.WriteHeader(status)
|
||||
// first panic from ErrorMaps, is is user defined error functions.
|
||||
if _, ok := middleware.ErrorMaps[body]; ok {
|
||||
panic(body)
|
||||
}
|
||||
// second panic from HTTPExceptionMaps, it is system defined functions.
|
||||
if e, ok := middleware.HTTPExceptionMaps[status]; ok {
|
||||
if len(body) >= 1 {
|
||||
e.Description = body
|
||||
}
|
||||
panic(e)
|
||||
}
|
||||
// last panic user string
|
||||
panic(body)
|
||||
}
|
||||
|
||||
// Write string to response body.
|
||||
// it sends response body.
|
||||
func (ctx *Context) WriteString(content string) {
|
||||
ctx.ResponseWriter.Write([]byte(content))
|
||||
}
|
||||
|
||||
// Get cookie from request by a given key.
|
||||
// It's alias of BeegoInput.Cookie.
|
||||
func (ctx *Context) GetCookie(key string) string {
|
||||
return ctx.Input.Cookie(key)
|
||||
}
|
||||
|
||||
// Set cookie for response.
|
||||
// It's alias of BeegoOutput.Cookie.
|
||||
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
|
||||
ctx.Output.Cookie(name, value, others...)
|
||||
}
|
||||
|
||||
// Get secure cookie from request by a given key.
|
||||
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
|
||||
val := ctx.Input.Cookie(key)
|
||||
if val == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
parts := strings.SplitN(val, "|", 3)
|
||||
|
||||
if len(parts) != 3 {
|
||||
return "", false
|
||||
}
|
||||
|
||||
vs := parts[0]
|
||||
timestamp := parts[1]
|
||||
sig := parts[2]
|
||||
|
||||
h := hmac.New(sha1.New, []byte(Secret))
|
||||
fmt.Fprintf(h, "%s%s", vs, timestamp)
|
||||
|
||||
if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
|
||||
return "", false
|
||||
}
|
||||
res, _ := base64.URLEncoding.DecodeString(vs)
|
||||
return string(res), true
|
||||
}
|
||||
|
||||
// Set Secure cookie for response.
|
||||
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
|
||||
vs := base64.URLEncoding.EncodeToString([]byte(value))
|
||||
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
|
||||
h := hmac.New(sha1.New, []byte(Secret))
|
||||
fmt.Fprintf(h, "%s%s", vs, timestamp)
|
||||
sig := fmt.Sprintf("%02x", h.Sum(nil))
|
||||
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
|
||||
ctx.Output.Cookie(name, cookie, others...)
|
||||
}
|
||||
|
||||
// XsrfToken creates a xsrf token string and returns.
|
||||
func (ctx *Context) XsrfToken(key string, expire int64) string {
|
||||
if ctx._xsrf_token == "" {
|
||||
token, ok := ctx.GetSecureCookie(key, "_xsrf")
|
||||
if !ok {
|
||||
token = string(utils.RandomCreateBytes(32))
|
||||
ctx.SetSecureCookie(key, "_xsrf", token, expire)
|
||||
}
|
||||
ctx._xsrf_token = token
|
||||
}
|
||||
return ctx._xsrf_token
|
||||
}
|
||||
|
||||
// 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 {
|
||||
token := ctx.Input.Query("_xsrf")
|
||||
if token == "" {
|
||||
token = ctx.Request.Header.Get("X-Xsrftoken")
|
||||
}
|
||||
if token == "" {
|
||||
token = ctx.Request.Header.Get("X-Csrftoken")
|
||||
}
|
||||
if token == "" {
|
||||
ctx.Abort(403, "'_xsrf' argument missing from POST")
|
||||
} else if ctx._xsrf_token != token {
|
||||
ctx.Abort(403, "XSRF cookie does not match POST argument")
|
||||
}
|
||||
return true
|
||||
}
|
535
context/input.go
Normal file
@ -0,0 +1,535 @@
|
||||
// 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 (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/session"
|
||||
)
|
||||
|
||||
// BeegoInput operates the http request header ,data ,cookie and body.
|
||||
// it also contains router params and current session.
|
||||
type BeegoInput struct {
|
||||
CruSession session.SessionStore
|
||||
Params map[string]string
|
||||
Data map[interface{}]interface{} // store some values in this context when calling context in filter or controller.
|
||||
Request *http.Request
|
||||
RequestBody []byte
|
||||
RunController reflect.Type
|
||||
RunMethod string
|
||||
}
|
||||
|
||||
// NewInput return BeegoInput generated by http.Request.
|
||||
func NewInput(req *http.Request) *BeegoInput {
|
||||
return &BeegoInput{
|
||||
Params: make(map[string]string),
|
||||
Data: make(map[interface{}]interface{}),
|
||||
Request: req,
|
||||
}
|
||||
}
|
||||
|
||||
// Protocol returns request protocol name, such as HTTP/1.1 .
|
||||
func (input *BeegoInput) Protocol() string {
|
||||
return input.Request.Proto
|
||||
}
|
||||
|
||||
// Uri returns full request url with query string, fragment.
|
||||
func (input *BeegoInput) Uri() string {
|
||||
return input.Request.RequestURI
|
||||
}
|
||||
|
||||
// Url returns request url path (without query string, fragment).
|
||||
func (input *BeegoInput) Url() string {
|
||||
return input.Request.URL.Path
|
||||
}
|
||||
|
||||
// Site returns base site url as scheme://domain type.
|
||||
func (input *BeegoInput) Site() string {
|
||||
return input.Scheme() + "://" + input.Domain()
|
||||
}
|
||||
|
||||
// Scheme returns request scheme as "http" or "https".
|
||||
func (input *BeegoInput) Scheme() string {
|
||||
if input.Request.URL.Scheme != "" {
|
||||
return input.Request.URL.Scheme
|
||||
} else if input.Request.TLS == nil {
|
||||
return "http"
|
||||
} else {
|
||||
return "https"
|
||||
}
|
||||
}
|
||||
|
||||
// Domain returns host name.
|
||||
// Alias of Host method.
|
||||
func (input *BeegoInput) Domain() string {
|
||||
return input.Host()
|
||||
}
|
||||
|
||||
// Host returns host name.
|
||||
// if no host info in request, return localhost.
|
||||
func (input *BeegoInput) Host() string {
|
||||
if input.Request.Host != "" {
|
||||
hostParts := strings.Split(input.Request.Host, ":")
|
||||
if len(hostParts) > 0 {
|
||||
return hostParts[0]
|
||||
}
|
||||
return input.Request.Host
|
||||
}
|
||||
return "localhost"
|
||||
}
|
||||
|
||||
// Method returns http request method.
|
||||
func (input *BeegoInput) Method() string {
|
||||
return input.Request.Method
|
||||
}
|
||||
|
||||
// Is returns boolean of this request is on given method, such as Is("POST").
|
||||
func (input *BeegoInput) Is(method string) bool {
|
||||
return input.Method() == method
|
||||
}
|
||||
|
||||
// Is this a GET method request?
|
||||
func (input *BeegoInput) IsGet() bool {
|
||||
return input.Is("GET")
|
||||
}
|
||||
|
||||
// Is this a POST method request?
|
||||
func (input *BeegoInput) IsPost() bool {
|
||||
return input.Is("POST")
|
||||
}
|
||||
|
||||
// Is this a Head method request?
|
||||
func (input *BeegoInput) IsHead() bool {
|
||||
return input.Is("HEAD")
|
||||
}
|
||||
|
||||
// Is this a OPTIONS method request?
|
||||
func (input *BeegoInput) IsOptions() bool {
|
||||
return input.Is("OPTIONS")
|
||||
}
|
||||
|
||||
// Is this a PUT method request?
|
||||
func (input *BeegoInput) IsPut() bool {
|
||||
return input.Is("PUT")
|
||||
}
|
||||
|
||||
// Is this a DELETE method request?
|
||||
func (input *BeegoInput) IsDelete() bool {
|
||||
return input.Is("DELETE")
|
||||
}
|
||||
|
||||
// Is this a PATCH method request?
|
||||
func (input *BeegoInput) IsPatch() bool {
|
||||
return input.Is("PATCH")
|
||||
}
|
||||
|
||||
// IsAjax returns boolean of this request is generated by ajax.
|
||||
func (input *BeegoInput) IsAjax() bool {
|
||||
return input.Header("X-Requested-With") == "XMLHttpRequest"
|
||||
}
|
||||
|
||||
// IsSecure returns boolean of this request is in https.
|
||||
func (input *BeegoInput) IsSecure() bool {
|
||||
return input.Scheme() == "https"
|
||||
}
|
||||
|
||||
// IsSecure returns boolean of this request is in webSocket.
|
||||
func (input *BeegoInput) IsWebsocket() bool {
|
||||
return input.Header("Upgrade") == "websocket"
|
||||
}
|
||||
|
||||
// IsSecure returns boolean of whether file uploads in this request or not..
|
||||
func (input *BeegoInput) IsUpload() bool {
|
||||
return strings.Contains(input.Header("Content-Type"), "multipart/form-data")
|
||||
}
|
||||
|
||||
// IP returns request client ip.
|
||||
// if in proxy, return first proxy id.
|
||||
// if error, return 127.0.0.1.
|
||||
func (input *BeegoInput) IP() string {
|
||||
ips := input.Proxy()
|
||||
if len(ips) > 0 && ips[0] != "" {
|
||||
rip := strings.Split(ips[0], ":")
|
||||
return rip[0]
|
||||
}
|
||||
ip := strings.Split(input.Request.RemoteAddr, ":")
|
||||
if len(ip) > 0 {
|
||||
if ip[0] != "[" {
|
||||
return ip[0]
|
||||
}
|
||||
}
|
||||
return "127.0.0.1"
|
||||
}
|
||||
|
||||
// Proxy returns proxy client ips slice.
|
||||
func (input *BeegoInput) Proxy() []string {
|
||||
if ips := input.Header("X-Forwarded-For"); ips != "" {
|
||||
return strings.Split(ips, ",")
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// Refer returns http referer header.
|
||||
func (input *BeegoInput) Refer() string {
|
||||
return input.Header("Referer")
|
||||
}
|
||||
|
||||
// SubDomains returns sub domain string.
|
||||
// if aa.bb.domain.com, returns aa.bb .
|
||||
func (input *BeegoInput) SubDomains() string {
|
||||
parts := strings.Split(input.Host(), ".")
|
||||
return strings.Join(parts[len(parts)-2:], ".")
|
||||
}
|
||||
|
||||
// Port returns request client port.
|
||||
// when error or empty, return 80.
|
||||
func (input *BeegoInput) Port() int {
|
||||
parts := strings.Split(input.Request.Host, ":")
|
||||
if len(parts) == 2 {
|
||||
port, _ := strconv.Atoi(parts[1])
|
||||
return port
|
||||
}
|
||||
return 80
|
||||
}
|
||||
|
||||
// UserAgent returns request client user agent string.
|
||||
func (input *BeegoInput) UserAgent() string {
|
||||
return input.Header("User-Agent")
|
||||
}
|
||||
|
||||
// Param returns router param by a given key.
|
||||
func (input *BeegoInput) Param(key string) string {
|
||||
if v, ok := input.Params[key]; ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Query returns input data item string by a given string.
|
||||
func (input *BeegoInput) Query(key string) string {
|
||||
if val := input.Param(key); val != "" {
|
||||
return val
|
||||
}
|
||||
if input.Request.Form == nil {
|
||||
input.Request.ParseForm()
|
||||
}
|
||||
return input.Request.Form.Get(key)
|
||||
}
|
||||
|
||||
// Header returns request header item string by a given string.
|
||||
func (input *BeegoInput) Header(key string) string {
|
||||
return input.Request.Header.Get(key)
|
||||
}
|
||||
|
||||
// Cookie returns request cookie item string by a given key.
|
||||
// if non-existed, return empty string.
|
||||
func (input *BeegoInput) Cookie(key string) string {
|
||||
ck, err := input.Request.Cookie(key)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return ck.Value
|
||||
}
|
||||
|
||||
// Session returns current session item value by a given key.
|
||||
func (input *BeegoInput) Session(key interface{}) interface{} {
|
||||
return input.CruSession.Get(key)
|
||||
}
|
||||
|
||||
// Body returns the raw request body data as bytes.
|
||||
func (input *BeegoInput) CopyBody() []byte {
|
||||
requestbody, _ := ioutil.ReadAll(input.Request.Body)
|
||||
input.Request.Body.Close()
|
||||
bf := bytes.NewBuffer(requestbody)
|
||||
input.Request.Body = ioutil.NopCloser(bf)
|
||||
input.RequestBody = requestbody
|
||||
return requestbody
|
||||
}
|
||||
|
||||
// GetData returns the stored data in this context.
|
||||
func (input *BeegoInput) GetData(key interface{}) interface{} {
|
||||
if v, ok := input.Data[key]; ok {
|
||||
return v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetData stores data with given key in this context.
|
||||
// This data are only available in this context.
|
||||
func (input *BeegoInput) SetData(key, val interface{}) {
|
||||
input.Data[key] = val
|
||||
}
|
||||
|
||||
// parseForm or parseMultiForm based on Content-type
|
||||
func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error {
|
||||
// Parse the body depending on the content type.
|
||||
if strings.Contains(input.Header("Content-Type"), "multipart/form-data") {
|
||||
if err := input.Request.ParseMultipartForm(maxMemory); err != nil {
|
||||
return errors.New("Error parsing request body:" + err.Error())
|
||||
}
|
||||
} else if err := input.Request.ParseForm(); err != nil {
|
||||
return errors.New("Error parsing request body:" + err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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") id ==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 {
|
||||
value := reflect.ValueOf(dest)
|
||||
if value.Kind() != reflect.Ptr {
|
||||
return errors.New("beego: non-pointer passed to Bind: " + key)
|
||||
}
|
||||
value = value.Elem()
|
||||
if !value.CanSet() {
|
||||
return errors.New("beego: non-settable variable passed to Bind: " + key)
|
||||
}
|
||||
rv := input.bind(key, value.Type())
|
||||
if !rv.IsValid() {
|
||||
return errors.New("beego: reflect value is empty")
|
||||
}
|
||||
value.Set(rv)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bind(key string, typ reflect.Type) reflect.Value {
|
||||
rv := reflect.Zero(reflect.TypeOf(0))
|
||||
switch typ.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
val := input.Query(key)
|
||||
if len(val) == 0 {
|
||||
return rv
|
||||
}
|
||||
rv = input.bindInt(val, typ)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
val := input.Query(key)
|
||||
if len(val) == 0 {
|
||||
return rv
|
||||
}
|
||||
rv = input.bindUint(val, typ)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
val := input.Query(key)
|
||||
if len(val) == 0 {
|
||||
return rv
|
||||
}
|
||||
rv = input.bindFloat(val, typ)
|
||||
case reflect.String:
|
||||
val := input.Query(key)
|
||||
if len(val) == 0 {
|
||||
return rv
|
||||
}
|
||||
rv = input.bindString(val, typ)
|
||||
case reflect.Bool:
|
||||
val := input.Query(key)
|
||||
if len(val) == 0 {
|
||||
return rv
|
||||
}
|
||||
rv = input.bindBool(val, typ)
|
||||
case reflect.Slice:
|
||||
rv = input.bindSlice(&input.Request.Form, key, typ)
|
||||
case reflect.Struct:
|
||||
rv = input.bindStruct(&input.Request.Form, key, typ)
|
||||
case reflect.Ptr:
|
||||
rv = input.bindPoint(key, typ)
|
||||
case reflect.Map:
|
||||
rv = input.bindMap(&input.Request.Form, key, typ)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindValue(val string, typ reflect.Type) reflect.Value {
|
||||
rv := reflect.Zero(reflect.TypeOf(0))
|
||||
switch typ.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
rv = input.bindInt(val, typ)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
rv = input.bindUint(val, typ)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
rv = input.bindFloat(val, typ)
|
||||
case reflect.String:
|
||||
rv = input.bindString(val, typ)
|
||||
case reflect.Bool:
|
||||
rv = input.bindBool(val, typ)
|
||||
case reflect.Slice:
|
||||
rv = input.bindSlice(&url.Values{"": {val}}, "", typ)
|
||||
case reflect.Struct:
|
||||
rv = input.bindStruct(&url.Values{"": {val}}, "", typ)
|
||||
case reflect.Ptr:
|
||||
rv = input.bindPoint(val, typ)
|
||||
case reflect.Map:
|
||||
rv = input.bindMap(&url.Values{"": {val}}, "", typ)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindInt(val string, typ reflect.Type) reflect.Value {
|
||||
intValue, err := strconv.ParseInt(val, 10, 64)
|
||||
if err != nil {
|
||||
return reflect.Zero(typ)
|
||||
}
|
||||
pValue := reflect.New(typ)
|
||||
pValue.Elem().SetInt(intValue)
|
||||
return pValue.Elem()
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindUint(val string, typ reflect.Type) reflect.Value {
|
||||
uintValue, err := strconv.ParseUint(val, 10, 64)
|
||||
if err != nil {
|
||||
return reflect.Zero(typ)
|
||||
}
|
||||
pValue := reflect.New(typ)
|
||||
pValue.Elem().SetUint(uintValue)
|
||||
return pValue.Elem()
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindFloat(val string, typ reflect.Type) reflect.Value {
|
||||
floatValue, err := strconv.ParseFloat(val, 64)
|
||||
if err != nil {
|
||||
return reflect.Zero(typ)
|
||||
}
|
||||
pValue := reflect.New(typ)
|
||||
pValue.Elem().SetFloat(floatValue)
|
||||
return pValue.Elem()
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindString(val string, typ reflect.Type) reflect.Value {
|
||||
return reflect.ValueOf(val)
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindBool(val string, typ reflect.Type) reflect.Value {
|
||||
val = strings.TrimSpace(strings.ToLower(val))
|
||||
switch val {
|
||||
case "true", "on", "1":
|
||||
return reflect.ValueOf(true)
|
||||
}
|
||||
return reflect.ValueOf(false)
|
||||
}
|
||||
|
||||
type sliceValue struct {
|
||||
index int // Index extracted from brackets. If -1, no index was provided.
|
||||
value reflect.Value // the bound value for this slice element.
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindSlice(params *url.Values, key string, typ reflect.Type) reflect.Value {
|
||||
maxIndex := -1
|
||||
numNoIndex := 0
|
||||
sliceValues := []sliceValue{}
|
||||
for reqKey, vals := range *params {
|
||||
if !strings.HasPrefix(reqKey, key+"[") {
|
||||
continue
|
||||
}
|
||||
// Extract the index, and the index where a sub-key starts. (e.g. field[0].subkey)
|
||||
index := -1
|
||||
leftBracket, rightBracket := len(key), strings.Index(reqKey[len(key):], "]")+len(key)
|
||||
if rightBracket > leftBracket+1 {
|
||||
index, _ = strconv.Atoi(reqKey[leftBracket+1 : rightBracket])
|
||||
}
|
||||
subKeyIndex := rightBracket + 1
|
||||
|
||||
// Handle the indexed case.
|
||||
if index > -1 {
|
||||
if index > maxIndex {
|
||||
maxIndex = index
|
||||
}
|
||||
sliceValues = append(sliceValues, sliceValue{
|
||||
index: index,
|
||||
value: input.bind(reqKey[:subKeyIndex], typ.Elem()),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// It's an un-indexed element. (e.g. element[])
|
||||
numNoIndex += len(vals)
|
||||
for _, val := range vals {
|
||||
// Unindexed values can only be direct-bound.
|
||||
sliceValues = append(sliceValues, sliceValue{
|
||||
index: -1,
|
||||
value: input.bindValue(val, typ.Elem()),
|
||||
})
|
||||
}
|
||||
}
|
||||
resultArray := reflect.MakeSlice(typ, maxIndex+1, maxIndex+1+numNoIndex)
|
||||
for _, sv := range sliceValues {
|
||||
if sv.index != -1 {
|
||||
resultArray.Index(sv.index).Set(sv.value)
|
||||
} else {
|
||||
resultArray = reflect.Append(resultArray, sv.value)
|
||||
}
|
||||
}
|
||||
return resultArray
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindStruct(params *url.Values, key string, typ reflect.Type) reflect.Value {
|
||||
result := reflect.New(typ).Elem()
|
||||
fieldValues := make(map[string]reflect.Value)
|
||||
for reqKey, val := range *params {
|
||||
if !strings.HasPrefix(reqKey, key+".") {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldName := reqKey[len(key)+1:]
|
||||
|
||||
if _, ok := fieldValues[fieldName]; !ok {
|
||||
// Time to bind this field. Get it and make sure we can set it.
|
||||
fieldValue := result.FieldByName(fieldName)
|
||||
if !fieldValue.IsValid() {
|
||||
continue
|
||||
}
|
||||
if !fieldValue.CanSet() {
|
||||
continue
|
||||
}
|
||||
boundVal := input.bindValue(val[0], fieldValue.Type())
|
||||
fieldValue.Set(boundVal)
|
||||
fieldValues[fieldName] = boundVal
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindPoint(key string, typ reflect.Type) reflect.Value {
|
||||
return input.bind(key, typ.Elem()).Addr()
|
||||
}
|
||||
|
||||
func (input *BeegoInput) bindMap(params *url.Values, key string, typ reflect.Type) reflect.Value {
|
||||
var (
|
||||
result = reflect.MakeMap(typ)
|
||||
keyType = typ.Key()
|
||||
valueType = typ.Elem()
|
||||
)
|
||||
for paramName, values := range *params {
|
||||
if !strings.HasPrefix(paramName, key+"[") || paramName[len(paramName)-1] != ']' {
|
||||
continue
|
||||
}
|
||||
|
||||
key := paramName[len(key)+1 : len(paramName)-1]
|
||||
result.SetMapIndex(input.bindValue(key, keyType), input.bindValue(values[0], valueType))
|
||||
}
|
||||
return result
|
||||
}
|
72
context/input_test.go
Normal file
@ -0,0 +1,72 @@
|
||||
// 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 (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "/?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie", nil)
|
||||
beegoInput := NewInput(r)
|
||||
beegoInput.ParseFormOrMulitForm(1 << 20)
|
||||
|
||||
var id int
|
||||
err := beegoInput.Bind(&id, "id")
|
||||
if id != 123 || err != nil {
|
||||
t.Fatal("id should has int value")
|
||||
}
|
||||
fmt.Println(id)
|
||||
|
||||
var isok bool
|
||||
err = beegoInput.Bind(&isok, "isok")
|
||||
if !isok || err != nil {
|
||||
t.Fatal("isok should be true")
|
||||
}
|
||||
fmt.Println(isok)
|
||||
|
||||
var float float64
|
||||
err = beegoInput.Bind(&float, "ft")
|
||||
if float != 1.2 || err != nil {
|
||||
t.Fatal("float should be equal to 1.2")
|
||||
}
|
||||
fmt.Println(float)
|
||||
|
||||
ol := make([]int, 0, 2)
|
||||
err = beegoInput.Bind(&ol, "ol")
|
||||
if len(ol) != 2 || err != nil || ol[0] != 1 || ol[1] != 2 {
|
||||
t.Fatal("ol should has two elements")
|
||||
}
|
||||
fmt.Println(ol)
|
||||
|
||||
ul := make([]string, 0, 2)
|
||||
err = beegoInput.Bind(&ul, "ul")
|
||||
if len(ul) != 2 || err != nil || ul[0] != "str" || ul[1] != "array" {
|
||||
t.Fatal("ul should has two elements")
|
||||
}
|
||||
fmt.Println(ul)
|
||||
|
||||
type User struct {
|
||||
Name string
|
||||
}
|
||||
user := User{}
|
||||
err = beegoInput.Bind(&user, "user")
|
||||
if err != nil || user.Name != "astaxie" {
|
||||
t.Fatal("user should has name")
|
||||
}
|
||||
fmt.Println(user)
|
||||
}
|
360
context/output.go
Normal file
@ -0,0 +1,360 @@
|
||||
// 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 (
|
||||
"bytes"
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BeegoOutput does work for sending response header.
|
||||
type BeegoOutput struct {
|
||||
Context *Context
|
||||
Status int
|
||||
EnableGzip bool
|
||||
}
|
||||
|
||||
// NewOutput returns new BeegoOutput.
|
||||
// it contains nothing now.
|
||||
func NewOutput() *BeegoOutput {
|
||||
return &BeegoOutput{}
|
||||
}
|
||||
|
||||
// Header sets response header item string via given key.
|
||||
func (output *BeegoOutput) Header(key, val string) {
|
||||
output.Context.ResponseWriter.Header().Set(key, val)
|
||||
}
|
||||
|
||||
// Body sets response body content.
|
||||
// if EnableGzip, compress content string.
|
||||
// it sends out response body directly.
|
||||
func (output *BeegoOutput) Body(content []byte) {
|
||||
output_writer := output.Context.ResponseWriter.(io.Writer)
|
||||
if output.EnableGzip == true && output.Context.Input.Header("Accept-Encoding") != "" {
|
||||
splitted := strings.SplitN(output.Context.Input.Header("Accept-Encoding"), ",", -1)
|
||||
encodings := make([]string, len(splitted))
|
||||
|
||||
for i, val := range splitted {
|
||||
encodings[i] = strings.TrimSpace(val)
|
||||
}
|
||||
for _, val := range encodings {
|
||||
if val == "gzip" {
|
||||
output.Header("Content-Encoding", "gzip")
|
||||
output_writer, _ = gzip.NewWriterLevel(output.Context.ResponseWriter, gzip.BestSpeed)
|
||||
|
||||
break
|
||||
} else if val == "deflate" {
|
||||
output.Header("Content-Encoding", "deflate")
|
||||
output_writer, _ = flate.NewWriter(output.Context.ResponseWriter, flate.BestSpeed)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
output.Header("Content-Length", strconv.Itoa(len(content)))
|
||||
}
|
||||
|
||||
// Write status code if it has been set manually
|
||||
// Set it to 0 afterwards to prevent "multiple response.WriteHeader calls"
|
||||
if output.Status != 0 {
|
||||
output.Context.ResponseWriter.WriteHeader(output.Status)
|
||||
output.Status = 0
|
||||
}
|
||||
|
||||
output_writer.Write(content)
|
||||
switch output_writer.(type) {
|
||||
case *gzip.Writer:
|
||||
output_writer.(*gzip.Writer).Close()
|
||||
case *flate.Writer:
|
||||
output_writer.(*flate.Writer).Close()
|
||||
}
|
||||
}
|
||||
|
||||
// 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{}) {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
|
||||
if len(others) > 0 {
|
||||
switch v := others[0].(type) {
|
||||
case int:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int64:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int32:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the settings below
|
||||
// Path, Domain, Secure, HttpOnly
|
||||
// can use nil skip set
|
||||
|
||||
// default "/"
|
||||
if len(others) > 1 {
|
||||
if v, ok := others[1].(string); ok && len(v) > 0 {
|
||||
fmt.Fprintf(&b, "; Path=%s", sanitizeValue(v))
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(&b, "; Path=%s", "/")
|
||||
}
|
||||
|
||||
// default empty
|
||||
if len(others) > 2 {
|
||||
if v, ok := others[2].(string); ok && len(v) > 0 {
|
||||
fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(v))
|
||||
}
|
||||
}
|
||||
|
||||
// default empty
|
||||
if len(others) > 3 {
|
||||
var secure bool
|
||||
switch v := others[3].(type) {
|
||||
case bool:
|
||||
secure = v
|
||||
default:
|
||||
if others[3] != nil {
|
||||
secure = true
|
||||
}
|
||||
}
|
||||
if secure {
|
||||
fmt.Fprintf(&b, "; Secure")
|
||||
}
|
||||
}
|
||||
|
||||
// default false. for session cookie default true
|
||||
httponly := false
|
||||
if len(others) > 4 {
|
||||
if v, ok := others[4].(bool); ok && v {
|
||||
// HttpOnly = true
|
||||
httponly = true
|
||||
}
|
||||
}
|
||||
|
||||
if httponly {
|
||||
fmt.Fprintf(&b, "; HttpOnly")
|
||||
}
|
||||
|
||||
output.Context.ResponseWriter.Header().Add("Set-Cookie", b.String())
|
||||
}
|
||||
|
||||
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
|
||||
|
||||
func sanitizeName(n string) string {
|
||||
return cookieNameSanitizer.Replace(n)
|
||||
}
|
||||
|
||||
var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ")
|
||||
|
||||
func sanitizeValue(v string) string {
|
||||
return cookieValueSanitizer.Replace(v)
|
||||
}
|
||||
|
||||
// Json writes json to response body.
|
||||
// if coding is true, it converts utf-8 to \u0000 type.
|
||||
func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) error {
|
||||
output.Header("Content-Type", "application/json;charset=UTF-8")
|
||||
var content []byte
|
||||
var err error
|
||||
if hasIndent {
|
||||
content, err = json.MarshalIndent(data, "", " ")
|
||||
} else {
|
||||
content, err = json.Marshal(data)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return err
|
||||
}
|
||||
if coding {
|
||||
content = []byte(stringsToJson(string(content)))
|
||||
}
|
||||
output.Body(content)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Jsonp writes jsonp to response body.
|
||||
func (output *BeegoOutput) Jsonp(data interface{}, hasIndent bool) error {
|
||||
output.Header("Content-Type", "application/javascript;charset=UTF-8")
|
||||
var content []byte
|
||||
var err error
|
||||
if hasIndent {
|
||||
content, err = json.MarshalIndent(data, "", " ")
|
||||
} else {
|
||||
content, err = json.Marshal(data)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return err
|
||||
}
|
||||
callback := output.Context.Input.Query("callback")
|
||||
if callback == "" {
|
||||
return errors.New(`"callback" parameter required`)
|
||||
}
|
||||
callback_content := bytes.NewBufferString(" " + template.JSEscapeString(callback))
|
||||
callback_content.WriteString("(")
|
||||
callback_content.Write(content)
|
||||
callback_content.WriteString(");\r\n")
|
||||
output.Body(callback_content.Bytes())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Xml writes xml string to response body.
|
||||
func (output *BeegoOutput) Xml(data interface{}, hasIndent bool) error {
|
||||
output.Header("Content-Type", "application/xml;charset=UTF-8")
|
||||
var content []byte
|
||||
var err error
|
||||
if hasIndent {
|
||||
content, err = xml.MarshalIndent(data, "", " ")
|
||||
} else {
|
||||
content, err = xml.Marshal(data)
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return err
|
||||
}
|
||||
output.Body(content)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Download forces response for download file.
|
||||
// it prepares the download response header automatically.
|
||||
func (output *BeegoOutput) Download(file string, filename ...string) {
|
||||
output.Header("Content-Description", "File Transfer")
|
||||
output.Header("Content-Type", "application/octet-stream")
|
||||
if len(filename) > 0 && filename[0] != "" {
|
||||
output.Header("Content-Disposition", "attachment; filename="+filename[0])
|
||||
} else {
|
||||
output.Header("Content-Disposition", "attachment; filename="+filepath.Base(file))
|
||||
}
|
||||
output.Header("Content-Transfer-Encoding", "binary")
|
||||
output.Header("Expires", "0")
|
||||
output.Header("Cache-Control", "must-revalidate")
|
||||
output.Header("Pragma", "public")
|
||||
http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file)
|
||||
}
|
||||
|
||||
// ContentType sets the content type from ext string.
|
||||
// MIME type is given in mime package.
|
||||
func (output *BeegoOutput) ContentType(ext string) {
|
||||
if !strings.HasPrefix(ext, ".") {
|
||||
ext = "." + ext
|
||||
}
|
||||
ctype := mime.TypeByExtension(ext)
|
||||
if ctype != "" {
|
||||
output.Header("Content-Type", ctype)
|
||||
}
|
||||
}
|
||||
|
||||
// SetStatus sets response status code.
|
||||
// It writes response header directly.
|
||||
func (output *BeegoOutput) SetStatus(status int) {
|
||||
output.Status = status
|
||||
}
|
||||
|
||||
// IsCachable returns boolean of this request is cached.
|
||||
// HTTP 304 means cached.
|
||||
func (output *BeegoOutput) IsCachable(status int) bool {
|
||||
return output.Status >= 200 && output.Status < 300 || output.Status == 304
|
||||
}
|
||||
|
||||
// IsEmpty returns boolean of this request is empty.
|
||||
// HTTP 201,204 and 304 means empty.
|
||||
func (output *BeegoOutput) IsEmpty(status int) bool {
|
||||
return output.Status == 201 || output.Status == 204 || output.Status == 304
|
||||
}
|
||||
|
||||
// IsOk returns boolean of this request runs well.
|
||||
// HTTP 200 means ok.
|
||||
func (output *BeegoOutput) IsOk(status int) bool {
|
||||
return output.Status == 200
|
||||
}
|
||||
|
||||
// IsSuccessful returns boolean of this request runs successfully.
|
||||
// HTTP 2xx means ok.
|
||||
func (output *BeegoOutput) IsSuccessful(status int) bool {
|
||||
return output.Status >= 200 && output.Status < 300
|
||||
}
|
||||
|
||||
// IsRedirect returns boolean of this request is redirection header.
|
||||
// HTTP 301,302,307 means redirection.
|
||||
func (output *BeegoOutput) IsRedirect(status int) bool {
|
||||
return output.Status == 301 || output.Status == 302 || output.Status == 303 || output.Status == 307
|
||||
}
|
||||
|
||||
// IsForbidden returns boolean of this request is forbidden.
|
||||
// HTTP 403 means forbidden.
|
||||
func (output *BeegoOutput) IsForbidden(status int) bool {
|
||||
return output.Status == 403
|
||||
}
|
||||
|
||||
// IsNotFound returns boolean of this request is not found.
|
||||
// HTTP 404 means forbidden.
|
||||
func (output *BeegoOutput) IsNotFound(status int) bool {
|
||||
return output.Status == 404
|
||||
}
|
||||
|
||||
// IsClient returns boolean of this request client sends error data.
|
||||
// HTTP 4xx means forbidden.
|
||||
func (output *BeegoOutput) IsClientError(status int) bool {
|
||||
return output.Status >= 400 && output.Status < 500
|
||||
}
|
||||
|
||||
// IsServerError returns boolean of this server handler errors.
|
||||
// HTTP 5xx means server internal error.
|
||||
func (output *BeegoOutput) IsServerError(status int) bool {
|
||||
return output.Status >= 500 && output.Status < 600
|
||||
}
|
||||
|
||||
func stringsToJson(str string) string {
|
||||
rs := []rune(str)
|
||||
jsons := ""
|
||||
for _, r := range rs {
|
||||
rint := int(r)
|
||||
if rint < 128 {
|
||||
jsons += string(r)
|
||||
} else {
|
||||
jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
|
||||
}
|
||||
}
|
||||
return jsons
|
||||
}
|
||||
|
||||
// Sessions sets session item value with given key.
|
||||
func (output *BeegoOutput) Session(name interface{}, value interface{}) {
|
||||
output.Context.Input.CruSession.Set(name, value)
|
||||
}
|
451
controller.go
@ -1,17 +1,22 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/astaxie/beego/session"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
@ -19,27 +24,59 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
"github.com/astaxie/beego/session"
|
||||
)
|
||||
|
||||
//commonly used mime-types
|
||||
const (
|
||||
applicationJson = "application/json"
|
||||
applicationXml = "application/xml"
|
||||
textXml = "text/xml"
|
||||
)
|
||||
|
||||
var (
|
||||
// custom error when user stop request handler manually.
|
||||
USERSTOPRUN = errors.New("User stop run")
|
||||
GlobalControllerRouter map[string][]ControllerComments = make(map[string][]ControllerComments) //pkgpath+controller:comments
|
||||
)
|
||||
|
||||
// store the comment for the controller method
|
||||
type ControllerComments struct {
|
||||
Method string
|
||||
Router string
|
||||
AllowHTTPMethods []string
|
||||
Params []map[string]string
|
||||
}
|
||||
|
||||
// Controller defines some basic http request handler operations, such as
|
||||
// http context, template and view, session and xsrf.
|
||||
type Controller struct {
|
||||
Ctx *Context
|
||||
Ctx *context.Context
|
||||
Data map[interface{}]interface{}
|
||||
ChildName string
|
||||
controllerName string
|
||||
actionName string
|
||||
TplNames string
|
||||
Layout string
|
||||
LayoutSections map[string]string // the key is the section name and the value is the template name
|
||||
TplExt string
|
||||
_xsrf_token string
|
||||
gotofunc string
|
||||
CruSession session.SessionStore
|
||||
XSRFExpire int
|
||||
AppController interface{}
|
||||
EnableRender bool
|
||||
EnableXSRF bool
|
||||
methodMapping map[string]func() //method:routertree
|
||||
}
|
||||
|
||||
// ControllerInterface is an interface to uniform all controller handler.
|
||||
type ControllerInterface interface {
|
||||
Init(ct *Context, cn string)
|
||||
Init(ct *context.Context, controllerName, actionName string, app interface{})
|
||||
Prepare()
|
||||
Get()
|
||||
Post()
|
||||
@ -50,255 +87,324 @@ type ControllerInterface interface {
|
||||
Options()
|
||||
Finish()
|
||||
Render() error
|
||||
XsrfToken() string
|
||||
CheckXsrfCookie() bool
|
||||
HandlerFunc(fn string) bool
|
||||
URLMapping()
|
||||
}
|
||||
|
||||
func (c *Controller) Init(ctx *Context, cn string) {
|
||||
c.Data = make(map[interface{}]interface{})
|
||||
// Init generates default values of controller operations.
|
||||
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
|
||||
c.Layout = ""
|
||||
c.TplNames = ""
|
||||
c.ChildName = cn
|
||||
c.controllerName = controllerName
|
||||
c.actionName = actionName
|
||||
c.Ctx = ctx
|
||||
c.TplExt = "tpl"
|
||||
c.AppController = app
|
||||
c.EnableRender = true
|
||||
c.EnableXSRF = true
|
||||
c.Data = ctx.Input.Data
|
||||
c.methodMapping = make(map[string]func())
|
||||
}
|
||||
|
||||
// Prepare runs after Init before request function execution.
|
||||
func (c *Controller) Prepare() {
|
||||
|
||||
}
|
||||
|
||||
// Finish runs after request function execution.
|
||||
func (c *Controller) Finish() {
|
||||
|
||||
}
|
||||
|
||||
func (c *Controller) Destructor() {
|
||||
if c.CruSession != nil {
|
||||
c.CruSession.SessionRelease()
|
||||
}
|
||||
}
|
||||
|
||||
// Get adds a request function to handle GET request.
|
||||
func (c *Controller) Get() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Post adds a request function to handle POST request.
|
||||
func (c *Controller) Post() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Delete adds a request function to handle DELETE request.
|
||||
func (c *Controller) Delete() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Put adds a request function to handle PUT request.
|
||||
func (c *Controller) Put() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Head adds a request function to handle HEAD request.
|
||||
func (c *Controller) Head() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Patch adds a request function to handle PATCH request.
|
||||
func (c *Controller) Patch() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// Options adds a request function to handle OPTIONS request.
|
||||
func (c *Controller) Options() {
|
||||
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
// call function fn
|
||||
func (c *Controller) HandlerFunc(fnname string) bool {
|
||||
if v, ok := c.methodMapping[fnname]; ok {
|
||||
v()
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// URLMapping register the internal Controller router.
|
||||
func (c *Controller) URLMapping() {
|
||||
}
|
||||
|
||||
func (c *Controller) Mapping(method string, fn func()) {
|
||||
c.methodMapping[method] = fn
|
||||
}
|
||||
|
||||
// Render sends the response with rendered template bytes as text/html type.
|
||||
func (c *Controller) Render() error {
|
||||
if !c.EnableRender {
|
||||
return nil
|
||||
}
|
||||
rb, err := c.RenderBytes()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
c.writeToWriter(rb)
|
||||
c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.Ctx.Output.Body(rb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenderString returns the rendered template string. Do not send out response.
|
||||
func (c *Controller) RenderString() (string, error) {
|
||||
b, e := c.RenderBytes()
|
||||
return string(b), e
|
||||
}
|
||||
|
||||
// RenderBytes returns the bytes of rendered template string. Do not send out response.
|
||||
func (c *Controller) RenderBytes() ([]byte, error) {
|
||||
//if the controller has set layout, then first get the tplname's content set the content to the layout
|
||||
if c.Layout != "" {
|
||||
if c.TplNames == "" {
|
||||
c.TplNames = c.ChildName + "/" + strings.ToLower(c.Ctx.Request.Method) + "." + c.TplExt
|
||||
c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
|
||||
}
|
||||
if RunMode == "dev" {
|
||||
BuildTemplate(ViewsPath)
|
||||
}
|
||||
subdir := path.Dir(c.TplNames)
|
||||
_, file := path.Split(c.TplNames)
|
||||
newbytes := bytes.NewBufferString("")
|
||||
if _, ok := BeeTemplates[subdir]; !ok {
|
||||
if _, ok := BeeTemplates[c.TplNames]; !ok {
|
||||
panic("can't find templatefile in the path:" + c.TplNames)
|
||||
return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
|
||||
}
|
||||
BeeTemplates[subdir].ExecuteTemplate(newbytes, file, c.Data)
|
||||
tplcontent, _ := ioutil.ReadAll(newbytes)
|
||||
c.Data["LayoutContent"] = template.HTML(string(tplcontent))
|
||||
subdir = path.Dir(c.Layout)
|
||||
_, file = path.Split(c.Layout)
|
||||
ibytes := bytes.NewBufferString("")
|
||||
err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
|
||||
err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
return nil, err
|
||||
}
|
||||
tplcontent, _ := ioutil.ReadAll(newbytes)
|
||||
c.Data["LayoutContent"] = template.HTML(string(tplcontent))
|
||||
|
||||
if c.LayoutSections != nil {
|
||||
for sectionName, sectionTpl := range c.LayoutSections {
|
||||
if sectionTpl == "" {
|
||||
c.Data[sectionName] = ""
|
||||
continue
|
||||
}
|
||||
|
||||
sectionBytes := bytes.NewBufferString("")
|
||||
err = BeeTemplates[sectionTpl].ExecuteTemplate(sectionBytes, sectionTpl, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
return nil, err
|
||||
}
|
||||
sectionContent, _ := ioutil.ReadAll(sectionBytes)
|
||||
c.Data[sectionName] = template.HTML(string(sectionContent))
|
||||
}
|
||||
}
|
||||
|
||||
ibytes := bytes.NewBufferString("")
|
||||
err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
return nil, err
|
||||
}
|
||||
icontent, _ := ioutil.ReadAll(ibytes)
|
||||
return icontent, nil
|
||||
} else {
|
||||
if c.TplNames == "" {
|
||||
c.TplNames = c.ChildName + "/" + strings.ToLower(c.Ctx.Request.Method) + "." + c.TplExt
|
||||
c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
|
||||
}
|
||||
if RunMode == "dev" {
|
||||
BuildTemplate(ViewsPath)
|
||||
}
|
||||
subdir := path.Dir(c.TplNames)
|
||||
_, file := path.Split(c.TplNames)
|
||||
ibytes := bytes.NewBufferString("")
|
||||
if _, ok := BeeTemplates[subdir]; !ok {
|
||||
if _, ok := BeeTemplates[c.TplNames]; !ok {
|
||||
panic("can't find templatefile in the path:" + c.TplNames)
|
||||
return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
|
||||
}
|
||||
err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
|
||||
err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
return nil, err
|
||||
}
|
||||
icontent, _ := ioutil.ReadAll(ibytes)
|
||||
return icontent, nil
|
||||
}
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
func (c *Controller) writeToWriter(rb []byte) {
|
||||
output_writer := c.Ctx.ResponseWriter.(io.Writer)
|
||||
if EnableGzip == true && c.Ctx.Request.Header.Get("Accept-Encoding") != "" {
|
||||
splitted := strings.SplitN(c.Ctx.Request.Header.Get("Accept-Encoding"), ",", -1)
|
||||
encodings := make([]string, len(splitted))
|
||||
|
||||
for i, val := range splitted {
|
||||
encodings[i] = strings.TrimSpace(val)
|
||||
}
|
||||
for _, val := range encodings {
|
||||
if val == "gzip" {
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
|
||||
output_writer, _ = gzip.NewWriterLevel(c.Ctx.ResponseWriter, gzip.BestSpeed)
|
||||
|
||||
break
|
||||
} else if val == "deflate" {
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "deflate")
|
||||
output_writer, _ = flate.NewWriter(c.Ctx.ResponseWriter, flate.BestSpeed)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(rb)), true)
|
||||
}
|
||||
output_writer.Write(rb)
|
||||
switch output_writer.(type) {
|
||||
case *gzip.Writer:
|
||||
output_writer.(*gzip.Writer).Close()
|
||||
case *flate.Writer:
|
||||
output_writer.(*flate.Writer).Close()
|
||||
case io.WriteCloser:
|
||||
output_writer.(io.WriteCloser).Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect sends the redirection response to url with status code.
|
||||
func (c *Controller) Redirect(url string, code int) {
|
||||
c.Ctx.Redirect(code, url)
|
||||
}
|
||||
|
||||
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
|
||||
func (c *Controller) Abort(code string) {
|
||||
panic(code)
|
||||
}
|
||||
|
||||
func (c *Controller) ServeJson(encoding ...bool) {
|
||||
content, err := json.MarshalIndent(c.Data["json"], "", " ")
|
||||
if err != nil {
|
||||
http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=UTF-8")
|
||||
if len(encoding) > 0 && encoding[0] == true {
|
||||
content = []byte(stringsToJson(string(content)))
|
||||
}
|
||||
c.writeToWriter(content)
|
||||
}
|
||||
|
||||
func (c *Controller) ServeJsonp() {
|
||||
content, err := json.MarshalIndent(c.Data["jsonp"], "", " ")
|
||||
if err != nil {
|
||||
http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
callback := c.Ctx.Request.Form.Get("callback")
|
||||
if callback == "" {
|
||||
http.Error(c.Ctx.ResponseWriter, `"callback" parameter required`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
callback_content := bytes.NewBufferString(callback)
|
||||
callback_content.WriteString("(")
|
||||
callback_content.Write(content)
|
||||
callback_content.WriteString(");\r\n")
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=UTF-8")
|
||||
c.writeToWriter(callback_content.Bytes())
|
||||
}
|
||||
|
||||
func (c *Controller) ServeXml() {
|
||||
content, err := xml.Marshal(c.Data["xml"])
|
||||
if err != nil {
|
||||
http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/xml;charset=UTF-8")
|
||||
c.writeToWriter(content)
|
||||
}
|
||||
|
||||
func (c *Controller) Input() url.Values {
|
||||
ct := c.Ctx.Request.Header.Get("Content-Type")
|
||||
if strings.Contains(ct, "multipart/form-data") {
|
||||
c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
|
||||
status, err := strconv.Atoi(code)
|
||||
if err == nil {
|
||||
c.Ctx.Abort(status, code)
|
||||
} else {
|
||||
c.Ctx.Abort(200, 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) {
|
||||
c.Ctx.Abort(status, body)
|
||||
}
|
||||
|
||||
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
|
||||
func (c *Controller) StopRun() {
|
||||
panic(USERSTOPRUN)
|
||||
}
|
||||
|
||||
// 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 ...string) string {
|
||||
if len(endpoint) <= 0 {
|
||||
return ""
|
||||
}
|
||||
if endpoint[0] == '.' {
|
||||
return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
|
||||
} else {
|
||||
return UrlFor(endpoint, values...)
|
||||
}
|
||||
}
|
||||
|
||||
// ServeJson sends a json response with encoding charset.
|
||||
func (c *Controller) ServeJson(encoding ...bool) {
|
||||
var hasIndent bool
|
||||
var hasencoding bool
|
||||
if RunMode == "prod" {
|
||||
hasIndent = false
|
||||
} else {
|
||||
hasIndent = true
|
||||
}
|
||||
if len(encoding) > 0 && encoding[0] == true {
|
||||
hasencoding = true
|
||||
}
|
||||
c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
|
||||
}
|
||||
|
||||
// ServeJsonp sends a jsonp response.
|
||||
func (c *Controller) ServeJsonp() {
|
||||
var hasIndent bool
|
||||
if RunMode == "prod" {
|
||||
hasIndent = false
|
||||
} else {
|
||||
hasIndent = true
|
||||
}
|
||||
c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
|
||||
}
|
||||
|
||||
// ServeXml sends xml response.
|
||||
func (c *Controller) ServeXml() {
|
||||
var hasIndent bool
|
||||
if RunMode == "prod" {
|
||||
hasIndent = false
|
||||
} else {
|
||||
hasIndent = true
|
||||
}
|
||||
c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
|
||||
}
|
||||
|
||||
// ServeFormatted serve Xml OR Json, depending on the value of the Accept header
|
||||
func (c *Controller) ServeFormatted() {
|
||||
accept := c.Ctx.Input.Header("Accept")
|
||||
switch accept {
|
||||
case applicationJson:
|
||||
c.ServeJson()
|
||||
case applicationXml, textXml:
|
||||
c.ServeXml()
|
||||
default:
|
||||
c.ServeJson()
|
||||
}
|
||||
}
|
||||
|
||||
// Input returns the input data map from POST or PUT request body and query string.
|
||||
func (c *Controller) Input() url.Values {
|
||||
if c.Ctx.Request.Form == nil {
|
||||
c.Ctx.Request.ParseForm()
|
||||
}
|
||||
return c.Ctx.Request.Form
|
||||
}
|
||||
|
||||
// ParseForm maps input data map to obj struct.
|
||||
func (c *Controller) ParseForm(obj interface{}) error {
|
||||
return ParseForm(c.Input(), obj)
|
||||
}
|
||||
|
||||
// GetString returns the input value by key string.
|
||||
func (c *Controller) GetString(key string) string {
|
||||
return c.Input().Get(key)
|
||||
return c.Ctx.Input.Query(key)
|
||||
}
|
||||
|
||||
// GetStrings returns the input string slice by key string.
|
||||
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
|
||||
func (c *Controller) GetStrings(key string) []string {
|
||||
r := c.Ctx.Request
|
||||
if r.Form == nil {
|
||||
f := c.Input()
|
||||
if f == nil {
|
||||
return []string{}
|
||||
}
|
||||
vs := r.Form[key]
|
||||
vs := f[key]
|
||||
if len(vs) > 0 {
|
||||
return vs
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// GetInt returns input value as int64.
|
||||
func (c *Controller) GetInt(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.Input().Get(key), 10, 64)
|
||||
return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
|
||||
}
|
||||
|
||||
// GetBool returns input value as bool.
|
||||
func (c *Controller) GetBool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.Input().Get(key))
|
||||
return strconv.ParseBool(c.Ctx.Input.Query(key))
|
||||
}
|
||||
|
||||
// GetFloat returns input value as float64.
|
||||
func (c *Controller) GetFloat(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
|
||||
}
|
||||
|
||||
// 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 c.Ctx.Request.FormFile(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 {
|
||||
file, _, err := c.Ctx.Request.FormFile(fromfile)
|
||||
if err != nil {
|
||||
@ -314,13 +420,15 @@ func (c *Controller) SaveToFile(fromfile, tofile string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartSession starts session and load old session data info this controller.
|
||||
func (c *Controller) StartSession() session.SessionStore {
|
||||
if c.CruSession == nil {
|
||||
c.CruSession = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
|
||||
c.CruSession = c.Ctx.Input.CruSession
|
||||
}
|
||||
return c.CruSession
|
||||
}
|
||||
|
||||
// SetSession puts value into session.
|
||||
func (c *Controller) SetSession(name interface{}, value interface{}) {
|
||||
if c.CruSession == nil {
|
||||
c.StartSession()
|
||||
@ -328,6 +436,7 @@ func (c *Controller) SetSession(name interface{}, value interface{}) {
|
||||
c.CruSession.Set(name, value)
|
||||
}
|
||||
|
||||
// GetSession gets value from session.
|
||||
func (c *Controller) GetSession(name interface{}) interface{} {
|
||||
if c.CruSession == nil {
|
||||
c.StartSession()
|
||||
@ -335,6 +444,7 @@ func (c *Controller) GetSession(name interface{}) interface{} {
|
||||
return c.CruSession.Get(name)
|
||||
}
|
||||
|
||||
// SetSession removes value from session.
|
||||
func (c *Controller) DelSession(name interface{}) {
|
||||
if c.CruSession == nil {
|
||||
c.StartSession()
|
||||
@ -342,61 +452,68 @@ func (c *Controller) DelSession(name interface{}) {
|
||||
c.CruSession.Delete(name)
|
||||
}
|
||||
|
||||
// SessionRegenerateID regenerates session id for this session.
|
||||
// the session data have no changes.
|
||||
func (c *Controller) SessionRegenerateID() {
|
||||
if c.CruSession != nil {
|
||||
c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
|
||||
}
|
||||
c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
|
||||
c.Ctx.Input.CruSession = c.CruSession
|
||||
}
|
||||
|
||||
// DestroySession cleans session data and session cookie.
|
||||
func (c *Controller) DestroySession() {
|
||||
c.Ctx.Input.CruSession.Flush()
|
||||
GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
|
||||
}
|
||||
|
||||
// IsAjax returns this request is ajax or not.
|
||||
func (c *Controller) IsAjax() bool {
|
||||
return (c.Ctx.Request.Header.Get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest")
|
||||
return c.Ctx.Input.IsAjax()
|
||||
}
|
||||
|
||||
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
|
||||
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
|
||||
return c.Ctx.GetSecureCookie(Secret, key)
|
||||
}
|
||||
|
||||
// SetSecureCookie puts value into cookie after encoded the value.
|
||||
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
|
||||
c.Ctx.SetSecureCookie(Secret, name, value, others...)
|
||||
}
|
||||
|
||||
// XsrfToken creates a xsrf token string and returns.
|
||||
func (c *Controller) XsrfToken() string {
|
||||
if c._xsrf_token == "" {
|
||||
token := c.Ctx.GetCookie("_xsrf")
|
||||
if token == "" {
|
||||
h := hmac.New(sha1.New, []byte(XSRFKEY))
|
||||
fmt.Fprintf(h, "%s:%d", c.Ctx.Request.RemoteAddr, time.Now().UnixNano())
|
||||
tok := fmt.Sprintf("%s:%d", h.Sum(nil), time.Now().UnixNano())
|
||||
token = base64.URLEncoding.EncodeToString([]byte(tok))
|
||||
expire := 0
|
||||
var expire int64
|
||||
if c.XSRFExpire > 0 {
|
||||
expire = c.XSRFExpire
|
||||
expire = int64(c.XSRFExpire)
|
||||
} else {
|
||||
expire = XSRFExpire
|
||||
expire = int64(XSRFExpire)
|
||||
}
|
||||
c.Ctx.SetCookie("_xsrf", token, expire)
|
||||
}
|
||||
c._xsrf_token = token
|
||||
c._xsrf_token = c.Ctx.XsrfToken(XSRFKEY, expire)
|
||||
}
|
||||
return c._xsrf_token
|
||||
}
|
||||
|
||||
// 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 {
|
||||
token := c.GetString("_xsrf")
|
||||
if token == "" {
|
||||
token = c.Ctx.Request.Header.Get("X-Xsrftoken")
|
||||
}
|
||||
if token == "" {
|
||||
token = c.Ctx.Request.Header.Get("X-Csrftoken")
|
||||
}
|
||||
if token == "" {
|
||||
c.Ctx.Abort(403, "'_xsrf' argument missing from POST")
|
||||
}
|
||||
|
||||
if c._xsrf_token != token {
|
||||
c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
|
||||
}
|
||||
if !c.EnableXSRF {
|
||||
return true
|
||||
}
|
||||
return c.Ctx.CheckXsrfCookie()
|
||||
}
|
||||
|
||||
// XsrfFormHtml writes an input field contains xsrf token value.
|
||||
func (c *Controller) XsrfFormHtml() string {
|
||||
return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
|
||||
c._xsrf_token + "\"/>"
|
||||
}
|
||||
|
||||
func (c *Controller) GoToFunc(funcname string) {
|
||||
if funcname[0] < 65 || funcname[0] > 90 {
|
||||
panic("GoToFunc should exported function")
|
||||
}
|
||||
c.gotofunc = funcname
|
||||
// GetControllerAndAction gets the executing controller name and action name.
|
||||
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
|
||||
return c.controllerName, c.actionName
|
||||
}
|
||||
|
52
docs.go
Normal file
@ -0,0 +1,52 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
)
|
||||
|
||||
var GlobalDocApi map[string]interface{}
|
||||
|
||||
func init() {
|
||||
if EnableDocs {
|
||||
GlobalDocApi = make(map[string]interface{})
|
||||
}
|
||||
}
|
||||
|
||||
func serverDocs(ctx *context.Context) {
|
||||
var obj interface{}
|
||||
if splat := ctx.Input.Param(":splat"); splat == "" {
|
||||
obj = GlobalDocApi["Root"]
|
||||
} else {
|
||||
if v, ok := GlobalDocApi[splat]; ok {
|
||||
obj = v
|
||||
}
|
||||
}
|
||||
if obj != nil {
|
||||
bt, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
ctx.Output.SetStatus(504)
|
||||
return
|
||||
}
|
||||
ctx.Output.Header("Content-Type", "application/json;charset=UTF-8")
|
||||
ctx.Output.Header("Access-Control-Allow-Origin", "*")
|
||||
ctx.Output.Body(bt)
|
||||
return
|
||||
}
|
||||
ctx.Output.SetStatus(404)
|
||||
}
|
102
docs/en/API.md
@ -1,102 +0,0 @@
|
||||
# Getting start with API application development
|
||||
Go is very good for developing API applications which I think is the biggest strength compare to other dynamic languages. Beego provides powerful and quick setup tool for developing API applications, which gives you more focus on business logic.
|
||||
|
||||
|
||||
## Quick setup
|
||||
bee can setup a API application very quick by executing commands under any `$GOPATH/src`.
|
||||
|
||||
`bee api beeapi`
|
||||
|
||||
## Application directory structure
|
||||
|
||||
```
|
||||
├── conf
|
||||
│ └── app.conf
|
||||
├── controllers
|
||||
│ └── default.go
|
||||
├── models
|
||||
│ └── object.go
|
||||
└── main.go
|
||||
```
|
||||
|
||||
## Source code explanation
|
||||
|
||||
- app.conf has following configuration options for your API applications:
|
||||
|
||||
- autorender = false // Disable auto-render since API applications don't need.
|
||||
- copyrequestbody = true // RESTFul applications sends raw body instead of form, so we need to read body specifically.
|
||||
|
||||
- main.go is for registering routers of RESTFul.
|
||||
|
||||
beego.RESTRouter("/object", &controllers.ObejctController{})
|
||||
|
||||
Match rules as follows:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>URL</th> <th>HTTP Verb</th> <th>Functionality</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object</td> <td>POST</td> <td>Creating Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>GET</td> <td>Retrieving Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>PUT</td> <td>Updating Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object</td> <td>GET</td> <td>Queries</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>DELETE</td> <td>Deleting Objects</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
- ObejctController implemented corresponding methods:
|
||||
|
||||
type ObejctController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *ObejctController) Post(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Get(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Put(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Delete(){
|
||||
|
||||
}
|
||||
|
||||
- models implemented corresponding object operation for adding, deleting, updating and getting.
|
||||
|
||||
## Test
|
||||
|
||||
- Add a new object:
|
||||
|
||||
curl -X POST -d '{"Score":1337,"PlayerName":"Sean Plott"}' http://127.0.0.1:8080/object
|
||||
|
||||
Returns a corresponding objectID:astaxie1373349756660423900
|
||||
|
||||
- Query a object:
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
- Query all objects:
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object`
|
||||
|
||||
- Update a object:
|
||||
|
||||
`curl -X PUT -d '{"Score":10000}'http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
- Delete a object:
|
||||
|
||||
`curl -X DELETE http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
@ -1,46 +0,0 @@
|
||||
## What is hot update?
|
||||
|
||||
If you have used nginx, you may know that nginx supports hot update, which means you can update your nginx without stopping and restarting it. It serves old connections with old version, and accepts new connections with new version. Notice that hot compiling is different from hot update, where hot compiling is monitoring your source files and recompile them when the content changes, it requires stop and restart your applications, `bee start` is a tool for hot compiling.
|
||||
|
||||
|
||||
## Is hot update necessary?
|
||||
|
||||
Some people says that hot update is not as useful as its cool name. In my opinion, this is absolutely necessary because zero-down server is our goal for our services. Even though sometimes some errors or hardware problems may occur, but it belongs to design of high availability, don't mix them up. Service update is a known issue, so we need to fix this problem.
|
||||
|
||||
|
||||
## How Beego support hot update?
|
||||
|
||||
The basic principle of hot update: main process fork a process, and child process execute corresponding programs. So what happens? We know that after forked a process, main process will have all handles, data and stack, etc, but all handles are saved in `CloseOnExec`, so all copied handles will be closed when you execute it unless you clarify this, and we need child process to reuse the handle of `net.Listener`. Once a process calls exec functions, it is "dead", system replaces it with new code. The only thing it left is the process ID, which is the same number but it is a new program after executed.
|
||||
|
||||
Therefore, the first thing we need to do is that let child process fork main process and through `os.StartProcess` to append files that contains handle that is going to be inherited.
|
||||
|
||||
The second step is that we hope child process can start listening from same handle, so we can use `net.FileListener` to achieve this goal. Here we also need FD of this file, so we need to add a environment variable to set this FD before we start child process.
|
||||
|
||||
The final step is that we want to serve old connections with old version of application, and serve new connections with new version. So how can we know if there is any old connections? To do this, we have to record all connections, then we are able to know. Another problem is that how to let new application to accept connection? Because two versions of applications are listening to same port, they get connection request randomly, so we just close old accept function, and it will get error in `l.Accept`.
|
||||
|
||||
Above are three problems that we need to solve, you can see my code logic for specific implementation.
|
||||
|
||||
|
||||
## Show time
|
||||
|
||||
1. Write code in your Get method:
|
||||
|
||||
func (this *MainController) Get() {
|
||||
a, _ := this.GetInt("sleep")
|
||||
time.Sleep(time.Duration(a) * time.Second)
|
||||
this.Ctx.WriteString("ospid:" + strconv.Itoa(os.Getpid()))
|
||||
}
|
||||
|
||||
2. Open two terminals:
|
||||
|
||||
One execute: ` ps -ef|grep <application name>`
|
||||
|
||||
Another one execute: `curl "http://127.0.0.1:8080/?sleep=20"`
|
||||
|
||||
3. Hot update
|
||||
|
||||
`kill -HUP <PID>`
|
||||
|
||||
4. Open a terminal to request connection: `curl "http://127.0.0.1:8080/?sleep=0"`
|
||||
|
||||
As you will see, the first request will wait for 20 seconds, but it's served by old process; after hot update, the first request will print old process ID, but the second request will print new process ID.
|
@ -1,26 +0,0 @@
|
||||
# Installation
|
||||
|
||||
Beego is a simple web framework, but it uses many third-party packages, so you have to install all dependency packages also.
|
||||
|
||||
- Before anything you do, you have to check that you installed Go in your computer, see more detail about Go installation in my book: [Chapter 1](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/01.1.md)
|
||||
- Use `go get ` to install Beego:
|
||||
|
||||
go get github.com/astaxie/beego
|
||||
|
||||
- Install bee tools for fast-develop Beego applications:
|
||||
|
||||
go get github.com/astaxie/bee
|
||||
|
||||
Good job, you're ready to Beego with powerful bee tools!
|
||||
|
||||

|
||||
|
||||
Beego has following dependency packages:
|
||||
|
||||
- Session module: [github.com/astaxie/beego/session](https://github.com/astaxie/beego/session)
|
||||
- To support redis engine: [github.com/garyburd/redigo/redis](https://github.com/garyburd/redigo/redis)
|
||||
- To support mysql engine: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
|
||||
- To support markdown as template function: [github.com/russross/blackfriday](https://github.com/russross/blackfriday)
|
||||
|
||||
- [Introduction](README.md)
|
||||
- [Quick start](Quickstart.md)
|
@ -1,60 +0,0 @@
|
||||
# Beego
|
||||
|
||||
Beego is a lightweight, open source, non-blocking and scalable web framework for the Go programming language. It's like tornado in Python. This web framework has already been using for building web server and tools in SNDA's CDN system. Documentation and downloads available at [http://astaxie.github.com/beego](http://astaxie.github.com/beego)
|
||||
|
||||
It has following main features:
|
||||
|
||||
- Supports MVC model, you only need to focus on logic and implementation methods.
|
||||
- Supports websocket, use customized handlers to integrate sockjs.
|
||||
- Supports customized router rules, including regex and semanteme.
|
||||
- Session integration, supports memory, file, redis, mysql, etc.
|
||||
- Automated parsing user form, you can get data very easy.
|
||||
- Log level system, easy to record debugging and deployment logs.
|
||||
- Use configuration file (.ini) to customized your system.
|
||||
- Use built-in templates in Go, and it provides much more useful functions which are commonly used in web development.
|
||||
|
||||
The working principles of Beego as follows:
|
||||
|
||||

|
||||
|
||||
Beego is licensed under the Apache Licence, Version 2.0
|
||||
(http://www.apache.org/licenses/LICENSE-2.0.html).
|
||||
|
||||
|
||||
# Simple example
|
||||
|
||||
The following example prints string "Hello world" to your browser, it shows how easy to build a web application with Beego.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Ctx.WriteString("hello world")
|
||||
}
|
||||
|
||||
func main() {
|
||||
beego.Router("/", &MainController{})
|
||||
beego.Run()
|
||||
}
|
||||
|
||||
|
||||
# Handbook
|
||||
|
||||
- [Purposes](Why.md)
|
||||
- [Installation](Install.md)
|
||||
- [Quick start](Quickstart.md)
|
||||
- [Step by step](Tutorial.md)
|
||||
- [Real world usage](Application.md)
|
||||
- [Hot update](HotUpdate.md)
|
||||
|
||||
|
||||
# Documentation
|
||||
|
||||
[Go Walker](http://gowalker.org/github.com/astaxie/beego)
|
@ -1,36 +0,0 @@
|
||||
## Supervisord
|
||||
|
||||
[Supervisord](http://supervisord.org/) will make sure your web app is always up.
|
||||
|
||||
1. Installation
|
||||
|
||||
wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
|
||||
|
||||
sh setuptools-0.6c11-py2.7.egg
|
||||
|
||||
easy_install supervisor
|
||||
|
||||
echo_supervisord_conf >/etc/supervisord.conf
|
||||
|
||||
mkdir /etc/supervisord.conf.d
|
||||
|
||||
2. Configure `/etc/supervisord.conf`
|
||||
|
||||
[include]
|
||||
files = /etc/supervisord.conf.d/*.conf
|
||||
|
||||
3. Add new application
|
||||
|
||||
cd /etc/supervisord.conf.d
|
||||
vim beepkg.conf
|
||||
|
||||
Configuration file:
|
||||
|
||||
[program:beepkg]
|
||||
directory = /opt/app/beepkg
|
||||
command = /opt/app/beepkg/beepkg
|
||||
autostart = true
|
||||
startsecs = 5
|
||||
user = root
|
||||
redirect_stderr = true
|
||||
stdout_logfile = /var/log/supervisord/beepkg.log
|
@ -1,19 +0,0 @@
|
||||
# 一步一步跟我写博客
|
||||
|
||||
|
||||
## 创建项目
|
||||
|
||||
|
||||
## 数据库结构设计
|
||||
|
||||
|
||||
## 控制器设计
|
||||
|
||||
|
||||
## 模板设计
|
||||
|
||||
|
||||
## 用户登陆退出
|
||||
|
||||
|
||||
## 数据库操作
|
@ -1,20 +0,0 @@
|
||||
# Design purposes and ideas
|
||||
|
||||
People may ask me why I want to build a new web framework rather than use other good ones. I know there are many excellent web frameworks on the internet and almost all of them are open source, and I have my reasons to do this.
|
||||
|
||||
Remember when I was writing the book about how to build web applications with Go, I just wanted to tell people what were my valuable experiences with Go in web development, especially I have been working with PHP and Python for almost ten years. At first, I didn't realize that a small web framework can give great help to web developers when they are learning to build web applications in a new programming language, and it also helps people more by studying its source code. Finally, I decided to write a open source web framework called Beego as supporting materiel for my book.
|
||||
|
||||
I used to use CI in PHP and tornado in Python, there are both lightweight, so they has following advantages:
|
||||
|
||||
1. Save time for handling general problems, I only need to care about logic part.
|
||||
2. Learn more about languages by studying their source code, it's not hard to read and understand them because they are both lightweight frameworks.
|
||||
3. It's quite easy to make secondary development of these frameworks for specific purposes.
|
||||
|
||||
Those reasons are my original intention of implementing Beego, and used two chapters in my book to introduce and design this lightweight web framework in Go.
|
||||
|
||||
Then I started to design logic execution of Beego. Because Go and Python have somewhat similar, I referenced some ideas from tornado to design Beego. As you can see, there is no different between Beego and tornado in RESTful processing; they both use GET, POST or some other methods to implement RESTful. I took some ideas from [https://github.com/drone/routes](https://github.com/drone/routes) at the beginning of designing routes. It uses regular expression in route rules processing, which is an excellent idea that to make up for the default Mux router function in Go. However, I have to design my own interface in order to implement RESTful and use inherited ideas in Python.
|
||||
|
||||
The controller is the most important part of whole MVC model, and Beego uses the interface and ideas I said above for the controller. Although I haven't decided to have to design the model part, everyone is welcome to implement data management by referencing Beedb, my another open source project. I simply adopt Go built-in template engine for the view part, but add more commonly used functions as template functions. This is how a simple web framework looks like, but I'll keep working on form processing, session handling, log recording, configuration, automated operation, etc, to build a simple but complete web framework.
|
||||
|
||||
- [Introduction](README.md)
|
||||
- [Installation](Install.md)
|
Before Width: | Height: | Size: 78 KiB |
Before Width: | Height: | Size: 60 KiB |
Before Width: | Height: | Size: 68 KiB |
106
docs/zh/API.md
@ -1,106 +0,0 @@
|
||||
# API应用开发入门
|
||||
Go是非常适合用来开发API应用的,而且我认为也是Go相对于其他动态语言的最大优势应用。beego在开发API应用方面提供了非常强大和快速的工具,方便用户快速的建立API应用原型,专心业务逻辑就行了。
|
||||
|
||||
|
||||
## 快速建立原型
|
||||
bee快速开发工具提供了一个API应用建立的工具,在gopath/src下的任意目录执行如下命令就可以快速的建立一个API应用:
|
||||
|
||||
`bee api beeapi`
|
||||
|
||||
## 应用的目录结构
|
||||
应用的目录结构如下所示:
|
||||
|
||||
```
|
||||
├── conf
|
||||
│ └── app.conf
|
||||
├── controllers
|
||||
│ └── default.go
|
||||
├── models
|
||||
│ └── object.go
|
||||
└── main.go
|
||||
```
|
||||
|
||||
## 源码解析
|
||||
|
||||
- app.conf里面主要针对API的配置如下:
|
||||
|
||||
autorender = false //API应用不需要模板渲染,所以关闭自动渲染
|
||||
|
||||
copyrequestbody = true //RESTFul应用发送信息的时候是raw body,而不是普通的form表单,所以需要额外的读取body信息
|
||||
|
||||
- main.go文件主要针对RESTFul的路由注册
|
||||
|
||||
`beego.RESTRouter("/object", &controllers.ObejctController{})`
|
||||
|
||||
这个路由可以匹配如下的规则
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>URL</th> <th>HTTP Verb</th> <th>Functionality</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object</td> <td>POST</td> <td>Creating Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>GET</td> <td>Retrieving Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>PUT</td> <td>Updating Objects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object</td> <td>GET</td> <td>Queries</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>/object/objectId</td> <td>DELETE</td> <td>Deleting Objects</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
- ObejctController实现了对应的方法:
|
||||
|
||||
```
|
||||
type ObejctController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *ObejctController) Post(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Get(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Put(){
|
||||
|
||||
}
|
||||
|
||||
func (this *ObejctController) Delete(){
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
- models里面实现了对应操作对象的增删改取等操作
|
||||
|
||||
## 测试
|
||||
|
||||
- 添加一个对象:
|
||||
|
||||
`curl -X POST -d '{"Score":1337,"PlayerName":"Sean Plott"}' http://127.0.0.1:8080/object`
|
||||
|
||||
返回一个相应的objectID:astaxie1373349756660423900
|
||||
|
||||
- 查询一个对象
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
- 查询全部的对象
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object`
|
||||
|
||||
- 更新一个对象
|
||||
|
||||
`curl -X PUT -d '{"Score":10000}'http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
- 删除一个对象
|
||||
|
||||
`curl -X DELETE http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
@ -1,23 +0,0 @@
|
||||
# beego案例
|
||||
|
||||
- 短域名服务
|
||||
|
||||
使用beego开发了一个类似bitly的短域名服务,提供盛大内部项目使用,目前一台机器:32G内存、8核、centos64
|
||||
redis数据库,数据量在1500w多点,从2012年8月份运行至今没有出现过问题
|
||||
- 政府合作项目
|
||||
|
||||
使用beego提供系统级别服务,监控继承电路板信号,智能分析nginx配置,提供大数据量的下载调度
|
||||
|
||||
- 内部监控系统
|
||||
目前这个项目还在开发中,主要是利用beego做两个服务,一个是服务器端,收集信息,一个是客户端,收集信息并上报给服务器端,如果和服务端断开,那么本地可以暂存数据,防止数据丢失,同时还支持类似pupput的功能,支持程序自动更新(重启功能,不支持热更新)
|
||||
|
||||
- 日志分析系统
|
||||
以前采用hadoop来分析日志的来源和省份信息,发现hadoop分析这么大的数据,性能不是很好,延迟比较大,目前采用自己的一套架构,squid日志每小时分割上报,每小时对日志进行分割,然后进行UV、PV、省份、运营商、浏览器、数据量等的分析,同时把日志进行按域名分割,提供用户原始日志下载
|
||||
|
||||
- 下载分发系统
|
||||
架构暂时不好公布,我们提供文件下载的智能分发,但是从文件上传到下发到每一台服务器,以前采用BT的方式,性能不是很好,目前采用新的架构,性能提升十几倍
|
||||
|
||||
- 基于微信的提醒助手
|
||||
开源在github上
|
||||
|
||||
- 视频直播调度器
|
@ -1,45 +0,0 @@
|
||||
## 热升级是什么?
|
||||
|
||||
热升级是什么呢?了解nginx的同学都知道,nginx是支持热升级的,可以用老进程服务先前链接的链接,使用新进程服务新的链接,即在不停止服务的情况下完成系统的升级与运行参数修改。那么热升级和热编译是不同的概念,热编译是通过监控文件的变化重新编译,然后重启进程,例如bee start就是这样的工具
|
||||
|
||||
|
||||
## 热升级有必要吗?
|
||||
|
||||
很多人认为HTTP的应用有必要支持热升级吗?那么我可以很负责的说非常有必要,不中断服务始终是我们所追求的目标,虽然很多人说可能服务器会坏掉等等,这个是属于高可用的设计范畴,不要搞混了,这个是可预知的问题,所以我们需要避免这样的升级带来的用户不可用。你还在为以前升级搞到凌晨升级而烦恼嘛?那么现在就赶紧拥抱热升级吧。
|
||||
|
||||
|
||||
## beego如何支持热升级
|
||||
热升级的原理基本上就是:主进程fork一个进程,然后子进程exec相应的程序。那么这个过程中发生了什么呢?我们知道进程fork之后会把主进程的所有句柄、数据和堆栈继承过来、但是里面所有的句柄存在一个叫做CloseOnExec,也就是执行exec的时候,copy的所有的句柄都被关闭了,除非特别申明,而我们期望的是子进程能够复用主进程的net.Listener的句柄。一个进程一旦调用exec类函数,它本身就"死亡"了,系统把代码段替换成新的程序的代码,废弃原有的数据段和堆栈段,并为新程序分配新的数据段与堆栈段,唯一留下的,就是进程号,也就是说,对系统而言,还是同一个进程,不过已经是另一个程序了。
|
||||
|
||||
那么我们要做的第一步就是让子进程继承主进程的这个句柄,我们可以通过os.StartProcess的参数来附加Files,把需要继承的句柄写在里面。
|
||||
|
||||
第二步就是我们希望子进程能够从这个句柄启动监听,还好Go里面支持net.FileListener,直接从句柄来监听,但是我们需要子进程知道这个FD,所以在启动子进程的时候我们设置了一个环境变量设置这个FD。
|
||||
|
||||
第三步就是我们期望老的链接继续服务完,而新的链接采用新的进程,这里面有两个细节,第一就是老的链接继续服务,那么我们怎么知道有老链接存在?所以我们必须每次接收一个链接记录一下,这样我们就知道还存在没有服务完的链接,第二就是怎么让老进程停止接收数据,让新进程接收数据呢?大家都监听在同一个端口,理论上是随机来接收的,所以这里我们只要关闭老的链接的接收就行,这样就会使得在l.Accept的时候报错。
|
||||
|
||||
上面是我们需要解决的三个方面的问题,具体的实现大家可以看我实现的代码逻辑。
|
||||
|
||||
|
||||
## 如何演示热升级
|
||||
|
||||
1. 编写代码,在beego应用的控制器中Get方法实现大概如下:
|
||||
|
||||
func (this *MainController) Get() {
|
||||
a, _ := this.GetInt("sleep")
|
||||
time.Sleep(time.Duration(a) * time.Second)
|
||||
this.Ctx.WriteString("ospid:" + strconv.Itoa(os.Getpid()))
|
||||
}
|
||||
|
||||
2. 打开两个终端
|
||||
|
||||
一个终端输入:` ps -ef|grep 应用名`
|
||||
|
||||
一个终端输入请求:`curl "http://127.0.0.1:8080/?sleep=20"`
|
||||
|
||||
3. 热升级
|
||||
|
||||
`kill -HUP 进程ID`
|
||||
|
||||
4. 打开一个终端输入请求:`curl "http://127.0.0.1:8080/?sleep=0"`
|
||||
|
||||
我们可以看到这样的结果,第一个请求等待20s,但是处理他的是老的进程,热升级之后,第一个请求还在执行,最后会输出老的进程ID,而第二次请求,输出的是新的进程ID
|
@ -1,78 +0,0 @@
|
||||
## 方便的http客户端
|
||||
我们经常会使用Go来请求其他API应用,例如你使用beego开发了一个RESTFul的API应用,那么如果来请求呢?当然可以使用`http.Client`来实现,但是需要自己来操作很多步骤,自己需要考虑很多东西,所以我就基于net下的一些包实现了这个简便的http客户端工具。
|
||||
|
||||
该工具的主要特点:
|
||||
|
||||
- 链式操作
|
||||
- 超时控制
|
||||
- 方便的解析
|
||||
- 可控的debug
|
||||
|
||||
## 例子
|
||||
我们上次开发的RESTful应用,最后我写过如何通过curl来进行测试,那么下面一一对每个操作如何用httplib来操作进行展示
|
||||
|
||||
- 添加一个对象:
|
||||
|
||||
`curl -X POST -d '{"Score":1337,"PlayerName":"Sean Plott"}' http://127.0.0.1:8080/object`
|
||||
|
||||
返回一个相应的objectID:astaxie1373349756660423900
|
||||
|
||||
str,err:=beego.Post("http://127.0.0.1:8080/object").Body(`{"Score":1337,"PlayerName":"Sean Plott"}`).String()
|
||||
if err != nil{
|
||||
println(err)
|
||||
}
|
||||
|
||||
- 查询一个对象
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
var object Obeject
|
||||
err:=beego.Get("http://127.0.0.1:8080/object/astaxie1373349756660423900").ToJson(&object)
|
||||
if err != nil{
|
||||
println(err)
|
||||
}
|
||||
|
||||
- 查询全部的对象
|
||||
|
||||
`curl -X GET http://127.0.0.1:8080/object`
|
||||
|
||||
var objects []Object
|
||||
err:=beego.Get("http://127.0.0.1:8080/object").ToJson(&objects)
|
||||
if err != nil{
|
||||
println(err)
|
||||
}
|
||||
|
||||
- 更新一个对象
|
||||
|
||||
`curl -X PUT -d '{"Score":10000}'http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
str,err:=beego.Put("http://127.0.0.1:8080/object/astaxie1373349756660423900").Body(`{"Score":10000}`).String()
|
||||
if err != nil{
|
||||
println(err)
|
||||
}
|
||||
|
||||
- 删除一个对象
|
||||
|
||||
`curl -X DELETE http://127.0.0.1:8080/object/astaxie1373349756660423900`
|
||||
|
||||
str,er:=beego.Delete("http://127.0.0.1:8080/object/astaxie1373349756660423900").String()
|
||||
if err != nil{
|
||||
println(err)
|
||||
}
|
||||
|
||||
## 开启调试模式
|
||||
用户可以开启调试打印request信息,默认是关闭模式
|
||||
|
||||
beego.Post(url).Debug(true)
|
||||
|
||||
## ToFile、ToXML、ToJson
|
||||
上面我演示了Json的解析,其实还有直接保存为文件的ToFile操作,解析XML的ToXML操作
|
||||
|
||||
|
||||
## 设置链接超时和读写超时
|
||||
默认都设置为60秒,用户可以通过函数来设置相应的超时时间
|
||||
|
||||
beego.Get(url).SetTimeout(100*time.Second,100*time.Second)
|
||||
|
||||
|
||||
更加详细的请参考[API接口](http://gowalker.org/github.com/astaxie/beego)
|
@ -1,31 +0,0 @@
|
||||
# 安装入门
|
||||
|
||||
beego虽然是一个简单的框架,但是其中用到了很多第三方的包,所以在你安装beego的过程中Go会自动安装其他关联的包。
|
||||
|
||||
- 当然第一步你需要安装Go,如何安装Go请参考我的书[第一章](https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/01.1.md)
|
||||
|
||||
- 安装beego
|
||||
|
||||
go get github.com/astaxie/beego
|
||||
|
||||
- 安装bee工具,这个工具可以用来快速的建立beego的应用
|
||||
|
||||
go get github.com/astaxie/bee
|
||||
|
||||
这样就完成了beego的安装,你就可以开始开发了,可以通过bee工具来创建beego项目
|
||||
|
||||

|
||||
|
||||
>beego依赖的第三方包有如下:
|
||||
|
||||
> - session模块:github.com/astaxie/beego/session
|
||||
|
||||
|
||||
> - session模块中支持redis引擎:github.com/garyburd/redigo/redis
|
||||
|
||||
> - session模块中支持mysql引擎:github.com/go-sql-driver/mysql
|
||||
|
||||
|
||||
|
||||
- [beego介绍](README.md)
|
||||
- [快速入门](Quickstart.md)
|
@ -1,54 +0,0 @@
|
||||
# beego介绍
|
||||
beego是一个类似tornado的Go应用框架,采用了RESTFul的方式来实现应用框架,是一个超轻量级的框架,主要有如下的特点:
|
||||
|
||||
- 支持MVC的方式,用户只需要关注逻辑,实现对应method的方法即可
|
||||
- 支持websocket,通过自定义Handler实现集成sockjs等方式实现
|
||||
- 支持自定义路由,支持各种方式的路由,正则、语意均支持,类似sinatra
|
||||
- session集成,支持memory、file、redis、mysql等存储
|
||||
- 表单处理自动化解析,用户可以很方便的获取数据
|
||||
- 日志分级系统,用户可以很方便的调试和应用日志记录
|
||||
- 自定义配置文件,支持ini格式的文本配置,可以方便的在系统中调参数
|
||||
- 采用了Go内置的模板,集成实现了很多Web开发中常用的函数
|
||||
|
||||
执行过程如下所示:
|
||||

|
||||
|
||||
# beego简单例子
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Ctx.WriteString("hello world")
|
||||
}
|
||||
|
||||
func main() {
|
||||
beego.Router("/", &MainController{})
|
||||
beego.Run()
|
||||
}
|
||||
|
||||
|
||||
# beego 指南
|
||||
|
||||
* [为什么设计beego](Why.md)
|
||||
* [安装入门](Install.md)
|
||||
* [快速入门](Quickstart.md)
|
||||
* [一步一步开发应用](Tutorial.md)
|
||||
* [beego案例](Application.md)
|
||||
* [热升级](HotUpdate.md)
|
||||
* [API应用开发入门](API.md)
|
||||
* [HTTPLIB客户端](HttpLib.md)
|
||||
|
||||
|
||||
# API接口
|
||||
|
||||
API对于我们平时开发应用非常有用,用于查询一些开发的函数,godoc做的非常好了
|
||||
|
||||
[Go Walker](http://gowalker.org/github.com/astaxie/beego)
|
@ -1,34 +0,0 @@
|
||||
## supervisord安装
|
||||
|
||||
1. setuptools安装
|
||||
|
||||
wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
|
||||
|
||||
sh setuptools-0.6c11-py2.7.egg
|
||||
|
||||
easy_install supervisor
|
||||
|
||||
echo_supervisord_conf >/etc/supervisord.conf
|
||||
|
||||
mkdir /etc/supervisord.conf.d
|
||||
|
||||
2. 修改配置/etc/supervisord.conf
|
||||
|
||||
[include]
|
||||
files = /etc/supervisord.conf.d/*.conf
|
||||
|
||||
3. 新建管理的应用
|
||||
|
||||
cd /etc/supervisord.conf.d
|
||||
vim beepkg.conf
|
||||
|
||||
配置文件:
|
||||
|
||||
[program:beepkg]
|
||||
directory = /opt/app/beepkg
|
||||
command = /opt/app/beepkg/beepkg
|
||||
autostart = true
|
||||
startsecs = 5
|
||||
user = root
|
||||
redirect_stderr = true
|
||||
stdout_logfile = /var/log/supervisord/beepkg.log
|
@ -1,19 +0,0 @@
|
||||
# 一步一步跟我写博客
|
||||
|
||||
|
||||
## 创建项目
|
||||
|
||||
|
||||
## 数据库结构设计
|
||||
|
||||
|
||||
## 控制器设计
|
||||
|
||||
|
||||
## 模板设计
|
||||
|
||||
|
||||
## 用户登陆退出
|
||||
|
||||
|
||||
## 数据库操作
|
@ -1,20 +0,0 @@
|
||||
# 为什么设计beego和设计的思路
|
||||
|
||||
很多人会问为什么有那么多框架了,还要去实现一个框架呢?是不是大家都有自己实现框架的情节,我可以肯定的说不是,我说一下为什么设计beego的初衷
|
||||
|
||||
还记得当初写书的时候,我纯粹只是想把自己在学习Go语言中的一些体会写出来,由于我以前主要从事PHP和python的Web开发,所以想写一本Go如何来做Web实战的经验,刚开始的时候书的目录里面根本就没有框架实现这些章节,是写到后来发现其实对于Web开发者来说,一个微型的框架是非常有利于大家学习一个语言和快速进行应用开发的。
|
||||
|
||||
我以前经常用PHP的CI框架和python的tornado框架,这些框架都是非常轻量级的,轻量级就有利于我们:
|
||||
|
||||
- 第一节约我开发中一些常见问题的处理,用户只需要关注逻辑层面的东西
|
||||
- 第二轻量级以至于他们的代码也是非常清晰的,我们可以通过阅读他们的源码来学习和体会这门语言的一些细节
|
||||
- 第三对于项目开发者来说可以基于这些框架进行改造以适应自己的项目,从而实现二次框架的创造
|
||||
|
||||
所以基于上面这些的考虑,我就想实现一个类似这些语言的轻量级框架,所以我就在书的最后设计了两个章节来介绍和实现beego框架,这就是当初写beego框架的初衷。
|
||||
|
||||
有了这个初衷之后我就开始设计beego的执行逻辑,由于Go语言和python的思路比较接近,所以我就参考了tornado的思路来设计beego,你可以看到beego的RESTful处理完全和tornado的处理是一模一样的,通过controller层的Get、Post等方法来实现RESTFul。刚开始的时候路由参考的是[https://github.com/drone/routes](https://github.com/drone/routes),这个的正则处理我觉得非常好,弥补了Go语言默认Mux中的路由功能,但是由于要采用RESTFul方式,所以我自己设计了一个接口,实现python中的继承思想。
|
||||
|
||||
整个的MVC逻辑中C是最重要的部分,这一块采用了我上面说的接口方式,M模块目前我还没想好怎么做,但是大家可以参考我的另一个开源项目beedb来实现数据的管理,V这一块目前采用了Go语言自带的模板引擎,但是实现了很多方便的模板函数。这样一个简易的框架就完成了,然后我就不断的完善周边的功能,包括表单处理、session处理、日志处理、配置处理、自动化运行等功能。
|
||||
|
||||
- [beego介绍](README.md)
|
||||
- [安装入门](Install.md)
|
Before Width: | Height: | Size: 33 KiB |
Before Width: | Height: | Size: 78 KiB |
Before Width: | Height: | Size: 60 KiB |
Before Width: | Height: | Size: 68 KiB |
@ -1,25 +1,32 @@
|
||||
// Beego (http://beego.me/)
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
// @authors astaxie
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/example/beeapi/models"
|
||||
)
|
||||
|
||||
type ObejctController struct {
|
||||
type ObjectController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *ObejctController) Post() {
|
||||
func (this *ObjectController) Post() {
|
||||
var ob models.Object
|
||||
json.Unmarshal(this.Ctx.RequestBody, &ob)
|
||||
json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
|
||||
objectid := models.AddOne(ob)
|
||||
this.Data["json"] = "{\"ObjectId\":\"" + objectid + "\"}"
|
||||
this.Data["json"] = map[string]string{"ObjectId": objectid}
|
||||
this.ServeJson()
|
||||
}
|
||||
|
||||
func (this *ObejctController) Get() {
|
||||
objectId := this.Ctx.Params[":objectId"]
|
||||
func (this *ObjectController) Get() {
|
||||
objectId := this.Ctx.Input.Params[":objectId"]
|
||||
if objectId != "" {
|
||||
ob, err := models.GetOne(objectId)
|
||||
if err != nil {
|
||||
@ -34,10 +41,10 @@ func (this *ObejctController) Get() {
|
||||
this.ServeJson()
|
||||
}
|
||||
|
||||
func (this *ObejctController) Put() {
|
||||
objectId := this.Ctx.Params[":objectId"]
|
||||
func (this *ObjectController) Put() {
|
||||
objectId := this.Ctx.Input.Params[":objectId"]
|
||||
var ob models.Object
|
||||
json.Unmarshal(this.Ctx.RequestBody, &ob)
|
||||
json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
|
||||
|
||||
err := models.Update(objectId, ob.Score)
|
||||
if err != nil {
|
||||
@ -48,8 +55,8 @@ func (this *ObejctController) Put() {
|
||||
this.ServeJson()
|
||||
}
|
||||
|
||||
func (this *ObejctController) Delete() {
|
||||
objectId := this.Ctx.Params[":objectId"]
|
||||
func (this *ObjectController) Delete() {
|
||||
objectId := this.Ctx.Input.Params[":objectId"]
|
||||
models.Delete(objectId)
|
||||
this.Data["json"] = "delete success!"
|
||||
this.ServeJson()
|
||||
|
@ -1,3 +1,13 @@
|
||||
// Beego (http://beego.me/)
|
||||
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
|
||||
// @authors astaxie
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
@ -15,6 +25,6 @@ import (
|
||||
// /object/<objectId> DELETE Deleting Objects
|
||||
|
||||
func main() {
|
||||
beego.RESTRouter("/object", &controllers.ObejctController{})
|
||||
beego.RESTRouter("/object", &controllers.ObjectController{})
|
||||
beego.Run()
|
||||
}
|
||||
|
@ -1,3 +1,9 @@
|
||||
// Beego (http://beego.me/)
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
// @authors astaxie
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
|
@ -1,42 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/fzzy/sockjs-go/sockjs"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var users *sockjs.SessionPool = sockjs.NewSessionPool()
|
||||
|
||||
func chatHandler(s sockjs.Session) {
|
||||
users.Add(s)
|
||||
defer users.Remove(s)
|
||||
|
||||
for {
|
||||
m := s.Receive()
|
||||
if m == nil {
|
||||
break
|
||||
}
|
||||
fullAddr := s.Info().RemoteAddr
|
||||
addr := fullAddr[:strings.LastIndex(fullAddr, ":")]
|
||||
m = []byte(fmt.Sprintf("%s: %s", addr, m))
|
||||
users.Broadcast(m)
|
||||
}
|
||||
}
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (m *MainController) Get() {
|
||||
m.TplNames = "index.html"
|
||||
}
|
||||
|
||||
func main() {
|
||||
conf := sockjs.NewConfig()
|
||||
sockjshandler := sockjs.NewHandler("/chat", chatHandler, conf)
|
||||
beego.Router("/", &MainController{})
|
||||
beego.RouterHandler("/chat/:info(.*)", sockjshandler)
|
||||
beego.Run()
|
||||
}
|
3
example/chat/conf/app.conf
Normal file
@ -0,0 +1,3 @@
|
||||
appname = chat
|
||||
httpport = 8080
|
||||
runmode = dev
|
20
example/chat/controllers/default.go
Normal file
@ -0,0 +1,20 @@
|
||||
// Beego (http://beego.me/)
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
// @authors Unknwon
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Data["host"] = this.Ctx.Request.Host
|
||||
this.TplNames = "index.tpl"
|
||||
}
|
181
example/chat/controllers/ws.go
Normal file
@ -0,0 +1,181 @@
|
||||
// Beego (http://beego.me/)
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
// @authors Unknwon
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
// Time allowed to write a message to the client.
|
||||
writeWait = 10 * time.Second
|
||||
|
||||
// Time allowed to read the next message from the client.
|
||||
readWait = 60 * time.Second
|
||||
|
||||
// Send pings to client with this period. Must be less than readWait.
|
||||
pingPeriod = (readWait * 9) / 10
|
||||
|
||||
// Maximum message size allowed from client.
|
||||
maxMessageSize = 512
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
go h.run()
|
||||
}
|
||||
|
||||
// connection is an middleman between the websocket connection and the hub.
|
||||
type connection struct {
|
||||
username string
|
||||
|
||||
// The websocket connection.
|
||||
ws *websocket.Conn
|
||||
|
||||
// Buffered channel of outbound messages.
|
||||
send chan []byte
|
||||
}
|
||||
|
||||
// readPump pumps messages from the websocket connection to the hub.
|
||||
func (c *connection) readPump() {
|
||||
defer func() {
|
||||
h.unregister <- c
|
||||
c.ws.Close()
|
||||
}()
|
||||
c.ws.SetReadLimit(maxMessageSize)
|
||||
c.ws.SetReadDeadline(time.Now().Add(readWait))
|
||||
for {
|
||||
op, r, err := c.ws.NextReader()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch op {
|
||||
case websocket.PongMessage:
|
||||
c.ws.SetReadDeadline(time.Now().Add(readWait))
|
||||
case websocket.TextMessage:
|
||||
message, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
h.broadcast <- []byte(c.username + "_" + time.Now().Format("15:04:05") + ":" + string(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// write writes a message with the given opCode and payload.
|
||||
func (c *connection) write(opCode int, payload []byte) error {
|
||||
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
return c.ws.WriteMessage(opCode, payload)
|
||||
}
|
||||
|
||||
// writePump pumps messages from the hub to the websocket connection.
|
||||
func (c *connection) writePump() {
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer func() {
|
||||
ticker.Stop()
|
||||
c.ws.Close()
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
if !ok {
|
||||
c.write(websocket.CloseMessage, []byte{})
|
||||
return
|
||||
}
|
||||
if err := c.write(websocket.TextMessage, message); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type hub struct {
|
||||
// Registered connections.
|
||||
connections map[*connection]bool
|
||||
|
||||
// Inbound messages from the connections.
|
||||
broadcast chan []byte
|
||||
|
||||
// Register requests from the connections.
|
||||
register chan *connection
|
||||
|
||||
// Unregister requests from connections.
|
||||
unregister chan *connection
|
||||
}
|
||||
|
||||
var h = &hub{
|
||||
broadcast: make(chan []byte, maxMessageSize),
|
||||
register: make(chan *connection, 1),
|
||||
unregister: make(chan *connection, 1),
|
||||
connections: make(map[*connection]bool),
|
||||
}
|
||||
|
||||
func (h *hub) run() {
|
||||
for {
|
||||
select {
|
||||
case c := <-h.register:
|
||||
h.connections[c] = true
|
||||
case c := <-h.unregister:
|
||||
delete(h.connections, c)
|
||||
close(c.send)
|
||||
case m := <-h.broadcast:
|
||||
for c := range h.connections {
|
||||
select {
|
||||
case c.send <- m:
|
||||
default:
|
||||
close(c.send)
|
||||
delete(h.connections, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type WSController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
func (this *WSController) Get() {
|
||||
ws, err := upgrader.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request,nil)
|
||||
if _, ok := err.(websocket.HandshakeError); ok {
|
||||
http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
|
||||
return
|
||||
} else if err != nil {
|
||||
return
|
||||
}
|
||||
c := &connection{send: make(chan []byte, 256), ws: ws, username: randomString(10)}
|
||||
h.register <- c
|
||||
go c.writePump()
|
||||
c.readPump()
|
||||
}
|
||||
|
||||
func randomString(l int) string {
|
||||
bytes := make([]byte, l)
|
||||
for i := 0; i < l; i++ {
|
||||
bytes[i] = byte(randInt(65, 90))
|
||||
}
|
||||
return string(bytes)
|
||||
}
|
||||
|
||||
func randInt(min int, max int) int {
|
||||
return min + rand.Intn(max-min)
|
||||
}
|
17
example/chat/main.go
Normal file
@ -0,0 +1,17 @@
|
||||
// Beego (http://beego.me/)
|
||||
// @description beego is an open-source, high-performance web framework for the Go programming language.
|
||||
// @link http://github.com/astaxie/beego for the canonical source repository
|
||||
// @license http://github.com/astaxie/beego/blob/master/LICENSE
|
||||
// @authors Unknwon
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/example/chat/controllers"
|
||||
)
|
||||
|
||||
func main() {
|
||||
beego.Router("/", &controllers.MainController{})
|
||||
beego.Router("/ws", &controllers.WSController{})
|
||||
beego.Run()
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
|
||||
<script src="http://cdn.sockjs.org/sockjs-0.3.4.min.js"></script>
|
||||
<script>
|
||||
$(function() {
|
||||
var conn = null;
|
||||
|
||||
function log(msg) {
|
||||
var control = $('#log');
|
||||
control.html(control.html() + msg + '<br/>');
|
||||
control.scrollTop(control.scrollTop() + 1000);
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
if (conn != null) {
|
||||
log('Disconnecting...');
|
||||
|
||||
conn.close();
|
||||
conn = null;
|
||||
|
||||
updateUi();
|
||||
}
|
||||
}
|
||||
|
||||
function updateUi() {
|
||||
if (conn == null || conn.readyState != SockJS.OPEN) {
|
||||
$('#status').text('disconnected');
|
||||
$('#connect').text('Connect');
|
||||
} else {
|
||||
$('#status').text('connected (' + conn.protocol + ')');
|
||||
$('#connect').text('Disconnect');
|
||||
}
|
||||
}
|
||||
|
||||
$('form').submit(function() {
|
||||
var text = $('#message').val();
|
||||
conn.send(text);
|
||||
$('#message').val('').focus();
|
||||
return false;
|
||||
});
|
||||
|
||||
conn = new SockJS('http://' + window.location.host + '/chat');
|
||||
log('Connecting...');
|
||||
|
||||
conn.onopen = function() {
|
||||
log('Connected.');
|
||||
updateUi();
|
||||
};
|
||||
|
||||
conn.onmessage = function(e) {
|
||||
log(e.data);
|
||||
};
|
||||
|
||||
conn.onclose = function() {
|
||||
log('Disconnected.');
|
||||
conn = null;
|
||||
updateUi();
|
||||
};
|
||||
|
||||
$('#message').val('').focus();
|
||||
});
|
||||
</script>
|
||||
<title>Sockjs-go chat</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Sockjs-go chat</h1>
|
||||
|
||||
<div>
|
||||
Status: <span id="status">disconnected</span>
|
||||
</div>
|
||||
<div id="log" style="width: 60em; height: 20em; overflow:auto; border: 1px solid black">
|
||||
</div>
|
||||
<form id="chatform">
|
||||
<label for="message">Message:</label>
|
||||
<input id="message" type="text" />
|
||||
<input type="submit" value="Send" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
92
example/chat/views/index.tpl
Normal file
@ -0,0 +1,92 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Chat Example</title>
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(function() {
|
||||
|
||||
var conn;
|
||||
var msg = $("#msg");
|
||||
var log = $("#log");
|
||||
|
||||
function appendLog(msg) {
|
||||
var d = log[0]
|
||||
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
|
||||
msg.appendTo(log)
|
||||
if (doScroll) {
|
||||
d.scrollTop = d.scrollHeight - d.clientHeight;
|
||||
}
|
||||
}
|
||||
|
||||
$("#form").submit(function() {
|
||||
if (!conn) {
|
||||
return false;
|
||||
}
|
||||
if (!msg.val()) {
|
||||
return false;
|
||||
}
|
||||
conn.send(msg.val());
|
||||
msg.val("");
|
||||
return false
|
||||
});
|
||||
|
||||
if (window["WebSocket"]) {
|
||||
conn = new WebSocket("ws://{{.host}}/ws");
|
||||
conn.onclose = function(evt) {
|
||||
appendLog($("<div><b>Connection closed.</b></div>"))
|
||||
}
|
||||
conn.onmessage = function(evt) {
|
||||
appendLog($("<div/>").text(evt.data))
|
||||
}
|
||||
} else {
|
||||
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<style type="text/css">
|
||||
html {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: gray;
|
||||
}
|
||||
|
||||
#log {
|
||||
background: white;
|
||||
margin: 0;
|
||||
padding: 0.5em 0.5em 0.5em 0.5em;
|
||||
position: absolute;
|
||||
top: 0.5em;
|
||||
left: 0.5em;
|
||||
right: 0.5em;
|
||||
bottom: 3em;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
#form {
|
||||
padding: 0 0.5em 0 0.5em;
|
||||
margin: 0;
|
||||
position: absolute;
|
||||
bottom: 1em;
|
||||
left: 0px;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="log"></div>
|
||||
<form id="form">
|
||||
<input type="submit" value="Send" />
|
||||
<input type="text" id="msg" size="64"/>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
37
filter.go
Normal file
@ -0,0 +1,37 @@
|
||||
// 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 beego
|
||||
|
||||
// FilterRouter defines filter operation before controller handler execution.
|
||||
// it can match patterned url and do filter function when action arrives.
|
||||
type FilterRouter struct {
|
||||
filterFunc FilterFunc
|
||||
tree *Tree
|
||||
pattern string
|
||||
}
|
||||
|
||||
// ValidRouter check current request is valid for this filter.
|
||||
// if matched, returns parsed params in this request by defined filter router pattern.
|
||||
func (f *FilterRouter) ValidRouter(router string) (bool, map[string]string) {
|
||||
isok, params := f.tree.Match(router)
|
||||
if isok == nil {
|
||||
return false, nil
|
||||
}
|
||||
if isok, ok := isok.(bool); ok {
|
||||
return isok, params
|
||||
} else {
|
||||
return false, nil
|
||||
}
|
||||
}
|
68
filter_test.go
Normal file
@ -0,0 +1,68 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
)
|
||||
|
||||
var FilterUser = func(ctx *context.Context) {
|
||||
ctx.Output.Body([]byte("i am " + ctx.Input.Params[":last"] + ctx.Input.Params[":first"]))
|
||||
}
|
||||
|
||||
func TestFilter(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "/person/asta/Xie", nil)
|
||||
w := httptest.NewRecorder()
|
||||
handler := NewControllerRegister()
|
||||
handler.InsertFilter("/person/:last/:first", BeforeRouter, FilterUser)
|
||||
handler.Add("/person/:last/:first", &TestController{})
|
||||
handler.ServeHTTP(w, r)
|
||||
if w.Body.String() != "i am astaXie" {
|
||||
t.Errorf("user define func can't run")
|
||||
}
|
||||
}
|
||||
|
||||
var FilterAdminUser = func(ctx *context.Context) {
|
||||
ctx.Output.Body([]byte("i am admin"))
|
||||
}
|
||||
|
||||
// Filter pattern /admin/:all
|
||||
// all url like /admin/ /admin/xie will all get filter
|
||||
|
||||
func TestPatternTwo(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "/admin/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
handler := NewControllerRegister()
|
||||
handler.InsertFilter("/admin/?:all", BeforeRouter, FilterAdminUser)
|
||||
handler.ServeHTTP(w, r)
|
||||
if w.Body.String() != "i am admin" {
|
||||
t.Errorf("filter /admin/ can't run")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatternThree(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "/admin/astaxie", nil)
|
||||
w := httptest.NewRecorder()
|
||||
handler := NewControllerRegister()
|
||||
handler.InsertFilter("/admin/:all", BeforeRouter, FilterAdminUser)
|
||||
handler.ServeHTTP(w, r)
|
||||
if w.Body.String() != "i am admin" {
|
||||
t.Errorf("filter /admin/astaxie can't run")
|
||||
}
|
||||
}
|
40
flash.go
@ -1,3 +1,17 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
@ -6,16 +20,19 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FlashData is a tools to maintain data when using across request.
|
||||
type FlashData struct {
|
||||
Data map[string]string
|
||||
}
|
||||
|
||||
// NewFlash return a new empty FlashData struct.
|
||||
func NewFlash() *FlashData {
|
||||
return &FlashData{
|
||||
Data: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// Notice writes notice message to flash.
|
||||
func (fd *FlashData) Notice(msg string, args ...interface{}) {
|
||||
if len(args) == 0 {
|
||||
fd.Data["notice"] = msg
|
||||
@ -24,6 +41,7 @@ func (fd *FlashData) Notice(msg string, args ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Warning writes warning message to flash.
|
||||
func (fd *FlashData) Warning(msg string, args ...interface{}) {
|
||||
if len(args) == 0 {
|
||||
fd.Data["warning"] = msg
|
||||
@ -32,6 +50,7 @@ func (fd *FlashData) Warning(msg string, args ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Error writes error message to flash.
|
||||
func (fd *FlashData) Error(msg string, args ...interface{}) {
|
||||
if len(args) == 0 {
|
||||
fd.Data["error"] = msg
|
||||
@ -40,32 +59,33 @@ func (fd *FlashData) Error(msg string, args ...interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Store does the saving operation of flash data.
|
||||
// the data are encoded and saved in cookie.
|
||||
func (fd *FlashData) Store(c *Controller) {
|
||||
c.Data["flash"] = fd.Data
|
||||
var flashValue string
|
||||
for key, value := range fd.Data {
|
||||
flashValue += "\x00" + key + ":" + value + "\x00"
|
||||
flashValue += "\x00" + key + "\x23" + FlashSeperator + "\x23" + value + "\x00"
|
||||
}
|
||||
c.Ctx.SetCookie("BEEGO_FLASH", url.QueryEscape(flashValue), 0, "/")
|
||||
c.Ctx.SetCookie(FlashName, url.QueryEscape(flashValue), 0, "/")
|
||||
}
|
||||
|
||||
// ReadFromRequest parsed flash data from encoded values in cookie.
|
||||
func ReadFromRequest(c *Controller) *FlashData {
|
||||
flash := &FlashData{
|
||||
Data: make(map[string]string),
|
||||
}
|
||||
if cookie, err := c.Ctx.Request.Cookie("BEEGO_FLASH"); err == nil {
|
||||
vals := strings.Split(cookie.Value, "\x00")
|
||||
flash := NewFlash()
|
||||
if cookie, err := c.Ctx.Request.Cookie(FlashName); err == nil {
|
||||
v, _ := url.QueryUnescape(cookie.Value)
|
||||
vals := strings.Split(v, "\x00")
|
||||
for _, v := range vals {
|
||||
if len(v) > 0 {
|
||||
kv := strings.Split(v, ":")
|
||||
kv := strings.Split(v, "\x23"+FlashSeperator+"\x23")
|
||||
if len(kv) == 2 {
|
||||
flash.Data[kv[0]] = kv[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
//read one time then delete it
|
||||
cookie.MaxAge = -1
|
||||
c.Ctx.Request.AddCookie(cookie)
|
||||
c.Ctx.SetCookie(FlashName, "", -1, "/")
|
||||
}
|
||||
c.Data["flash"] = flash.Data
|
||||
return flash
|
||||
|
54
flash_test.go
Normal file
@ -0,0 +1,54 @@
|
||||
// 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 beego
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type TestFlashController struct {
|
||||
Controller
|
||||
}
|
||||
|
||||
func (this *TestFlashController) TestWriteFlash() {
|
||||
flash := NewFlash()
|
||||
flash.Notice("TestFlashString")
|
||||
flash.Store(&this.Controller)
|
||||
// we choose to serve json because we don't want to load a template html file
|
||||
this.ServeJson(true)
|
||||
}
|
||||
|
||||
func TestFlashHeader(t *testing.T) {
|
||||
// create fake GET request
|
||||
r, _ := http.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// setup the handler
|
||||
handler := NewControllerRegister()
|
||||
handler.Add("/", &TestFlashController{}, "get:TestWriteFlash")
|
||||
handler.ServeHTTP(w, r)
|
||||
|
||||
// get the Set-Cookie value
|
||||
sc := w.Header().Get("Set-Cookie")
|
||||
// match for the expected header
|
||||
res := strings.Contains(sc, "BEEGO_FLASH=%00notice%23BEEGOFLASH%23TestFlashString%00")
|
||||
// validate the assertion
|
||||
if res != true {
|
||||
t.Errorf("TestFlashHeader() unable to validate flash message")
|
||||
}
|
||||
}
|
97
httplib/README.md
Normal file
@ -0,0 +1,97 @@
|
||||
# httplib
|
||||
httplib is an libs help you to curl remote url.
|
||||
|
||||
# How to use?
|
||||
|
||||
## GET
|
||||
you can use Get to crawl data.
|
||||
|
||||
import "github.com/astaxie/beego/httplib"
|
||||
|
||||
str, err := httplib.Get("http://beego.me/").String()
|
||||
if err != nil {
|
||||
// error
|
||||
}
|
||||
fmt.Println(str)
|
||||
|
||||
## POST
|
||||
POST data to remote url
|
||||
|
||||
req := httplib.Post("http://beego.me/")
|
||||
req.Param("username","astaxie")
|
||||
req.Param("password","123456")
|
||||
str, err := req.String()
|
||||
if err != nil {
|
||||
// error
|
||||
}
|
||||
fmt.Println(str)
|
||||
|
||||
## Set timeout
|
||||
|
||||
The default timeout is `60` seconds, function prototype:
|
||||
|
||||
SetTimeout(connectTimeout, readWriteTimeout time.Duration)
|
||||
|
||||
Exmaple:
|
||||
|
||||
// GET
|
||||
httplib.Get("http://beego.me/").SetTimeout(100 * time.Second, 30 * time.Second)
|
||||
|
||||
// POST
|
||||
httplib.Post("http://beego.me/").SetTimeout(100 * time.Second, 30 * time.Second)
|
||||
|
||||
|
||||
## Debug
|
||||
|
||||
If you want to debug the request info, set the debug on
|
||||
|
||||
httplib.Get("http://beego.me/").Debug(true)
|
||||
|
||||
## Set HTTP Basic Auth
|
||||
|
||||
str, err := Get("http://beego.me/").SetBasicAuth("user", "passwd").String()
|
||||
if err != nil {
|
||||
// error
|
||||
}
|
||||
fmt.Println(str)
|
||||
|
||||
## Set HTTPS
|
||||
|
||||
If request url is https, You can set the client support TSL:
|
||||
|
||||
httplib.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
|
||||
More info about the `tls.Config` please visit http://golang.org/pkg/crypto/tls/#Config
|
||||
|
||||
## Set HTTP Version
|
||||
|
||||
some servers need to specify the protocol version of HTTP
|
||||
|
||||
httplib.Get("http://beego.me/").SetProtocolVersion("HTTP/1.1")
|
||||
|
||||
## Set Cookie
|
||||
|
||||
some http request need setcookie. So set it like this:
|
||||
|
||||
cookie := &http.Cookie{}
|
||||
cookie.Name = "username"
|
||||
cookie.Value = "astaxie"
|
||||
httplib.Get("http://beego.me/").SetCookie(cookie)
|
||||
|
||||
## Upload file
|
||||
|
||||
httplib support mutil file upload, use `req.PostFile()`
|
||||
|
||||
req := httplib.Post("http://beego.me/")
|
||||
req.Param("username","astaxie")
|
||||
req.PostFile("uploadfile1", "httplib.pdf")
|
||||
str, err := req.String()
|
||||
if err != nil {
|
||||
// error
|
||||
}
|
||||
fmt.Println(str)
|
||||
|
||||
|
||||
See godoc for further documentation and examples.
|
||||
|
||||
* [godoc.org/github.com/astaxie/beego/httplib](https://godoc.org/github.com/astaxie/beego/httplib)
|
@ -1,92 +1,243 @@
|
||||
// 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.
|
||||
|
||||
// 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 (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var defaultUserAgent = "beegoServer"
|
||||
var defaultSetting = BeegoHttpSettings{false, "beegoServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
|
||||
var defaultCookieJar http.CookieJar
|
||||
var settingMutex sync.Mutex
|
||||
|
||||
// createDefaultCookie creates a global cookiejar to store cookies.
|
||||
func createDefaultCookie() {
|
||||
settingMutex.Lock()
|
||||
defer settingMutex.Unlock()
|
||||
defaultCookieJar, _ = cookiejar.New(nil)
|
||||
}
|
||||
|
||||
// Overwrite default settings
|
||||
func SetDefaultSetting(setting BeegoHttpSettings) {
|
||||
settingMutex.Lock()
|
||||
defer settingMutex.Unlock()
|
||||
defaultSetting = setting
|
||||
if defaultSetting.ConnectTimeout == 0 {
|
||||
defaultSetting.ConnectTimeout = 60 * time.Second
|
||||
}
|
||||
if defaultSetting.ReadWriteTimeout == 0 {
|
||||
defaultSetting.ReadWriteTimeout = 60 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// return *BeegoHttpRequest with specific method
|
||||
func newBeegoRequest(url, method string) *BeegoHttpRequest {
|
||||
var resp http.Response
|
||||
req := http.Request{
|
||||
Method: method,
|
||||
Header: make(http.Header),
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
}
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
|
||||
}
|
||||
|
||||
// Get returns *BeegoHttpRequest with GET method.
|
||||
func Get(url string) *BeegoHttpRequest {
|
||||
var req http.Request
|
||||
req.Method = "GET"
|
||||
req.Header = http.Header{}
|
||||
req.Header.Set("User-Agent", defaultUserAgent)
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second}
|
||||
return newBeegoRequest(url, "GET")
|
||||
}
|
||||
|
||||
// Post returns *BeegoHttpRequest with POST method.
|
||||
func Post(url string) *BeegoHttpRequest {
|
||||
var req http.Request
|
||||
req.Method = "POST"
|
||||
req.Header = http.Header{}
|
||||
req.Header.Set("User-Agent", defaultUserAgent)
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second}
|
||||
return newBeegoRequest(url, "POST")
|
||||
}
|
||||
|
||||
// Put returns *BeegoHttpRequest with PUT method.
|
||||
func Put(url string) *BeegoHttpRequest {
|
||||
var req http.Request
|
||||
req.Method = "PUT"
|
||||
req.Header = http.Header{}
|
||||
req.Header.Set("User-Agent", defaultUserAgent)
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second}
|
||||
return newBeegoRequest(url, "PUT")
|
||||
}
|
||||
|
||||
// Delete returns *BeegoHttpRequest DELETE method.
|
||||
func Delete(url string) *BeegoHttpRequest {
|
||||
var req http.Request
|
||||
req.Method = "DELETE"
|
||||
req.Header = http.Header{}
|
||||
req.Header.Set("User-Agent", defaultUserAgent)
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second}
|
||||
return newBeegoRequest(url, "DELETE")
|
||||
}
|
||||
|
||||
// Head returns *BeegoHttpRequest with HEAD method.
|
||||
func Head(url string) *BeegoHttpRequest {
|
||||
var req http.Request
|
||||
req.Method = "HEAD"
|
||||
req.Header = http.Header{}
|
||||
req.Header.Set("User-Agent", defaultUserAgent)
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second}
|
||||
return newBeegoRequest(url, "HEAD")
|
||||
}
|
||||
|
||||
// BeegoHttpSettings
|
||||
type BeegoHttpSettings struct {
|
||||
ShowDebug bool
|
||||
UserAgent string
|
||||
ConnectTimeout time.Duration
|
||||
ReadWriteTimeout time.Duration
|
||||
TlsClientConfig *tls.Config
|
||||
Proxy func(*http.Request) (*url.URL, error)
|
||||
Transport http.RoundTripper
|
||||
EnableCookie bool
|
||||
}
|
||||
|
||||
// BeegoHttpRequest provides more useful methods for requesting one url than http.Request.
|
||||
type BeegoHttpRequest struct {
|
||||
url string
|
||||
req *http.Request
|
||||
params map[string]string
|
||||
showdebug bool
|
||||
connectTimeout time.Duration
|
||||
readWriteTimeout time.Duration
|
||||
files map[string]string
|
||||
setting BeegoHttpSettings
|
||||
resp *http.Response
|
||||
body []byte
|
||||
}
|
||||
|
||||
// Change request settings
|
||||
func (b *BeegoHttpRequest) Setting(setting BeegoHttpSettings) *BeegoHttpRequest {
|
||||
b.setting = 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.req.SetBasicAuth(username, password)
|
||||
return b
|
||||
}
|
||||
|
||||
// SetEnableCookie sets enable/disable cookiejar
|
||||
func (b *BeegoHttpRequest) SetEnableCookie(enable bool) *BeegoHttpRequest {
|
||||
b.setting.EnableCookie = enable
|
||||
return b
|
||||
}
|
||||
|
||||
// SetUserAgent sets User-Agent header field
|
||||
func (b *BeegoHttpRequest) SetUserAgent(useragent string) *BeegoHttpRequest {
|
||||
b.setting.UserAgent = useragent
|
||||
return b
|
||||
}
|
||||
|
||||
// Debug sets show debug or not when executing request.
|
||||
func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest {
|
||||
b.showdebug = isdebug
|
||||
b.setting.ShowDebug = isdebug
|
||||
return b
|
||||
}
|
||||
|
||||
// SetTimeout sets connect time out and read-write time out for BeegoRequest.
|
||||
func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest {
|
||||
b.connectTimeout = connectTimeout
|
||||
b.readWriteTimeout = readWriteTimeout
|
||||
b.setting.ConnectTimeout = connectTimeout
|
||||
b.setting.ReadWriteTimeout = readWriteTimeout
|
||||
return b
|
||||
}
|
||||
|
||||
// SetTLSClientConfig sets tls connection configurations if visiting https url.
|
||||
func (b *BeegoHttpRequest) SetTLSClientConfig(config *tls.Config) *BeegoHttpRequest {
|
||||
b.setting.TlsClientConfig = config
|
||||
return b
|
||||
}
|
||||
|
||||
// Header add header item string in request.
|
||||
func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest {
|
||||
b.req.Header.Set(key, value)
|
||||
return b
|
||||
}
|
||||
|
||||
// Set the protocol version for incoming requests.
|
||||
// Client requests always use HTTP/1.1.
|
||||
func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest {
|
||||
if len(vers) == 0 {
|
||||
vers = "HTTP/1.1"
|
||||
}
|
||||
|
||||
major, minor, ok := http.ParseHTTPVersion(vers)
|
||||
if ok {
|
||||
b.req.Proto = vers
|
||||
b.req.ProtoMajor = major
|
||||
b.req.ProtoMinor = minor
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// SetCookie add cookie into request.
|
||||
func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest {
|
||||
b.req.Header.Add("Cookie", cookie.String())
|
||||
return b
|
||||
}
|
||||
|
||||
// Set transport to
|
||||
func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpRequest {
|
||||
b.setting.Transport = transport
|
||||
return b
|
||||
}
|
||||
|
||||
// Set 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.setting.Proxy = proxy
|
||||
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.params[key] = value
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) PostFile(formname, filename string) *BeegoHttpRequest {
|
||||
b.files[formname] = filename
|
||||
return b
|
||||
}
|
||||
|
||||
// Body adds request raw body.
|
||||
// it supports string and []byte.
|
||||
func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
|
||||
switch t := data.(type) {
|
||||
case string:
|
||||
@ -102,8 +253,11 @@ func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
if b.resp.StatusCode != 0 {
|
||||
return b.resp, nil
|
||||
}
|
||||
var paramBody string
|
||||
if b.params != nil && len(b.params) > 0 {
|
||||
if len(b.params) > 0 {
|
||||
var buf bytes.Buffer
|
||||
for k, v := range b.params {
|
||||
buf.WriteString(url.QueryEscape(k))
|
||||
@ -114,6 +268,7 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
paramBody = buf.String()
|
||||
paramBody = paramBody[0 : len(paramBody)-1]
|
||||
}
|
||||
|
||||
if b.req.Method == "GET" && len(paramBody) > 0 {
|
||||
if strings.Index(b.url, "?") != -1 {
|
||||
b.url += "&" + paramBody
|
||||
@ -121,21 +276,90 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
b.url = b.url + "?" + paramBody
|
||||
}
|
||||
} else if b.req.Method == "POST" && b.req.Body == nil && len(paramBody) > 0 {
|
||||
b.Header("Content-Type", "application/x-www-form-urlencoded")
|
||||
b.Body(paramBody)
|
||||
}
|
||||
|
||||
url, err := url.Parse(b.url)
|
||||
if url.Scheme == "" {
|
||||
b.url = "http://" + b.url
|
||||
url, err = url.Parse(b.url)
|
||||
}
|
||||
|
||||
if len(b.files) > 0 {
|
||||
bodyBuf := &bytes.Buffer{}
|
||||
bodyWriter := multipart.NewWriter(bodyBuf)
|
||||
for formname, filename := range b.files {
|
||||
fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fh, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//iocopy
|
||||
_, err = io.Copy(fileWriter, fh)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for k, v := range b.params {
|
||||
bodyWriter.WriteField(k, v)
|
||||
}
|
||||
contentType := bodyWriter.FormDataContentType()
|
||||
bodyWriter.Close()
|
||||
b.Header("Content-Type", contentType)
|
||||
b.req.Body = ioutil.NopCloser(bodyBuf)
|
||||
b.req.ContentLength = int64(bodyBuf.Len())
|
||||
} else {
|
||||
b.Header("Content-Type", "application/x-www-form-urlencoded")
|
||||
b.Body(paramBody)
|
||||
}
|
||||
}
|
||||
|
||||
url, err := url.Parse(b.url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b.req.URL = url
|
||||
if b.showdebug {
|
||||
|
||||
trans := b.setting.Transport
|
||||
|
||||
if trans == nil {
|
||||
// create default transport
|
||||
trans = &http.Transport{
|
||||
TLSClientConfig: b.setting.TlsClientConfig,
|
||||
Proxy: b.setting.Proxy,
|
||||
Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout),
|
||||
}
|
||||
} else {
|
||||
// if b.transport is *http.Transport then set the settings.
|
||||
if t, ok := trans.(*http.Transport); ok {
|
||||
if t.TLSClientConfig == nil {
|
||||
t.TLSClientConfig = b.setting.TlsClientConfig
|
||||
}
|
||||
if t.Proxy == nil {
|
||||
t.Proxy = b.setting.Proxy
|
||||
}
|
||||
if t.Dial == nil {
|
||||
t.Dial = TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var jar http.CookieJar
|
||||
if b.setting.EnableCookie {
|
||||
if defaultCookieJar == nil {
|
||||
createDefaultCookie()
|
||||
}
|
||||
jar = defaultCookieJar
|
||||
} else {
|
||||
jar = nil
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Transport: trans,
|
||||
Jar: jar,
|
||||
}
|
||||
|
||||
if b.setting.UserAgent != "" {
|
||||
b.req.Header.Set("User-Agent", b.setting.UserAgent)
|
||||
}
|
||||
|
||||
if b.setting.ShowDebug {
|
||||
dump, err := httputil.DumpRequest(b.req, true)
|
||||
if err != nil {
|
||||
println(err.Error())
|
||||
@ -143,18 +367,16 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
println(string(dump))
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Dial: TimeoutDialer(b.connectTimeout, b.readWriteTimeout),
|
||||
},
|
||||
}
|
||||
resp, err := client.Do(b.req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.resp = resp
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// String returns the body string in response.
|
||||
// it calls Response inner.
|
||||
func (b *BeegoHttpRequest) String() (string, error) {
|
||||
data, err := b.Bytes()
|
||||
if err != nil {
|
||||
@ -164,7 +386,12 @@ func (b *BeegoHttpRequest) String() (string, error) {
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// Bytes returns the body []byte in response.
|
||||
// it calls Response inner.
|
||||
func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
|
||||
if b.body != nil {
|
||||
return b.body, nil
|
||||
}
|
||||
resp, err := b.getResponse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -177,9 +404,12 @@ func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.body = data
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// ToFile saves the body data in response to one file.
|
||||
// it calls Response inner.
|
||||
func (b *BeegoHttpRequest) ToFile(filename string) error {
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
@ -196,40 +426,37 @@ func (b *BeegoHttpRequest) ToFile(filename string) error {
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_, err = io.Copy(f, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
data, err := b.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(data, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) ToXML(v interface{}) error {
|
||||
// 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 {
|
||||
data, err := b.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = xml.Unmarshal(data, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Response executes request client gets response mannually.
|
||||
func (b *BeegoHttpRequest) Response() (*http.Response, error) {
|
||||
return b.getResponse()
|
||||
}
|
||||
|
||||
// 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 func(netw, addr string) (net.Conn, error) {
|
||||
conn, err := net.DialTimeout(netw, addr, cTimeout)
|
||||
|
@ -1,32 +1,205 @@
|
||||
// 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
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetUrl(t *testing.T) {
|
||||
resp, err := Get("http://beego.me/").Response()
|
||||
func TestResponse(t *testing.T) {
|
||||
req := Get("http://httpbin.org/get")
|
||||
resp, err := req.Response()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Body == nil {
|
||||
t.Fatal("body is nil")
|
||||
}
|
||||
data, err := ioutil.ReadAll(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
t.Fatal("data is no")
|
||||
}
|
||||
t.Log(resp)
|
||||
}
|
||||
|
||||
str, err := Get("http://beego.me/").String()
|
||||
func TestGet(t *testing.T) {
|
||||
req := Get("http://httpbin.org/get")
|
||||
b, err := req.Bytes()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(str) == 0 {
|
||||
t.Fatal("has no info")
|
||||
t.Log(b)
|
||||
|
||||
s, err := req.String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(s)
|
||||
|
||||
if string(b) != s {
|
||||
t.Fatal("request data not match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimplePost(t *testing.T) {
|
||||
v := "smallfish"
|
||||
req := Post("http://httpbin.org/post")
|
||||
req.Param("username", v)
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostFile(t *testing.T) {
|
||||
v := "smallfish"
|
||||
req := Post("http://httpbin.org/post")
|
||||
req.Param("username", v)
|
||||
req.PostFile("uploadfile", "httplib_test.go")
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimplePut(t *testing.T) {
|
||||
str, err := Put("http://httpbin.org/put").String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
}
|
||||
|
||||
func TestSimpleDelete(t *testing.T) {
|
||||
str, err := Delete("http://httpbin.org/delete").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()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
|
||||
str, err = Get("http://httpbin.org/cookies").SetEnableCookie(true).String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
|
||||
n := strings.Index(str, v)
|
||||
if n == -1 {
|
||||
t.Fatal(v + " not found in cookie")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithBasicAuth(t *testing.T) {
|
||||
str, err := Get("http://httpbin.org/basic-auth/user/passwd").SetBasicAuth("user", "passwd").String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
n := strings.Index(str, "authenticated")
|
||||
if n == -1 {
|
||||
t.Fatal("authenticated not found in response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithUserAgent(t *testing.T) {
|
||||
v := "beego"
|
||||
str, err := Get("http://httpbin.org/headers").SetUserAgent(v).String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
|
||||
n := strings.Index(str, v)
|
||||
if n == -1 {
|
||||
t.Fatal(v + " not found in user-agent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithSetting(t *testing.T) {
|
||||
v := "beego"
|
||||
var setting BeegoHttpSettings
|
||||
setting.EnableCookie = true
|
||||
setting.UserAgent = v
|
||||
setting.Transport = nil
|
||||
SetDefaultSetting(setting)
|
||||
|
||||
str, err := Get("http://httpbin.org/get").String()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(str)
|
||||
|
||||
n := strings.Index(str, v)
|
||||
if n == -1 {
|
||||
t.Fatal(v + " not found in user-agent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToJson(t *testing.T) {
|
||||
req := Get("http://httpbin.org/ip")
|
||||
resp, err := req.Response()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(resp)
|
||||
|
||||
// httpbin will return http remote addr
|
||||
type Ip struct {
|
||||
Origin string `json:"origin"`
|
||||
}
|
||||
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 {
|
||||
t.Fatal("response is not valid ip")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToFile(t *testing.T) {
|
||||
f := "beego_testfile"
|
||||
req := Get("http://httpbin.org/ip")
|
||||
err := req.ToFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(f)
|
||||
b, err := ioutil.ReadFile(f)
|
||||
if n := strings.Index(string(b), "origin"); n == -1 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|