Compare commits
995 Commits
v3.0.0-bet
...
v3.11.46
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e86864ce7 | |||
|
|
a68d3b24b8 | ||
| 9c22ae5384 | |||
|
|
16bad9a0cd | ||
|
|
3c779b248f | ||
| bbc7512054 | |||
|
|
dd810e4ae0 | ||
| 236ed47ab1 | |||
|
|
909bcf51a4 | ||
| 9c24001f52 | |||
| 680cd6f708 | |||
|
|
3fcf3bef6d | ||
|
|
0ecd6199d4 | ||
| 14a30fb6a7 | |||
| 7c613072df | |||
|
|
c55e212270 | ||
| 100bc006bb | |||
| 5dbfe8a7a6 | |||
| 6be077dbe8 | |||
| b4878211ee | |||
| ec9178c6d4 | |||
| ae63d44866 | |||
| 883e79216a | |||
| fa636ef6a9 | |||
| cdb81a9ba3 | |||
| 413c6cc2f0 | |||
|
|
f56bd70136 | ||
| b51b4107a8 | |||
| 2067c9de6b | |||
| 3f82cb3ba4 | |||
|
|
306b7a3962 | ||
| a8eda9d58d | |||
| 7e4477dcb4 | |||
|
|
d846044fc6 | ||
| 29d956e74e | |||
| fcc4faff8a | |||
| 5df8f83f45 | |||
|
|
27fa6e9173 | ||
| bd55a35dc3 | |||
| 653bd386cc | |||
|
|
558c6f4d7c | ||
| d7dd6fbeb2 | |||
| a00cf2c8d9 | |||
|
|
a3e8ab2492 | ||
| 06da500ef4 | |||
| 277f04ba19 | |||
|
|
470263ff5f | ||
| b8232e02be | |||
|
|
f8c5e10c1d | ||
| 397e71f815 | |||
| 74e31d99f6 | |||
| f39de15d93 | |||
| d291102877 | |||
| 37ffbb18d8 | |||
| 9a85dead86 | |||
| a489aab1c3 | |||
| d160664ef1 | |||
| fa868edcaa | |||
|
|
6ed0b0e090 | ||
| 533b265d19 | |||
| 1ace2631a4 | |||
| 3dd5ca68d1 | |||
| 66ccd6021f | |||
| e5346f7e4f | |||
|
|
daf19f031a | ||
| 5989fd54ca | |||
| ed30c26324 | |||
| 0f8f93d09a | |||
|
|
f460e2f8dd | ||
| 70d6a79274 | |||
| 664b1586af | |||
| 8d747c64a8 | |||
| 94beb5ed3b | |||
| 98981ba86c | |||
| 1013f50d0e | |||
| 0b190997b1 | |||
| 69a44eb190 | |||
| 0476028f69 | |||
| 330d8b149a | |||
| 19b04fe070 | |||
| 4cd55875c6 | |||
| a7896cc728 | |||
| ff991bf49c | |||
| 5a6551b703 | |||
| 9406a33d60 | |||
| 8f185abd9d | |||
| 86492e0644 | |||
| b21972964a | |||
| f5ee065d09 | |||
| 8cb02f2b08 | |||
| bc926cd6bd | |||
| 356abfd818 | |||
| 18444d3f98 | |||
| d5f07922e8 | |||
| 675e717410 | |||
| 7b6aea235a | |||
| 2cb7200467 | |||
| f430f97a97 | |||
| 0060c4377a | |||
| e46579fe9a | |||
| ca52973194 | |||
| 5bb33c7e1d | |||
| b71fc25328 | |||
| 9345dd075a | |||
| 1c1b9c0a28 | |||
| 2969494c5a | |||
| cbd3fa38ba | |||
| 569a36383d | |||
| 90bed77526 | |||
| ba4478a5e0 | |||
| 6dc76cdfea | |||
| e266683d96 | |||
| 2b62ad04f2 | |||
| 275b0a64e5 | |||
| 38c5fe8b5a | |||
| b6a0e4d983 | |||
| d9b822deff | |||
| 0e66688f8f | |||
| 9213fd212f | |||
| aa360dcf51 | |||
| 2df259b5b8 | |||
| 15e9310368 | |||
|
|
16d8cf3434 | ||
| 9704ef2e5e | |||
| 94e8f90f00 | |||
| 34d1587881 | |||
| bf4143cde5 | |||
| 36b7b9f5fb | |||
| ae97023092 | |||
| 115ca6a018 | |||
| 89cf4ef8af | |||
| 2a6ce6d4da | |||
| ad19fe2b90 | |||
| 49055a28ea | |||
| d1c6e121c1 | |||
| 7cd7fb0c0a | |||
| 77eb5b5264 | |||
| 929e46c087 | |||
| 1fb5673d27 | |||
| 3bbb0cbc72 | |||
| 71fe0df73f | |||
| f1b8ecbdb3 | |||
| fd2b2762e9 | |||
| 82d269cfb4 | |||
| 6641463eed | |||
| faf2454f0a | |||
| de9e4d73f5 | |||
| 4ae7277140 | |||
| a98618ed5b | |||
| 3aaf1182cb | |||
| eb1482d789 | |||
| a305f7553f | |||
|
|
d9b2f2a45d | ||
| 3ace7657dc | |||
| 53b40617e2 | |||
| 1a9236caad | |||
| 6c68d39081 | |||
| 35e62fbeb0 | |||
| 00b3ceb468 | |||
| 7dc8f088c9 | |||
| c65afcea1b | |||
| 3eebfb5b11 | |||
| fa1427014c | |||
| 62074965ee | |||
| 9c8fbb2202 | |||
| 7c0a5f5e2a | |||
| b08f5321b0 | |||
| cc0f24e012 | |||
| 307a08f50c | |||
| edc93e8c37 | |||
| 391813c260 | |||
| 1a1459dd0e | |||
| 4e99680c30 | |||
| 92a3a547b8 | |||
| 849c462037 | |||
| 54a55c83e2 | |||
| 781dee03db | |||
| 26dd2eb405 | |||
| 3a21069b86 | |||
| add3ce478c | |||
|
|
c3de003e4a | ||
| 7b7cf18a65 | |||
| 1bcf71c189 | |||
| c320d8e518 | |||
| b5f8316b57 | |||
| d7ddd912a8 | |||
| c020d90cb4 | |||
| db47b62159 | |||
| 8254456c8b | |||
| c2808679c3 | |||
| f418235c16 | |||
| 67ba7b3753 | |||
| e48d7cadf9 | |||
| c906186011 | |||
| dc0ff91b83 | |||
| e739c2d438 | |||
| bf4a036652 | |||
| f83a29eb67 | |||
| aef7f53d88 | |||
| 02c8e4fb7f | |||
| f5693bd940 | |||
| 701afb7bea | |||
| 019b407e74 | |||
| f29a346434 | |||
| 27db1876c0 | |||
| f66ac9736b | |||
| ed7972a1fa | |||
| 2cc004b01c | |||
| df951e5daf | |||
| 5bec0cef03 | |||
| 34940b68d7 | |||
| 1c57127128 | |||
| a4dd1a494c | |||
| 60e5e42167 | |||
| b519b61fff | |||
| f62b26eda3 | |||
| 13eda451da | |||
| 89cad06121 | |||
| 0bebf3d59f | |||
| 01e05e8df6 | |||
| 2b69a4f51c | |||
| 4af2b077dd | |||
| de4418189d | |||
| 2c44550897 | |||
| 99b8a3c950 | |||
| 4c7e1607d4 | |||
| 897be419b4 | |||
| 81b9a4341f | |||
| d3bb2f7236 | |||
| 97fd62cb21 | |||
| 3cd8bc33d6 | |||
| f6f67af8d0 | |||
| 2d5acaca2f | |||
| 0674df3d9f | |||
| 2c282825ce | |||
| e87ff942bb | |||
| 0459ea0613 | |||
| d44a75d074 | |||
|
|
ccf92eb84d | ||
| 6baf1f2744 | |||
| 8e2eafde9c | |||
| c2b97b0f20 | |||
| 1db017d966 | |||
| debf8cb03d | |||
| 1dc9c1891f | |||
| 930859a537 | |||
| 3141f1ed8b | |||
| 47943cfb05 | |||
| ed4e9d54b1 | |||
| b4b8583594 | |||
| fb43e8c58c | |||
| 8863c10ef4 | |||
| 8058095bcc | |||
| 092f5d96b1 | |||
| 84552513f7 | |||
| 80a2db264e | |||
| 0be09c8b3e | |||
| 047f479e1b | |||
| 8f757c953e | |||
| 5f1c673a24 | |||
| 6794ea9871 | |||
| 089e7b6812 | |||
| 1c703f0f0c | |||
| d167c8c67c | |||
| df4f96a2d8 | |||
| fac3b20bd4 | |||
| 7c6bd98498 | |||
| 23e1174f25 | |||
| 52bed214cf | |||
| 64c4f5f47e | |||
| 036c612137 | |||
| ca80e3ecf2 | |||
| 18e7bb41ca | |||
| 8e72fb1c35 | |||
| 17f21a03f4 | |||
| a076d43a26 | |||
| de6efaee0b | |||
| 9e0e657003 | |||
| be5f9ab77f | |||
| 144dca0cae | |||
| 75173560e3 | |||
| 9b3bccd1f1 | |||
| ce125b77c1 | |||
| 2ee8d4ed46 | |||
| f58781d076 | |||
| e1af4aa3a4 | |||
| 1d5e795443 | |||
| a3a434d923 | |||
| bcc06054f1 | |||
| 270d26f1ae | |||
| 646212cc08 | |||
| 00c2c749db | |||
| 2dbada0e94 | |||
| 7b8f4410fb | |||
| 45ebef5544 | |||
| cf4cac0733 | |||
| 50d60b5825 | |||
| 46ef491764 | |||
| a51b8b8102 | |||
| 15aac48f1e | |||
| 078069b2d7 | |||
| 258812304a | |||
| da5d50db5b | |||
| 384e4d113d | |||
| dfd1da7f0d | |||
| 8e5015e580 | |||
| bd0c309b71 | |||
| b4f0c3e29a | |||
| 8fddaa0455 | |||
| 2710c269a8 | |||
| 70ea93e466 | |||
| a87d0ab1c1 | |||
| 2e5e102719 | |||
| 36e492314d | |||
| 0c78873277 | |||
| 7f57dc09d3 | |||
| 447206d256 | |||
| 33a7feb970 | |||
| 3950f2ed86 | |||
| 68c1048a7d | |||
| bff40bd317 | |||
| 2878d0a4ea | |||
| 3138a9fded | |||
| 742b99636a | |||
| 34387f129d | |||
| 47075acb06 | |||
| 09cb998ba4 | |||
| b9dbfb1cfc | |||
| 56efccc4cf | |||
| ce9f896287 | |||
| 83d87a40e4 | |||
| 75fd1e43b9 | |||
| 395a3eed3d | |||
| 3ba8cb7f9e | |||
| b07806b9a1 | |||
| 0f583218d4 | |||
| f4d0237785 | |||
| 0f343dad0b | |||
| 7c29afba0b | |||
| 8159b9d233 | |||
| 45cdac5c29 | |||
| 98db0dc8bc | |||
| 453d2232bd | |||
| 9b387312da | |||
| 84024f7713 | |||
| 5a554f9f0c | |||
| 9c33cbc8e2 | |||
| 848fe1c0d4 | |||
| 6cbf23fec5 | |||
| 7462b0b53c | |||
| cb743cee3f | |||
| d18952951c | |||
|
|
f6b7f1b4bc | ||
|
|
33fa702104 | ||
| 4debc392d1 | |||
| 7137d99102 | |||
| f76b3171d9 | |||
| db3fc42204 | |||
| f59023d741 | |||
| 6f17fd891a | |||
| fd93308e8e | |||
| 2aaa0a74d8 | |||
| ccbf23688b | |||
| 3bd6db79cb | |||
| 9347bb0651 | |||
| 0d63723ed3 | |||
| a7f84e0baa | |||
| c209892ce8 | |||
| 421842315f | |||
| 25350a6531 | |||
| 5e47cc7e8c | |||
| 1687b98b11 | |||
| a81649d2a2 | |||
| b48faa3b2b | |||
| 0be584ef0d | |||
| 26a2d18766 | |||
| 25a796fe4f | |||
| d23de14769 | |||
| 2fb108519c | |||
| c7ce238da3 | |||
|
|
67aa79f18a | ||
| e6c3d734a3 | |||
| 1374e27531 | |||
| 1060f6a4c3 | |||
| 7d72ab05c6 | |||
| 42864ff1c6 | |||
| 49978b75c0 | |||
|
|
20770b6e30 | ||
| b38c6106b2 | |||
|
|
138c4a0888 | ||
|
|
22f66fc258 | ||
| 18fafbbbab | |||
| 59c08c1d9a | |||
| 5fbb1a923e | |||
| 396387d1e8 | |||
|
|
4c2f12a419 | ||
| b2abb86971 | |||
| e546eef96c | |||
| 91701e7a45 | |||
| 817bf1f4d0 | |||
| 4120f79b55 | |||
| d659db69ff | |||
| 416bb313fc | |||
| ec43cfea6b | |||
|
|
60194fb42e | ||
|
|
945d9d16a5 | ||
| 1c0e5e1a85 | |||
| 33591e0bc9 | |||
|
|
75cbaf2612 | ||
| f4aee3414b | |||
| 9f7b61eb17 | |||
| 5953b5aae6 | |||
| 4a8f490e0c | |||
| eb8c1332f0 | |||
| c1c27b6d1d | |||
|
|
bb22b203cc | ||
|
|
4df2f3a5a1 | ||
| b8ad19a5a2 | |||
|
|
d32a97c846 | ||
| cfe0473ae0 | |||
| c26ad51e25 | |||
| aefc398b71 | |||
| 9af23e3e74 | |||
| 4ab7f19ef0 | |||
| d26e9d642b | |||
| f9ecb9b056 | |||
| dbfcfcd288 | |||
| 8b6bdb857b | |||
| 1181e9dc5e | |||
| 6ac7b53d75 | |||
| 80d342a72a | |||
| 8ff312e71d | |||
| 20e40ccdfd | |||
| d4efbb9b22 | |||
| b433cbcbb6 | |||
| dae3c1170b | |||
| a10dd3d08a | |||
| b075230ae5 | |||
| 289aadb28e | |||
| 9640cdae1a | |||
|
|
fb35e73731 | ||
| f416cb3e0e | |||
| 57d06d5d27 | |||
| 0628408c27 | |||
| 206cd8c3c9 | |||
|
|
b38db00ee5 | ||
|
|
0ca39a1477 | ||
| d9be99cfde | |||
| b37c6006c4 | |||
| 12f188e3ad | |||
| 08aaf14a79 | |||
| 2ce1e94596 | |||
| c5aeaf6db7 | |||
| 1db505decd | |||
| 8b1a579c9d | |||
| 11b614f2df | |||
| fb4d747197 | |||
| 00439e23f3 | |||
| 955953b519 | |||
| aa2b5ddaad | |||
| 46da092899 | |||
| b871f64ba6 | |||
| 74db004f51 | |||
| f93ba9d977 | |||
| c7da7d5bc8 | |||
| ed27647be5 | |||
|
|
db3b67267e | ||
| 9ee9cc2a4a | |||
| 0b41b4f9c5 | |||
| 8d14753931 | |||
| 93fc17bad3 | |||
| 5a1cd12d3d | |||
| 5c00e6763f | |||
| 497b82ac6c | |||
| a8c6690af7 | |||
| 98d2264c2a | |||
| 63641b9840 | |||
| 2b28057918 | |||
| 25c551411b | |||
| 35162a82a4 | |||
| 0ce0855b6a | |||
| 226ec43ecf | |||
| 575af66ddc | |||
|
|
afb9e8c240 | ||
| c10f29ee74 | |||
| 03410c4ab1 | |||
| 3805d0f067 | |||
| 680ac11ef9 | |||
| 35ab6ae84e | |||
| c6c2b0884e | |||
| 297a80da84 | |||
| 2d292db7bd | |||
| 54c4287fab | |||
| 9c074e5741 | |||
| 290975eaf5 | |||
| c64218d52c | |||
|
|
46c266a4a9 | ||
| 5527b16cd8 | |||
| 4904cad8ef | |||
| 74633f4290 | |||
|
|
c8ad4d772b | ||
| 91bd0f7efe | |||
| 00dc7e1bb5 | |||
| 5a5165a003 | |||
| 382e3d554b | |||
| 05a0c97fc6 | |||
|
|
5e06ae1a42 | ||
|
|
7ac4ad4efa | ||
|
|
01348bd9b2 | ||
| 2287c65118 | |||
| b34bc7ffff | |||
|
|
2a0bf03d0a | ||
| 89114c291c | |||
|
|
b4b4320fac | ||
| 7b0d69115c | |||
| f054beb6e8 | |||
| 9fb346594e | |||
|
|
cbf6fbd780 | ||
|
|
0392bff282 | ||
|
|
75b1fe5dc6 | ||
| 1f232ffba8 | |||
|
|
7f43b64fc2 | ||
| d0d04a840a | |||
| 1dda3f0dcc | |||
| 1abf5e7647 | |||
| f06610c9c2 | |||
| df8560bb6f | |||
| 0257eae936 | |||
| 58f03d05e7 | |||
| 60340a749b | |||
| 56b0df5b7a | |||
|
|
bb59d5a2fd | ||
| 67d5dc7e28 | |||
| 797c0f822d | |||
| 8546140e22 | |||
| 92b125c1ce | |||
| 8f7eebc24f | |||
| b0def96d14 | |||
| 927ca879b2 | |||
| 00450c9cc7 | |||
| 534bce2d20 | |||
| 53949be0cc | |||
| d8fe2ff8b4 | |||
| 53b5ee2c6f | |||
| dfd85cd871 | |||
| 52182261af | |||
| 1f3834e187 | |||
| 0354873c3a | |||
| 8e5e2167cd | |||
| c26a7db47c | |||
| 74765b4c5f | |||
| 8bd7323af1 | |||
|
|
899dc8b3bc | ||
| 6e6c31b5dd | |||
| 94929878fe | |||
| 8ce469a09e | |||
| 88788776d2 | |||
| e143e2b547 | |||
| a36f99e30b | |||
| 326ee53333 | |||
| 1244c5bb4d | |||
| 4ccc8a9c85 | |||
| 8a2e84d489 | |||
| d29363b78d | |||
| 734f751055 | |||
| 55d8a9ee20 | |||
| 07c93042ba | |||
| b9bbfdf159 | |||
| fbad257acc | |||
| 1829febb6e | |||
| 7838fa62a8 | |||
| 332803d8de | |||
| 11c868d476 | |||
| 38d6e482d7 | |||
| 07d4085201 | |||
| 45f30c0be3 | |||
| bcaea675a7 | |||
| 3087ba1d73 | |||
| 3f5b19497c | |||
| 37d937d7ae | |||
| 7d68f2396e | |||
| 0854a7ea72 | |||
| 5eb0e56373 | |||
| 6af837fd25 | |||
| ada59119cc | |||
| 8abc913b28 | |||
| 3247d144a8 | |||
| 7b2e3cc8aa | |||
| 8688179acd | |||
| 3e40bac5f4 | |||
| e3fee6f8a6 | |||
| 15c020fac5 | |||
| 3bc046e5d4 | |||
| 542f36cfa5 | |||
| 8237e6a08e | |||
| ecb60e4dc5 | |||
| a1999ff81c | |||
| d0f2bc8346 | |||
|
|
dd29bf457e | ||
| d062c248e3 | |||
| 875f66d36e | |||
| 818a0e6356 | |||
| 56e02ec463 | |||
| 6ca851401d | |||
| bd8216b397 | |||
| 2b13b3f128 | |||
| 9957380b6d | |||
| e10f8c0fa0 | |||
| 45252fe4a6 | |||
| faad082efe | |||
| 8ab35cbd9b | |||
| ad58ab6943 | |||
| 0e97049e1d | |||
| edb0bbf9cf | |||
|
|
1b01bd22a6 | ||
| 2fbaa26f0f | |||
| 35d3e4b332 | |||
|
|
e98a93d530 | ||
| e3545532e8 | |||
| 09653c2fb2 | |||
| 70adfeab0d | |||
| a45b672c98 | |||
| 4509323cae | |||
| b3f4c670d5 | |||
| 778dd449e2 | |||
| 1d16983b67 | |||
| f386bffd37 | |||
| 772bde7938 | |||
| ea16f5f825 | |||
| c2f34df493 | |||
| efe215cd60 | |||
| b4f332bf0d | |||
| f47fbb1030 | |||
| 1e8e57a708 | |||
|
|
5d0959b0a1 | ||
| fa8fb3aed7 | |||
| cfd2d53a79 | |||
| d306f77ffc | |||
| e5b0a7e20d | |||
| 9a5b158b4d | |||
| af8d81f3c6 | |||
| 5c9b3dae33 | |||
| 9f3957d101 | |||
| 8fd8bdcb39 | |||
| 80e3d239ab | |||
| 419cd486cf | |||
| e64269b2a8 | |||
| d18429e024 | |||
| 675e121049 | |||
| d357fb1e0d | |||
| e4673bcc50 | |||
| a839f75a2f | |||
| a7e6d61b95 | |||
| 650d167313 | |||
| c6ba2a91e6 | |||
| 7ece08896f | |||
|
|
57f6f23294 | ||
| 09e6fa2fed | |||
| 10a09a5c6f | |||
| b4e5d9462a | |||
| 96aa0b6906 | |||
| f54658830d | |||
| 1e43122660 | |||
| 42800fa247 | |||
| 5b9c810653 | |||
| c3def24bf4 | |||
| 0d1ef31764 | |||
| d49afa230f | |||
| e545eb4e13 | |||
| f28b107372 | |||
| c592fabe2a | |||
| eb107020c7 | |||
| bd4d4c363e | |||
| 2a548634fd | |||
| 598dddc476 | |||
| 887b48f1e7 | |||
| 6e55d07636 | |||
| 919520219c | |||
| 60a5e737f8 | |||
| 34f0b209cc | |||
| ba8e1889fe | |||
| dae5c57a60 | |||
| ea590d57df | |||
|
|
9aa6969836 | ||
|
|
c00c705c24 | ||
|
|
0239f795d8 | ||
|
|
e69b43881d | ||
| 3a48a613fe | |||
| 86626c5922 | |||
| ee11f39a2f | |||
| 3bdfdd8fd2 | |||
| 6dfdff7fd8 | |||
| 00a4785df3 | |||
|
|
bae3b0ef94 | ||
|
|
89b0565062 | ||
| 1f8b0aeb61 | |||
|
|
5b6f849e0a | ||
|
|
3b416fffde | ||
| 3a60103aed | |||
| 41837a67f8 | |||
| 852f19598d | |||
| 6537b35773 | |||
| b733f1316f | |||
|
|
840af5574c | ||
|
|
56e5b7001c | ||
|
|
11dc6fd752 | ||
| a2695d8699 | |||
| 618421de05 | |||
|
|
30baaabd9f | ||
| df5bce1191 | |||
|
|
089d0fe4df | ||
| a06f535303 | |||
|
|
eba586a329 | ||
|
|
d74a8645e8 | ||
|
|
5a00786192 | ||
|
|
b3e9941634 | ||
|
|
a5a5904302 | ||
|
|
a59832e57e | ||
| 0e42033e7f | |||
| 52d8255974 | |||
| 9830cb48a9 | |||
| 92d7ab2105 | |||
| d2935ef399 | |||
| ce4c96ae0a | |||
|
|
14026d15be | ||
|
|
2df0c7643e | ||
| e13c2c48fd | |||
| 8db55d2e55 | |||
| ed61cad961 | |||
| 040fc4548f | |||
| 6189a1b980 | |||
| eb2a450a7b | |||
|
|
d2a30a5da1 | ||
| 65889c66f6 | |||
| dcdf133d5b | |||
| 8742b55305 | |||
| 4a64ee72f7 | |||
| 881d7afeea | |||
| 8c95448535 | |||
| c1dc041d8c | |||
|
|
25be0ac0f0 | ||
|
|
86f73cac4e | ||
| 485eda6ce9 | |||
| dbbdb24631 | |||
| 723ceb4f32 | |||
| bac9869bb3 | |||
| 610427445f | |||
|
|
c84a66c713 | ||
| 00eaae717b | |||
| a102e95433 | |||
| 39f66cc86c | |||
| bbbcb22565 | |||
| cb70dfa664 | |||
| 1f0482fbd5 | |||
| a862562284 | |||
| c320c23913 | |||
|
|
ae848ba8bb | ||
|
|
8e264cbb3e | ||
|
|
54e523ab3f | ||
| 09973af099 | |||
| 3247da3dd0 | |||
| b505455f7c | |||
| 293949f081 | |||
| 8d7e442b3a | |||
|
|
f7b5211af3 | ||
| 7eb6d030dc | |||
| 47e75c31c7 | |||
| 20ff5eed22 | |||
| d23ca8db73 | |||
| 4dd28ac720 | |||
| 240b6016df | |||
| cf2aa827e4 | |||
| 5596345382 | |||
| 67748a2132 | |||
| c2333a9f35 | |||
| 4ec4c277b7 | |||
| a11dd00174 | |||
| cc7ebedf22 | |||
| e5bf1448f4 | |||
| f182bba6ff | |||
| 1f8810599b | |||
| 82248eb3b0 | |||
| abb9937787 | |||
| fd5ed64729 | |||
| 6751060d05 | |||
| ef664607b4 | |||
| 62e482a14b | |||
| a390ebf80f | |||
| 9a44960be7 | |||
| c846c59b9b | |||
|
|
902bf6326b | ||
|
|
bddf3bf502 | ||
|
|
284131da98 | ||
| 927c7ea3c2 | |||
| 0e51a79bb6 | |||
| 1de9911b73 | |||
| b4092c6619 | |||
| 024868bfd7 | |||
| a0bbfd6d02 | |||
| 2cb6843773 | |||
| 87e1480077 | |||
| bcd7f6a551 | |||
| 925b3af46b | |||
| ef4efa6a6b | |||
| 125646d89b | |||
| 7af7649448 | |||
| 827d467077 | |||
| ac8a3a12c4 | |||
| 286785491c | |||
| 263ea8910d | |||
| 202a942eef | |||
| c7bafecce3 | |||
| c67fe6f330 | |||
| 8c3f0d2c64 | |||
| 8494178b0d | |||
| 8a2c4c511e | |||
| dcca28944e | |||
| 92e6fd036e | |||
| eab1a1dd40 | |||
| 188d9611c9 | |||
| 74a52eed9d | |||
| 770e8425bd | |||
| 4783c6d9a3 | |||
| 2b2bcf4586 | |||
| 77f517a9f6 | |||
| 49d54f7fe6 | |||
| 8b7380876e | |||
| 7b3a7a9448 | |||
| 270ad1b889 | |||
| bcf7cf10d3 | |||
| 8930c3fbb7 | |||
| e6f870bda7 | |||
| 8feab7cc48 | |||
| aa6afdf440 | |||
| 6b1ed63b48 | |||
| b50855855b | |||
| 150e8ad698 | |||
| 035a84e696 | |||
| 565082f515 | |||
| 8c504bd029 | |||
| f6c0728a59 | |||
| 70a17dc10a | |||
| f14efa64f0 | |||
| 42f4d26fe4 | |||
| 06c3cd6637 | |||
| 99738096ac | |||
| c6dfc8acaa | |||
| 762f20d179 | |||
| 92aec349c3 | |||
| 2dcd30b21c | |||
| a7a3c679d1 | |||
| 5c6eba20e7 | |||
| 0a68a9c278 | |||
| a13cb01005 | |||
| 9fc0b5f88b | |||
| 6a7433ba2a | |||
| a754ff7c0c | |||
| e08276c2e2 | |||
| b7b28f6b9a | |||
| f63ff80d46 | |||
| 8fd745eab0 | |||
| c7ed807129 | |||
| c6fd9c1c23 | |||
| b5d3b699cf | |||
| 5279c2aa0f | |||
| 0ddc8de00b | |||
| 8d6eb34aee | |||
| 0d93b2c31c | |||
| 3f6852030f | |||
| 458388359a | |||
| 2101e994d9 | |||
| 8a50a2d0b8 | |||
| 71d82e9d5b | |||
| c9049c3845 | |||
| daffa9e548 | |||
| e0ef8b2953 | |||
| f6c914c1e4 | |||
| b38484d18e | |||
| 75222e07cb | |||
| 4233a4b673 | |||
| c44a82a8cb | |||
| 37f7960f4a | |||
| 6dc7e792c8 | |||
| 81649d51e1 | |||
| 23f5d10ccb | |||
| e3f235acc1 | |||
| fa9ef1c816 | |||
| 77dab8ee15 | |||
| 51fbff3e4a | |||
| bd6493327f | |||
|
|
2141e9631c | ||
| be8d09c663 | |||
| 72bbbe3817 | |||
| c92add984c | |||
| 3542d6c824 | |||
| dc63d96e0b | |||
| 7c9a7e84c7 | |||
| 31180758b4 | |||
| ce25a41fe1 | |||
| 8fa8afdfa4 | |||
| e127547799 | |||
| 1fbf8b2e20 | |||
| e41bb5ebc5 | |||
| 7c311aea19 | |||
| 8a2b122015 | |||
| 40b0870cf8 | |||
| e6ab6d50eb | |||
| a9eff06976 | |||
| 416fe5e4c8 | |||
| ddb53bf8e4 | |||
| 0e6efda528 | |||
| f2413a7789 | |||
| 9553f46cf4 | |||
| 14c97d59c1 | |||
| a59aae760f | |||
| 0a5b34a07b | |||
| 62502ad720 | |||
| 6e43ae7190 | |||
| 0e1f744fcc | |||
| 2fc47782cf | |||
| 34d93306d6 | |||
| 336868ed0d | |||
| 2682f15b8e | |||
| 4c12e38c01 | |||
| 62bfe9c06e | |||
| 24be220f91 | |||
| cacd33e84f | |||
| 9475003059 | |||
| 8532ccebba | |||
| 9c55b1d06a | |||
| efd9075d9b | |||
| 4c4fa00a5d | |||
| 21d5ca1cdd | |||
| ec3c1a02fc | |||
| dc5dc6ab5b | |||
| 1cbd1d2bad | |||
| aa667728a1 | |||
| 9b11ea527a | |||
| 5787a1afb8 | |||
| 74c10f1139 | |||
| 7e3fac8937 | |||
| 6021edc855 | |||
| 8817c110d0 | |||
| d59db9df16 | |||
| 2d1e6db9fd | |||
| 5bfca99627 | |||
| 9ea3149b60 | |||
| 8f03480ed2 | |||
| caec730248 | |||
| f1fde75567 | |||
| 5fe3a46732 | |||
| e7d418183b | |||
| c576749b57 | |||
| c062aab1a9 | |||
| 0252addf05 | |||
| b7338c12d7 | |||
| 7c115823a7 | |||
| 47d007c0b6 | |||
| c9b283be60 | |||
| 112f21006c | |||
| 53654185ba | |||
| 2382446e10 | |||
| 24c20b6907 | |||
| 622490fbf3 | |||
| dd8894e673 | |||
| eb1b14da8a | |||
| 0005f23585 | |||
| fb233374a0 | |||
| 9c695ac343 | |||
| 2c136b005e | |||
| 7cf42589b3 | |||
| 6aa857dfa1 | |||
| 0f19355621 | |||
| aa99378adc | |||
| b4ccde2228 | |||
| 36c53b4917 | |||
| ef773d8d49 | |||
| fc3794f548 | |||
| 67ab44593b | |||
| 8076e410a9 | |||
| dd78ae8658 | |||
| 0f4b1435d9 | |||
| c4a303190a | |||
| 199ff66bd4 | |||
| 98ba3b2788 | |||
| 5ea2590891 | |||
| 0a42845a40 | |||
|
|
e6daa9a838 | ||
|
|
72621e0da4 | ||
|
|
d5da9c0728 | ||
|
|
eee5b98d78 | ||
|
|
cf084b410f | ||
| cf9bdd0f99 | |||
| 06136312bb | |||
| 7a407d5792 |
24
.github.old/ISSUE_TEMPLATE/bug_report.md
Normal file
24
.github.old/ISSUE_TEMPLATE/bug_report.md
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: For reporting bugs in go-micro
|
||||||
|
title: "[BUG]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
|
||||||
|
1. What are you trying to do?
|
||||||
|
2. What did you expect to happen?
|
||||||
|
3. What happens instead?
|
||||||
|
|
||||||
|
**How to reproduce the bug:**
|
||||||
|
|
||||||
|
If possible, please include a minimal code snippet here.
|
||||||
|
|
||||||
|
**Environment:**
|
||||||
|
Go Version: please paste `go version` output here
|
||||||
|
```
|
||||||
|
please paste `go env` output here
|
||||||
|
```
|
||||||
17
.github.old/ISSUE_TEMPLATE/feature-request---enhancement.md
Normal file
17
.github.old/ISSUE_TEMPLATE/feature-request---enhancement.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
name: Feature request / Enhancement
|
||||||
|
about: If you have a need not served by go-micro
|
||||||
|
title: "[FEATURE]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
||||||
14
.github.old/ISSUE_TEMPLATE/question.md
Normal file
14
.github.old/ISSUE_TEMPLATE/question.md
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
---
|
||||||
|
name: Question
|
||||||
|
about: Ask a question about go-micro
|
||||||
|
title: ''
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Before asking, please check if your question has already been answered:
|
||||||
|
|
||||||
|
1. Check the documentation - https://micro.mu/docs/
|
||||||
|
2. Check the examples and plugins - https://github.com/micro/examples & https://github.com/micro/go-plugins
|
||||||
|
3. Search existing issues
|
||||||
9
.github.old/PULL_REQUEST_TEMPLATE.md
Normal file
9
.github.old/PULL_REQUEST_TEMPLATE.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
## Pull Request template
|
||||||
|
Please, go through these steps before clicking submit on this PR.
|
||||||
|
|
||||||
|
1. Give a descriptive title to your PR.
|
||||||
|
2. Provide a description of your changes.
|
||||||
|
3. Make sure you have some relevant tests.
|
||||||
|
4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if applicable).
|
||||||
|
|
||||||
|
**PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING**
|
||||||
26
.github.old/dependabot.yml
Normal file
26
.github.old/dependabot.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
|
||||||
|
# Maintain dependencies for GitHub Actions
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
commit-message:
|
||||||
|
prefix: "chore"
|
||||||
|
include: "scope"
|
||||||
|
|
||||||
|
# Maintain dependencies for Golang
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
commit-message:
|
||||||
|
prefix: "chore"
|
||||||
|
include: "scope"
|
||||||
|
|
||||||
24
.github.old/workflows/autoapprove.yml
Normal file
24
.github.old/workflows/autoapprove.yml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
name: "autoapprove"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
autoapprove:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: approve
|
||||||
|
uses: hmarr/auto-approve-action@v3
|
||||||
|
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
|
||||||
|
id: approve
|
||||||
|
with:
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
21
.github.old/workflows/automerge.yml
Normal file
21
.github.old/workflows/automerge.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: "automerge"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
automerge:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.actor == 'vtolstov'
|
||||||
|
steps:
|
||||||
|
- name: merge
|
||||||
|
id: merge
|
||||||
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
47
.github.old/workflows/build.yml
Normal file
47
.github.old/workflows/build.yml
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
name: build
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- v3
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: cache
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: ${{ runner.os }}-go-
|
||||||
|
- name: deps
|
||||||
|
run: go get -v -t -d ./...
|
||||||
|
- name: test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: go test -mod readonly -v ./...
|
||||||
|
lint:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: lint
|
||||||
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
version: v1.30
|
||||||
|
# Optional: working directory, useful for monorepos
|
||||||
|
# working-directory: somedir
|
||||||
|
# Optional: golangci-lint command line arguments.
|
||||||
|
# args: --issues-exit-code=0
|
||||||
|
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||||
|
# only-new-issues: true
|
||||||
39
.github.old/workflows/codecov.yml
Normal file
39
.github.old/workflows/codecov.yml
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
name: "codecov"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["build"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
push:
|
||||||
|
branches: [ v3 ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ v3 ]
|
||||||
|
schedule:
|
||||||
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
codecov:
|
||||||
|
name: codecov
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'go' ]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
|
- name: Run coverage
|
||||||
|
run: go test -v -race -coverprofile=coverage.out -covermode=atomic ./...
|
||||||
|
- name: codecov
|
||||||
|
uses: codecov/codecov-action@v3.1.1
|
||||||
78
.github.old/workflows/codeql-analysis.yml
Normal file
78
.github.old/workflows/codeql-analysis.yml
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# For most projects, this workflow file will not need changing; you simply need
|
||||||
|
# to commit it to your repository.
|
||||||
|
#
|
||||||
|
# You may wish to alter this file to override the set of languages analyzed,
|
||||||
|
# or to provide custom queries or build logic.
|
||||||
|
#
|
||||||
|
# ******** NOTE ********
|
||||||
|
# We have attempted to detect the languages in your repository. Please check
|
||||||
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
|
# supported CodeQL languages.
|
||||||
|
#
|
||||||
|
name: "codeql"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
push:
|
||||||
|
branches: [ master, v3 ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ master, v3 ]
|
||||||
|
schedule:
|
||||||
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'go' ]
|
||||||
|
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||||
|
# Learn more:
|
||||||
|
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
|
# Initializes the CodeQL tools for scanning.
|
||||||
|
- name: init
|
||||||
|
uses: github/codeql-action/init@v2
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
|
# By default, queries listed here will override any specified in a config file.
|
||||||
|
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||||
|
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||||
|
|
||||||
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
|
- name: autobuild
|
||||||
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
|
# 📚 https://git.io/JvXDl
|
||||||
|
|
||||||
|
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||||
|
# and modify them (or add more) to build your code if your project
|
||||||
|
# uses a compiled language
|
||||||
|
|
||||||
|
#- run: |
|
||||||
|
# make bootstrap
|
||||||
|
# make release
|
||||||
|
|
||||||
|
- name: analyze
|
||||||
|
uses: github/codeql-action/analyze@v2
|
||||||
27
.github.old/workflows/dependabot-automerge.yml
Normal file
27
.github.old/workflows/dependabot-automerge.yml
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
name: "dependabot-automerge"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
automerge:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.actor == 'dependabot[bot]'
|
||||||
|
steps:
|
||||||
|
- name: metadata
|
||||||
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v1.3.6
|
||||||
|
with:
|
||||||
|
github-token: "${{ secrets.TOKEN }}"
|
||||||
|
- name: merge
|
||||||
|
id: merge
|
||||||
|
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||||
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
40
.github.old/workflows/pr.yml
Normal file
40
.github.old/workflows/pr.yml
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
name: prbuild
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- v3
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: cache
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: ${{ runner.os }}-go-
|
||||||
|
- name: deps
|
||||||
|
run: go get -v -t -d ./...
|
||||||
|
- name: test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: go test -mod readonly -v ./...
|
||||||
|
lint:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: lint
|
||||||
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
version: v1.30
|
||||||
3
.github/FUNDING.yml
vendored
3
.github/FUNDING.yml
vendored
@@ -1,3 +0,0 @@
|
|||||||
# These are supported funding model platforms
|
|
||||||
|
|
||||||
github: micro
|
|
||||||
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: Bug report
|
name: Bug report
|
||||||
about: For reporting bugs in go-micro
|
about: For reporting bugs in micro
|
||||||
title: "[BUG]"
|
title: "[BUG]"
|
||||||
labels: ''
|
labels: ''
|
||||||
assignees: ''
|
assignees: ''
|
||||||
@@ -16,9 +16,3 @@ assignees: ''
|
|||||||
**How to reproduce the bug:**
|
**How to reproduce the bug:**
|
||||||
|
|
||||||
If possible, please include a minimal code snippet here.
|
If possible, please include a minimal code snippet here.
|
||||||
|
|
||||||
**Environment:**
|
|
||||||
Go Version: please paste `go version` output here
|
|
||||||
```
|
|
||||||
please paste `go env` output here
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: Feature request / Enhancement
|
name: Feature request / Enhancement
|
||||||
about: If you have a need not served by go-micro
|
about: If you have a need not served by micro
|
||||||
title: "[FEATURE]"
|
title: "[FEATURE]"
|
||||||
labels: ''
|
labels: ''
|
||||||
assignees: ''
|
assignees: ''
|
||||||
@@ -14,4 +14,4 @@ A clear and concise description of what the problem is. Ex. I'm always frustrate
|
|||||||
A clear and concise description of what you want to happen.
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
**Additional context**
|
**Additional context**
|
||||||
Add any other context or screenshots about the feature request here.
|
Add any other context or screenshots about the feature request here.
|
||||||
10
.github/ISSUE_TEMPLATE/question.md
vendored
10
.github/ISSUE_TEMPLATE/question.md
vendored
@@ -1,14 +1,8 @@
|
|||||||
---
|
---
|
||||||
name: Question
|
name: Question
|
||||||
about: Ask a question about go-micro
|
about: Ask a question about micro
|
||||||
title: ''
|
title: ''
|
||||||
labels: ''
|
labels: ''
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Before asking, please check if your question has already been answered:
|
|
||||||
|
|
||||||
1. Check the documentation - https://micro.mu/docs/
|
|
||||||
2. Check the examples and plugins - https://github.com/micro/examples & https://github.com/micro/go-plugins
|
|
||||||
3. Search existing issues
|
|
||||||
28
.github/autoapprove.yml
vendored
Normal file
28
.github/autoapprove.yml
vendored
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
name: "autoapprove"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["prbuild"]
|
||||||
|
types:
|
||||||
|
- completed
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
autoapprove:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: approve
|
||||||
|
run: [ "curl -o tea https://dl.gitea.com/tea/main/tea-main-linux-amd64",
|
||||||
|
"chmod +x ./tea",
|
||||||
|
"./tea login add --name unistack --token ${{ secrets.GITHUB_TOKEN }} --url https://git.unistack.org",
|
||||||
|
"./tea pr --repo ${{ github.event.repository.name }}"
|
||||||
|
]
|
||||||
|
if: github.actor == 'vtolstov'
|
||||||
|
id: approve
|
||||||
|
with:
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
15
.github/generate.sh
vendored
15
.github/generate.sh
vendored
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/bash -e
|
|
||||||
|
|
||||||
find . -type f -name '*.pb.*.go' -o -name '*.pb.go' -a ! -name 'message.pb.go' -delete
|
|
||||||
PROTOS=$(find . -type f -name '*.proto' | grep -v proto/google/api)
|
|
||||||
|
|
||||||
mkdir -p proto/google/api
|
|
||||||
curl -s -o proto/google/api/annotations.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto
|
|
||||||
curl -s -o proto/google/api/http.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto
|
|
||||||
|
|
||||||
for PROTO in $PROTOS; do
|
|
||||||
echo $PROTO
|
|
||||||
protoc -I./proto -I. -I$(dirname $PROTO) --go_out=plugins=grpc,paths=source_relative:. --micro_out=paths=source_relative:. $PROTO
|
|
||||||
done
|
|
||||||
|
|
||||||
rm -r proto
|
|
||||||
22
.github/workflows/docker.yml
vendored
22
.github/workflows/docker.yml
vendored
@@ -1,22 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
tags:
|
|
||||||
- v2.*
|
|
||||||
- v3.*
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
name: Check out repository
|
|
||||||
- uses: elgohr/Publish-Docker-Github-Action@2.12
|
|
||||||
name: Build and Push Docker Image
|
|
||||||
with:
|
|
||||||
name: micro/go-micro
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
tag_names: true
|
|
||||||
53
.github/workflows/job_coverage.yml
vendored
Normal file
53
.github/workflows/job_coverage.yml
vendored
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
name: coverage
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main, v3, v4 ]
|
||||||
|
paths-ignore:
|
||||||
|
- '.github/**'
|
||||||
|
- '.gitea/**'
|
||||||
|
pull_request:
|
||||||
|
branches: [ main, v3, v4 ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build:
|
||||||
|
if: github.server_url != 'https://github.com'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
filter: 'blob:none'
|
||||||
|
|
||||||
|
- name: setup go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
cache-dependency-path: "**/*.sum"
|
||||||
|
go-version: 'stable'
|
||||||
|
|
||||||
|
- name: test coverage
|
||||||
|
run: |
|
||||||
|
go test -v -cover ./... -covermode=count -coverprofile coverage.out -coverpkg ./...
|
||||||
|
go tool cover -func coverage.out -o coverage.out
|
||||||
|
|
||||||
|
- name: coverage badge
|
||||||
|
uses: tj-actions/coverage-badge-go@v2
|
||||||
|
with:
|
||||||
|
green: 80
|
||||||
|
filename: coverage.out
|
||||||
|
|
||||||
|
- uses: stefanzweifel/git-auto-commit-action@v4
|
||||||
|
name: autocommit
|
||||||
|
with:
|
||||||
|
commit_message: Apply Code Coverage Badge
|
||||||
|
skip_fetch: false
|
||||||
|
skip_checkout: false
|
||||||
|
file_pattern: ./README.md
|
||||||
|
|
||||||
|
- name: push
|
||||||
|
if: steps.auto-commit-action.outputs.changes_detected == 'true'
|
||||||
|
uses: ad-m/github-push-action@master
|
||||||
|
with:
|
||||||
|
github_token: ${{ github.token }}
|
||||||
|
branch: ${{ github.ref }}
|
||||||
29
.github/workflows/job_lint.yml
vendored
Normal file
29
.github/workflows/job_lint.yml
vendored
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
name: lint
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, reopened, synchronize]
|
||||||
|
branches: [ master, v3, v4 ]
|
||||||
|
paths-ignore:
|
||||||
|
- '.github/**'
|
||||||
|
- '.gitea/**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
filter: 'blob:none'
|
||||||
|
- name: setup go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
cache-dependency-path: "**/*.sum"
|
||||||
|
go-version: 'stable'
|
||||||
|
- name: setup deps
|
||||||
|
run: go get -v ./...
|
||||||
|
- name: run lint
|
||||||
|
uses: golangci/golangci-lint-action@v6
|
||||||
|
with:
|
||||||
|
version: 'latest'
|
||||||
31
.github/workflows/job_test.yml
vendored
Normal file
31
.github/workflows/job_test.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
name: test
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, reopened, synchronize]
|
||||||
|
branches: [ master, v3, v4 ]
|
||||||
|
push:
|
||||||
|
branches: [ master, v3, v4 ]
|
||||||
|
paths-ignore:
|
||||||
|
- '.github/**'
|
||||||
|
- '.gitea/**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
filter: 'blob:none'
|
||||||
|
- name: setup go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
cache-dependency-path: "**/*.sum"
|
||||||
|
go-version: 'stable'
|
||||||
|
- name: setup deps
|
||||||
|
run: go get -v ./...
|
||||||
|
- name: run test
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
run: go test -mod readonly -v ./...
|
||||||
50
.github/workflows/job_tests.yml
vendored
Normal file
50
.github/workflows/job_tests.yml
vendored
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
name: test
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, reopened, synchronize]
|
||||||
|
branches: [ master, v3, v4 ]
|
||||||
|
push:
|
||||||
|
branches: [ master, v3, v4 ]
|
||||||
|
paths-ignore:
|
||||||
|
- '.github/**'
|
||||||
|
- '.gitea/**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
filter: 'blob:none'
|
||||||
|
- name: checkout tests
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: master
|
||||||
|
filter: 'blob:none'
|
||||||
|
repository: unistack-org/micro-tests
|
||||||
|
path: micro-tests
|
||||||
|
- name: setup go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
cache-dependency-path: "**/*.sum"
|
||||||
|
go-version: 'stable'
|
||||||
|
- name: setup go work
|
||||||
|
env:
|
||||||
|
GOWORK: ${{ github.workspace }}/go.work
|
||||||
|
run: |
|
||||||
|
go work init
|
||||||
|
go work use .
|
||||||
|
go work use micro-tests
|
||||||
|
- name: setup deps
|
||||||
|
env:
|
||||||
|
GOWORK: ${{ github.workspace }}/go.work
|
||||||
|
run: go get -v ./...
|
||||||
|
- name: run tests
|
||||||
|
env:
|
||||||
|
INTEGRATION_TESTS: yes
|
||||||
|
GOWORK: ${{ github.workspace }}/go.work
|
||||||
|
run: |
|
||||||
|
cd micro-tests
|
||||||
|
go test -mod readonly -v ./... || true
|
||||||
28
.github/workflows/pr.yml
vendored
28
.github/workflows/pr.yml
vendored
@@ -1,28 +0,0 @@
|
|||||||
name: PR Sanity Check
|
|
||||||
on: pull_request
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
prtest:
|
|
||||||
name: PR sanity check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- name: Set up Go 1.13
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.13
|
|
||||||
id: go
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Get dependencies
|
|
||||||
run: |
|
|
||||||
go get -v -t -d ./...
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
id: tests
|
|
||||||
env:
|
|
||||||
IN_TRAVIS_CI: yes
|
|
||||||
run: go test -v ./...
|
|
||||||
41
.github/workflows/scripts/build-all-examples.sh
vendored
41
.github/workflows/scripts/build-all-examples.sh
vendored
@@ -1,41 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# set -x
|
|
||||||
|
|
||||||
function build_binary {
|
|
||||||
echo building $1
|
|
||||||
pushd $1
|
|
||||||
go build -o _main
|
|
||||||
local ret=$?
|
|
||||||
if [ $ret -gt 0 ]; then
|
|
||||||
failed=1
|
|
||||||
failed_arr+=($1)
|
|
||||||
fi
|
|
||||||
popd
|
|
||||||
}
|
|
||||||
|
|
||||||
function is_main {
|
|
||||||
grep "package main" -l -dskip $1/*.go > /dev/null 2>&1
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function check_dir {
|
|
||||||
is_main $1
|
|
||||||
local ret=$?
|
|
||||||
if [ $ret == 0 ]; then
|
|
||||||
build_binary $1 $2
|
|
||||||
fi
|
|
||||||
for filename in $1/*; do
|
|
||||||
if [ -d $filename ]; then
|
|
||||||
check_dir $filename $2
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
}
|
|
||||||
failed_arr=()
|
|
||||||
failed=0
|
|
||||||
go mod edit -replace github.com/micro/go-micro/v2=github.com/$2/v2@$1
|
|
||||||
check_dir . $1
|
|
||||||
if [ $failed -gt 0 ]; then
|
|
||||||
echo Some builds failed
|
|
||||||
printf '%s\n' "${failed_arr[@]}"
|
|
||||||
fi
|
|
||||||
exit $failed
|
|
||||||
19
.github/workflows/scripts/build-micro.sh
vendored
19
.github/workflows/scripts/build-micro.sh
vendored
@@ -1,19 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# set -x
|
|
||||||
|
|
||||||
failed=0
|
|
||||||
go mod edit -replace github.com/micro/go-micro/v2=github.com/$2/v2@$1
|
|
||||||
# basic test, build the binary
|
|
||||||
go install
|
|
||||||
failed=$?
|
|
||||||
if [ $failed -gt 0 ]; then
|
|
||||||
exit $failed
|
|
||||||
fi
|
|
||||||
# unit tests
|
|
||||||
IN_TRAVIS_CI=yes go test -v ./...
|
|
||||||
|
|
||||||
./scripts/test-docker.sh
|
|
||||||
# Generate keys for JWT tests
|
|
||||||
ssh-keygen -f /tmp/sshkey -m pkcs8 -q -N ""
|
|
||||||
ssh-keygen -f /tmp/sshkey -e -m pkcs8 > /tmp/sshkey.pub
|
|
||||||
go clean -testcache && IN_TRAVIS_CI=yes go test --tags=integration -v ./test
|
|
||||||
54
.github/workflows/tests.yml
vendored
54
.github/workflows/tests.yml
vendored
@@ -1,54 +0,0 @@
|
|||||||
name: Run tests
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
test:
|
|
||||||
name: Test repo
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- name: Set up Go 1.13
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.13
|
|
||||||
id: go
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Get dependencies
|
|
||||||
run: |
|
|
||||||
go get -v -t -d ./...
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
id: tests
|
|
||||||
env:
|
|
||||||
IN_TRAVIS_CI: yes
|
|
||||||
run: |
|
|
||||||
wget -qO- https://binaries.cockroachdb.com/cockroach-v20.1.4.linux-amd64.tgz | tar xvz
|
|
||||||
cockroach-v20.1.4.linux-amd64/cockroach start-single-node --insecure &
|
|
||||||
go test -v ./...
|
|
||||||
|
|
||||||
- name: Notify of test failure
|
|
||||||
if: failure()
|
|
||||||
uses: rtCamp/action-slack-notify@v2.0.0
|
|
||||||
env:
|
|
||||||
SLACK_CHANNEL: build
|
|
||||||
SLACK_COLOR: '#BF280A'
|
|
||||||
SLACK_ICON: https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png
|
|
||||||
SLACK_TITLE: Tests Failed
|
|
||||||
SLACK_USERNAME: GitHub Actions
|
|
||||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
- name: Notify of test success
|
|
||||||
if: success()
|
|
||||||
uses: rtCamp/action-slack-notify@v2.0.0
|
|
||||||
env:
|
|
||||||
SLACK_CHANNEL: build
|
|
||||||
SLACK_COLOR: '#1FAD2B'
|
|
||||||
SLACK_ICON: https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png
|
|
||||||
SLACK_TITLE: Tests Passed
|
|
||||||
SLACK_USERNAME: GitHub Actions
|
|
||||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,6 +1,8 @@
|
|||||||
# Develop tools
|
# Develop tools
|
||||||
/.vscode/
|
/.vscode/
|
||||||
/.idea/
|
/.idea/
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
|
||||||
# Binaries for programs and plugins
|
# Binaries for programs and plugins
|
||||||
*.exe
|
*.exe
|
||||||
@@ -13,6 +15,7 @@
|
|||||||
_obj
|
_obj
|
||||||
_test
|
_test
|
||||||
_build
|
_build
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
# Architecture specific extensions/prefixes
|
# Architecture specific extensions/prefixes
|
||||||
*.[568vq]
|
*.[568vq]
|
||||||
|
|||||||
@@ -1,26 +1,5 @@
|
|||||||
run:
|
run:
|
||||||
deadline: 10m
|
concurrency: 8
|
||||||
linters:
|
timeout: 5m
|
||||||
disable-all: false
|
issues-exit-code: 1
|
||||||
enable-all: false
|
tests: true
|
||||||
enable:
|
|
||||||
- megacheck
|
|
||||||
- staticcheck
|
|
||||||
- deadcode
|
|
||||||
- varcheck
|
|
||||||
- gosimple
|
|
||||||
- unused
|
|
||||||
- prealloc
|
|
||||||
- scopelint
|
|
||||||
- gocritic
|
|
||||||
- goimports
|
|
||||||
- unconvert
|
|
||||||
- govet
|
|
||||||
- nakedret
|
|
||||||
- structcheck
|
|
||||||
- gosec
|
|
||||||
disable:
|
|
||||||
- maligned
|
|
||||||
- interfacer
|
|
||||||
- typecheck
|
|
||||||
- dupl
|
|
||||||
|
|||||||
13
Dockerfile
13
Dockerfile
@@ -1,13 +0,0 @@
|
|||||||
FROM golang:1.13-alpine
|
|
||||||
|
|
||||||
RUN mkdir /user && \
|
|
||||||
echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \
|
|
||||||
echo 'nobody:x:65534:' > /user/group
|
|
||||||
|
|
||||||
ENV GO111MODULE=on
|
|
||||||
RUN apk --no-cache add make git gcc libtool musl-dev ca-certificates dumb-init && \
|
|
||||||
rm -rf /var/cache/apk/* /tmp/*
|
|
||||||
|
|
||||||
WORKDIR /
|
|
||||||
COPY ./go.mod ./go.sum ./
|
|
||||||
RUN go mod download && rm go.mod go.sum
|
|
||||||
3
LICENSE
3
LICENSE
@@ -176,7 +176,8 @@
|
|||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
Copyright 2015 Asim Aslam.
|
Copyright 2015-2020 Asim Aslam.
|
||||||
|
Copyright 2019-2020 Unistack LLC.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
49
README.md
49
README.md
@@ -1,56 +1,43 @@
|
|||||||
# Go Micro [](https://opensource.org/licenses/Apache-2.0) [](https://pkg.go.dev/github.com/micro/go-micro/v3?tab=overview) [](https://travis-ci.org/micro/go-micro) [](https://goreportcard.com/report/github.com/micro/go-micro)
|
# Micro
|
||||||
|

|
||||||
|
[](https://opensource.org/licenses/Apache-2.0)
|
||||||
|
[](https://pkg.go.dev/go.unistack.org/micro/v3?tab=overview)
|
||||||
|
[](https://git.unistack.org/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Av3+event%3Apush)
|
||||||
|
[](https://goreportcard.com/report/go.unistack.org/micro/v3)
|
||||||
|
|
||||||
Go Micro is a standard library for microservices.
|
Micro is a standard library for microservices.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Go Micro provides the core requirements for distributed systems development including RPC and Event driven communication.
|
Micro provides the core requirements for distributed systems development including SYNC and ASYNC communication.
|
||||||
The **Micro** philosophy is sane defaults with a pluggable architecture. We provide defaults to get you started quickly
|
|
||||||
but everything can be easily swapped out.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
Go Micro abstracts away the details of distributed systems. Here are the main features.
|
Micro abstracts away the details of distributed systems. Main features:
|
||||||
|
|
||||||
- **Authentication** - Auth is built in as a first class citizen. Authentication and authorization enable secure
|
|
||||||
zero trust networking by providing every service an identity and certificates. This additionally includes rule
|
|
||||||
based access control.
|
|
||||||
|
|
||||||
- **Dynamic Config** - Load and hot reload dynamic config from anywhere. The config interface provides a way to load application
|
- **Dynamic Config** - Load and hot reload dynamic config from anywhere. The config interface provides a way to load application
|
||||||
level config from any source such as env vars, file, etcd. You can merge the sources and even define fallbacks.
|
level config from any source such as env vars, cmdline, file, consul, vault, etc... You can merge the sources and even define fallbacks.
|
||||||
|
|
||||||
- **Data Storage** - A simple data store interface to read, write and delete records. It includes support for memory, file and
|
- **Data Storage** - A simple data store interface to read, write and delete records. It includes support for memory, file and
|
||||||
CockroachDB by default. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.
|
s3. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.
|
||||||
|
|
||||||
- **Service Discovery** - Automatic service registration and name resolution. Service discovery is at the core of micro service
|
- **Service Discovery** - Automatic service registration and name resolution. Service discovery is at the core of micro service
|
||||||
development. When service A needs to speak to service B it needs the location of that service. The default discovery mechanism is
|
development.
|
||||||
multicast DNS (mdns), a zeroconf system.
|
|
||||||
|
|
||||||
- **Load Balancing** - Client side load balancing built on service discovery. Once we have the addresses of any number of instances
|
|
||||||
of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution
|
|
||||||
across the services and retry a different node if there's a problem.
|
|
||||||
|
|
||||||
- **Message Encoding** - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type
|
- **Message Encoding** - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type
|
||||||
to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client
|
to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client
|
||||||
and server handle this by default. This includes protobuf and json by default.
|
and server handle this by default.
|
||||||
|
|
||||||
- **gRPC Transport** - gRPC based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.
|
- **Async Messaging** - Pub/Sub is built in as a first class citizen for asynchronous communication and event driven architectures.
|
||||||
|
Event notifications are a core pattern in micro service development.
|
||||||
- **Async Messaging** - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures.
|
|
||||||
Event notifications are a core pattern in micro service development. The default messaging system is a HTTP event message broker.
|
|
||||||
|
|
||||||
- **Synchronization** - Distributed systems are often built in an eventually consistent manner. Support for distributed locking and
|
- **Synchronization** - Distributed systems are often built in an eventually consistent manner. Support for distributed locking and
|
||||||
leadership are built in as a Sync interface. When using an eventually consistent database or scheduling use the Sync interface.
|
leadership are built in as a Sync interface. When using an eventually consistent database or scheduling use the Sync interface.
|
||||||
|
|
||||||
- **Pluggable Interfaces** - Go Micro makes use of Go interfaces for each distributed system abstraction. Because of this these interfaces
|
- **Pluggable Interfaces** - Micro makes use of Go interfaces for each system abstraction. Because of this these interfaces
|
||||||
are pluggable and allows Go Micro to be runtime agnostic. You can plugin any underlying technology. Find plugins in
|
are pluggable and allows Micro to be runtime agnostic.
|
||||||
[github.com/micro/go-plugins](https://github.com/micro/go-plugins).
|
|
||||||
|
|
||||||
## Getting Started
|
|
||||||
|
|
||||||
See [pkg.go.dev](https://pkg.go.dev/github.com/micro/go-micro/v3?tab=overview) for usage.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Go Micro is Apache 2.0 licensed.
|
Micro is Apache 2.0 licensed.
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
theme: jekyll-theme-architect
|
|
||||||
187
api/api.go
187
api/api.go
@@ -1,187 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/server"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Api interface {
|
|
||||||
// Initialise options
|
|
||||||
Init(...Option) error
|
|
||||||
// Get the options
|
|
||||||
Options() Options
|
|
||||||
// Register a http handler
|
|
||||||
Register(*Endpoint) error
|
|
||||||
// Register a route
|
|
||||||
Deregister(*Endpoint) error
|
|
||||||
// Implementation of api
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Options struct{}
|
|
||||||
|
|
||||||
type Option func(*Options) error
|
|
||||||
|
|
||||||
// Endpoint is a mapping between an RPC method and HTTP endpoint
|
|
||||||
type Endpoint struct {
|
|
||||||
// RPC Method e.g. Greeter.Hello
|
|
||||||
Name string
|
|
||||||
// Description e.g what's this endpoint for
|
|
||||||
Description string
|
|
||||||
// API Handler e.g rpc, proxy
|
|
||||||
Handler string
|
|
||||||
// HTTP Host e.g example.com
|
|
||||||
Host []string
|
|
||||||
// HTTP Methods e.g GET, POST
|
|
||||||
Method []string
|
|
||||||
// HTTP Path e.g /greeter. Expect POSIX regex
|
|
||||||
Path []string
|
|
||||||
// Body destination
|
|
||||||
// "*" or "" - top level message value
|
|
||||||
// "string" - inner message value
|
|
||||||
Body string
|
|
||||||
// Stream flag
|
|
||||||
Stream bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Service represents an API service
|
|
||||||
type Service struct {
|
|
||||||
// Name of service
|
|
||||||
Name string
|
|
||||||
// The endpoint for this service
|
|
||||||
Endpoint *Endpoint
|
|
||||||
// Versions of this service
|
|
||||||
Services []*registry.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
func strip(s string) string {
|
|
||||||
return strings.TrimSpace(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
func slice(s string) []string {
|
|
||||||
var sl []string
|
|
||||||
|
|
||||||
for _, p := range strings.Split(s, ",") {
|
|
||||||
if str := strip(p); len(str) > 0 {
|
|
||||||
sl = append(sl, strip(p))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sl
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encode encodes an endpoint to endpoint metadata
|
|
||||||
func Encode(e *Endpoint) map[string]string {
|
|
||||||
if e == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// endpoint map
|
|
||||||
ep := make(map[string]string)
|
|
||||||
|
|
||||||
// set vals only if they exist
|
|
||||||
set := func(k, v string) {
|
|
||||||
if len(v) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ep[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
set("endpoint", e.Name)
|
|
||||||
set("description", e.Description)
|
|
||||||
set("handler", e.Handler)
|
|
||||||
set("method", strings.Join(e.Method, ","))
|
|
||||||
set("path", strings.Join(e.Path, ","))
|
|
||||||
set("host", strings.Join(e.Host, ","))
|
|
||||||
|
|
||||||
return ep
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode decodes endpoint metadata into an endpoint
|
|
||||||
func Decode(e map[string]string) *Endpoint {
|
|
||||||
if e == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Endpoint{
|
|
||||||
Name: e["endpoint"],
|
|
||||||
Description: e["description"],
|
|
||||||
Method: slice(e["method"]),
|
|
||||||
Path: slice(e["path"]),
|
|
||||||
Host: slice(e["host"]),
|
|
||||||
Handler: e["handler"],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate validates an endpoint to guarantee it won't blow up when being served
|
|
||||||
func Validate(e *Endpoint) error {
|
|
||||||
if e == nil {
|
|
||||||
return errors.New("endpoint is nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(e.Name) == 0 {
|
|
||||||
return errors.New("name required")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range e.Path {
|
|
||||||
ps := p[0]
|
|
||||||
pe := p[len(p)-1]
|
|
||||||
|
|
||||||
if ps == '^' && pe == '$' {
|
|
||||||
_, err := regexp.CompilePOSIX(p)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else if ps == '^' && pe != '$' {
|
|
||||||
return errors.New("invalid path")
|
|
||||||
} else if ps != '^' && pe == '$' {
|
|
||||||
return errors.New("invalid path")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(e.Handler) == 0 {
|
|
||||||
return errors.New("invalid handler")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
Design ideas
|
|
||||||
|
|
||||||
// Gateway is an api gateway interface
|
|
||||||
type Gateway interface {
|
|
||||||
// Register a http handler
|
|
||||||
Handle(pattern string, http.Handler)
|
|
||||||
// Register a route
|
|
||||||
RegisterRoute(r Route)
|
|
||||||
// Init initialises the command line.
|
|
||||||
// It also parses further options.
|
|
||||||
Init(...Option) error
|
|
||||||
// Run the gateway
|
|
||||||
Run() error
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewGateway returns a new api gateway
|
|
||||||
func NewGateway() Gateway {
|
|
||||||
return newGateway()
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
// WithEndpoint returns a server.HandlerOption with endpoint metadata set
|
|
||||||
//
|
|
||||||
// Usage:
|
|
||||||
//
|
|
||||||
// proto.RegisterHandler(service.Server(), new(Handler), api.WithEndpoint(
|
|
||||||
// &api.Endpoint{
|
|
||||||
// Name: "Greeter.Hello",
|
|
||||||
// Path: []string{"/greeter"},
|
|
||||||
// },
|
|
||||||
// ))
|
|
||||||
func WithEndpoint(e *Endpoint) server.HandlerOption {
|
|
||||||
return server.EndpointMetadata(e.Name, Encode(e))
|
|
||||||
}
|
|
||||||
152
api/api_test.go
152
api/api_test.go
@@ -1,152 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestEncoding(t *testing.T) {
|
|
||||||
testData := []*Endpoint{
|
|
||||||
nil,
|
|
||||||
{
|
|
||||||
Name: "Foo.Bar",
|
|
||||||
Description: "A test endpoint",
|
|
||||||
Handler: "meta",
|
|
||||||
Host: []string{"foo.com"},
|
|
||||||
Method: []string{"GET"},
|
|
||||||
Path: []string{"/test"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
compare := func(expect, got []string) bool {
|
|
||||||
// no data to compare, return true
|
|
||||||
if len(expect) == 0 && len(got) == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
// no data expected but got some return false
|
|
||||||
if len(expect) == 0 && len(got) > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// compare expected with what we got
|
|
||||||
for _, e := range expect {
|
|
||||||
var seen bool
|
|
||||||
for _, g := range got {
|
|
||||||
if e == g {
|
|
||||||
seen = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !seen {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// we're done, return true
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, d := range testData {
|
|
||||||
// encode
|
|
||||||
e := Encode(d)
|
|
||||||
// decode
|
|
||||||
de := Decode(e)
|
|
||||||
|
|
||||||
// nil endpoint returns nil
|
|
||||||
if d == nil {
|
|
||||||
if e != nil {
|
|
||||||
t.Fatalf("expected nil got %v", e)
|
|
||||||
}
|
|
||||||
if de != nil {
|
|
||||||
t.Fatalf("expected nil got %v", de)
|
|
||||||
}
|
|
||||||
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// check encoded map
|
|
||||||
name := e["endpoint"]
|
|
||||||
desc := e["description"]
|
|
||||||
method := strings.Split(e["method"], ",")
|
|
||||||
path := strings.Split(e["path"], ",")
|
|
||||||
host := strings.Split(e["host"], ",")
|
|
||||||
handler := e["handler"]
|
|
||||||
|
|
||||||
if name != d.Name {
|
|
||||||
t.Fatalf("expected %v got %v", d.Name, name)
|
|
||||||
}
|
|
||||||
if desc != d.Description {
|
|
||||||
t.Fatalf("expected %v got %v", d.Description, desc)
|
|
||||||
}
|
|
||||||
if handler != d.Handler {
|
|
||||||
t.Fatalf("expected %v got %v", d.Handler, handler)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Method, method); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Method, method)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Path, path); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Path, path)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Host, host); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Host, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if de.Name != d.Name {
|
|
||||||
t.Fatalf("expected %v got %v", d.Name, de.Name)
|
|
||||||
}
|
|
||||||
if de.Description != d.Description {
|
|
||||||
t.Fatalf("expected %v got %v", d.Description, de.Description)
|
|
||||||
}
|
|
||||||
if de.Handler != d.Handler {
|
|
||||||
t.Fatalf("expected %v got %v", d.Handler, de.Handler)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Method, de.Method); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Method, de.Method)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Path, de.Path); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Path, de.Path)
|
|
||||||
}
|
|
||||||
if ok := compare(d.Host, de.Host); !ok {
|
|
||||||
t.Fatalf("expected %v got %v", d.Host, de.Host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidate(t *testing.T) {
|
|
||||||
epPcre := &Endpoint{
|
|
||||||
Name: "Foo.Bar",
|
|
||||||
Description: "A test endpoint",
|
|
||||||
Handler: "meta",
|
|
||||||
Host: []string{"foo.com"},
|
|
||||||
Method: []string{"GET"},
|
|
||||||
Path: []string{"^/test/?$"},
|
|
||||||
}
|
|
||||||
if err := Validate(epPcre); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
epGpath := &Endpoint{
|
|
||||||
Name: "Foo.Bar",
|
|
||||||
Description: "A test endpoint",
|
|
||||||
Handler: "meta",
|
|
||||||
Host: []string{"foo.com"},
|
|
||||||
Method: []string{"GET"},
|
|
||||||
Path: []string{"/test/{id}"},
|
|
||||||
}
|
|
||||||
if err := Validate(epGpath); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
epPcreInvalid := &Endpoint{
|
|
||||||
Name: "Foo.Bar",
|
|
||||||
Description: "A test endpoint",
|
|
||||||
Handler: "meta",
|
|
||||||
Host: []string{"foo.com"},
|
|
||||||
Method: []string{"GET"},
|
|
||||||
Path: []string{"/test/?$"},
|
|
||||||
}
|
|
||||||
if err := Validate(epPcreInvalid); err == nil {
|
|
||||||
t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
// Package api provides an http-rpc handler which provides the entire http request over rpc
|
|
||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
goapi "github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
api "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
|
||||||
"github.com/micro/go-micro/v3/util/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type apiHandler struct {
|
|
||||||
opts handler.Options
|
|
||||||
s *goapi.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
Handler = "api"
|
|
||||||
)
|
|
||||||
|
|
||||||
// API handler is the default handler which takes api.Request and returns api.Response
|
|
||||||
func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
bsize := handler.DefaultMaxRecvSize
|
|
||||||
if a.opts.MaxRecvSize > 0 {
|
|
||||||
bsize = a.opts.MaxRecvSize
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
|
||||||
request, err := requestToProto(r)
|
|
||||||
if err != nil {
|
|
||||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(er.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var service *goapi.Service
|
|
||||||
|
|
||||||
if a.s != nil {
|
|
||||||
// we were given the service
|
|
||||||
service = a.s
|
|
||||||
} else if a.opts.Router != nil {
|
|
||||||
// try get service from router
|
|
||||||
s, err := a.opts.Router.Route(r)
|
|
||||||
if err != nil {
|
|
||||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(er.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
service = s
|
|
||||||
} else {
|
|
||||||
// we have no way of routing the request
|
|
||||||
er := errors.InternalServerError("go.micro.api", "no route found")
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(er.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// create request and response
|
|
||||||
c := a.opts.Client
|
|
||||||
req := c.NewRequest(service.Name, service.Endpoint.Name, request)
|
|
||||||
rsp := &api.Response{}
|
|
||||||
|
|
||||||
// create the context from headers
|
|
||||||
cx := ctx.FromRequest(r)
|
|
||||||
|
|
||||||
if err := c.Call(cx, req, rsp, client.WithRouter(router.New(service.Services))); err != nil {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
ce := errors.Parse(err.Error())
|
|
||||||
switch ce.Code {
|
|
||||||
case 0:
|
|
||||||
w.WriteHeader(500)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(int(ce.Code))
|
|
||||||
}
|
|
||||||
w.Write([]byte(ce.Error()))
|
|
||||||
return
|
|
||||||
} else if rsp.StatusCode == 0 {
|
|
||||||
rsp.StatusCode = http.StatusOK
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, header := range rsp.GetHeader() {
|
|
||||||
for _, val := range header.Values {
|
|
||||||
w.Header().Add(header.Key, val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(w.Header().Get("Content-Type")) == 0 {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(int(rsp.StatusCode))
|
|
||||||
w.Write([]byte(rsp.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *apiHandler) String() string {
|
|
||||||
return "api"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
return &apiHandler{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithService(s *goapi.Service, opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
return &apiHandler{
|
|
||||||
opts: options,
|
|
||||||
s: s,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"mime"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
api "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
"github.com/oxtoacart/bpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// need to calculate later to specify useful defaults
|
|
||||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
|
||||||
)
|
|
||||||
|
|
||||||
func requestToProto(r *http.Request) (*api.Request, error) {
|
|
||||||
if err := r.ParseForm(); err != nil {
|
|
||||||
return nil, fmt.Errorf("Error parsing form: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &api.Request{
|
|
||||||
Path: r.URL.Path,
|
|
||||||
Method: r.Method,
|
|
||||||
Header: make(map[string]*api.Pair),
|
|
||||||
Get: make(map[string]*api.Pair),
|
|
||||||
Post: make(map[string]*api.Pair),
|
|
||||||
Url: r.URL.String(),
|
|
||||||
}
|
|
||||||
|
|
||||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
||||||
if err != nil {
|
|
||||||
ct = "text/plain; charset=UTF-8" //default CT is text/plain
|
|
||||||
r.Header.Set("Content-Type", ct)
|
|
||||||
}
|
|
||||||
|
|
||||||
//set the body:
|
|
||||||
if r.Body != nil {
|
|
||||||
switch ct {
|
|
||||||
case "application/x-www-form-urlencoded":
|
|
||||||
// expect form vals in Post data
|
|
||||||
default:
|
|
||||||
buf := bufferPool.Get()
|
|
||||||
defer bufferPool.Put(buf)
|
|
||||||
if _, err = buf.ReadFrom(r.Body); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
req.Body = buf.String()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set X-Forwarded-For if it does not exist
|
|
||||||
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
|
||||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
|
||||||
ip = strings.Join(prior, ", ") + ", " + ip
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the header
|
|
||||||
req.Header["X-Forwarded-For"] = &api.Pair{
|
|
||||||
Key: "X-Forwarded-For",
|
|
||||||
Values: []string{ip},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Host is stripped from net/http Headers so let's add it
|
|
||||||
req.Header["Host"] = &api.Pair{
|
|
||||||
Key: "Host",
|
|
||||||
Values: []string{r.Host},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get data
|
|
||||||
for key, vals := range r.URL.Query() {
|
|
||||||
header, ok := req.Get[key]
|
|
||||||
if !ok {
|
|
||||||
header = &api.Pair{
|
|
||||||
Key: key,
|
|
||||||
}
|
|
||||||
req.Get[key] = header
|
|
||||||
}
|
|
||||||
header.Values = vals
|
|
||||||
}
|
|
||||||
|
|
||||||
// Post data
|
|
||||||
for key, vals := range r.PostForm {
|
|
||||||
header, ok := req.Post[key]
|
|
||||||
if !ok {
|
|
||||||
header = &api.Pair{
|
|
||||||
Key: key,
|
|
||||||
}
|
|
||||||
req.Post[key] = header
|
|
||||||
}
|
|
||||||
header.Values = vals
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, vals := range r.Header {
|
|
||||||
header, ok := req.Header[key]
|
|
||||||
if !ok {
|
|
||||||
header = &api.Pair{
|
|
||||||
Key: key,
|
|
||||||
}
|
|
||||||
req.Header[key] = header
|
|
||||||
}
|
|
||||||
header.Values = vals
|
|
||||||
}
|
|
||||||
|
|
||||||
return req, nil
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRequestToProto(t *testing.T) {
|
|
||||||
testData := []*http.Request{
|
|
||||||
{
|
|
||||||
Method: "GET",
|
|
||||||
Header: http.Header{
|
|
||||||
"Header": []string{"test"},
|
|
||||||
},
|
|
||||||
URL: &url.URL{
|
|
||||||
Scheme: "http",
|
|
||||||
Host: "localhost",
|
|
||||||
Path: "/foo/bar",
|
|
||||||
RawQuery: "param1=value1",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, d := range testData {
|
|
||||||
p, err := requestToProto(d)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if p.Path != d.URL.Path {
|
|
||||||
t.Fatalf("Expected path %s got %s", d.URL.Path, p.Path)
|
|
||||||
}
|
|
||||||
if p.Method != d.Method {
|
|
||||||
t.Fatalf("Expected method %s got %s", d.Method, p.Method)
|
|
||||||
}
|
|
||||||
for k, v := range d.Header {
|
|
||||||
if val, ok := p.Header[k]; !ok {
|
|
||||||
t.Fatalf("Expected header %s", k)
|
|
||||||
} else {
|
|
||||||
if val.Values[0] != v[0] {
|
|
||||||
t.Fatalf("Expected val %s, got %s", val.Values[0], v[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
// Package event provides a handler which publishes an event
|
|
||||||
package event
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"path"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
proto "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
|
||||||
"github.com/oxtoacart/bpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
|
||||||
)
|
|
||||||
|
|
||||||
type event struct {
|
|
||||||
opts handler.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
Handler = "event"
|
|
||||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
|
||||||
)
|
|
||||||
|
|
||||||
func eventName(parts []string) string {
|
|
||||||
return strings.Join(parts, ".")
|
|
||||||
}
|
|
||||||
|
|
||||||
func evRoute(ns, p string) (string, string) {
|
|
||||||
p = path.Clean(p)
|
|
||||||
p = strings.TrimPrefix(p, "/")
|
|
||||||
|
|
||||||
if len(p) == 0 {
|
|
||||||
return ns, "event"
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(p, "/")
|
|
||||||
|
|
||||||
// no path
|
|
||||||
if len(parts) == 0 {
|
|
||||||
// topic: namespace
|
|
||||||
// action: event
|
|
||||||
return strings.Trim(ns, "."), "event"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Treat /v[0-9]+ as versioning
|
|
||||||
// /v1/foo/bar => topic: v1.foo action: bar
|
|
||||||
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
|
|
||||||
topic := ns + "." + strings.Join(parts[:2], ".")
|
|
||||||
action := eventName(parts[1:])
|
|
||||||
return topic, action
|
|
||||||
}
|
|
||||||
|
|
||||||
// /foo => topic: ns.foo action: foo
|
|
||||||
// /foo/bar => topic: ns.foo action: bar
|
|
||||||
topic := ns + "." + strings.Join(parts[:1], ".")
|
|
||||||
action := eventName(parts[1:])
|
|
||||||
|
|
||||||
return topic, action
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
bsize := handler.DefaultMaxRecvSize
|
|
||||||
if e.opts.MaxRecvSize > 0 {
|
|
||||||
bsize = e.opts.MaxRecvSize
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
|
||||||
|
|
||||||
// request to topic:event
|
|
||||||
// create event
|
|
||||||
// publish to topic
|
|
||||||
|
|
||||||
topic, action := evRoute(e.opts.Namespace, r.URL.Path)
|
|
||||||
|
|
||||||
// create event
|
|
||||||
ev := &proto.Event{
|
|
||||||
Name: action,
|
|
||||||
// TODO: dedupe event
|
|
||||||
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.New().String()),
|
|
||||||
Header: make(map[string]*proto.Pair),
|
|
||||||
Timestamp: time.Now().Unix(),
|
|
||||||
}
|
|
||||||
|
|
||||||
// set headers
|
|
||||||
for key, vals := range r.Header {
|
|
||||||
header, ok := ev.Header[key]
|
|
||||||
if !ok {
|
|
||||||
header = &proto.Pair{
|
|
||||||
Key: key,
|
|
||||||
}
|
|
||||||
ev.Header[key] = header
|
|
||||||
}
|
|
||||||
header.Values = vals
|
|
||||||
}
|
|
||||||
|
|
||||||
// set body
|
|
||||||
if r.Method == "GET" {
|
|
||||||
bytes, _ := json.Marshal(r.URL.Query())
|
|
||||||
ev.Data = string(bytes)
|
|
||||||
} else {
|
|
||||||
// Read body
|
|
||||||
buf := bufferPool.Get()
|
|
||||||
defer bufferPool.Put(buf)
|
|
||||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
|
||||||
http.Error(w, err.Error(), 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ev.Data = buf.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// get client
|
|
||||||
c := e.opts.Client
|
|
||||||
|
|
||||||
// create publication
|
|
||||||
p := c.NewMessage(topic, ev)
|
|
||||||
|
|
||||||
// publish event
|
|
||||||
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
|
|
||||||
http.Error(w, err.Error(), 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *event) String() string {
|
|
||||||
return "event"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
|
||||||
return &event{
|
|
||||||
opts: handler.NewOptions(opts...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
// Package handler provides http handlers
|
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler represents a HTTP handler that manages a request
|
|
||||||
type Handler interface {
|
|
||||||
// standard http handler
|
|
||||||
http.Handler
|
|
||||||
// name of handler
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
// Package http is a http reverse proxy handler
|
|
||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httputil"
|
|
||||||
"net/url"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Handler = "http"
|
|
||||||
)
|
|
||||||
|
|
||||||
type httpHandler struct {
|
|
||||||
options handler.Options
|
|
||||||
|
|
||||||
// set with different initializer
|
|
||||||
s *api.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
service, err := h.getService(r)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(service) == 0 {
|
|
||||||
w.WriteHeader(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rp, err := url.Parse(service)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getService returns the service for this request from the selector
|
|
||||||
func (h *httpHandler) getService(r *http.Request) (string, error) {
|
|
||||||
var service *api.Service
|
|
||||||
|
|
||||||
if h.s != nil {
|
|
||||||
// we were given the service
|
|
||||||
service = h.s
|
|
||||||
} else if h.options.Router != nil {
|
|
||||||
// try get service from router
|
|
||||||
s, err := h.options.Router.Route(r)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
service = s
|
|
||||||
} else {
|
|
||||||
// we have no way of routing the request
|
|
||||||
return "", errors.New("no route found")
|
|
||||||
}
|
|
||||||
|
|
||||||
// get the nodes for this service
|
|
||||||
var nodes []*registry.Node
|
|
||||||
for _, srv := range service.Services {
|
|
||||||
nodes = append(nodes, srv.Nodes...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// select a random node
|
|
||||||
if len(nodes) == 0 {
|
|
||||||
return "", errors.New("no route found")
|
|
||||||
}
|
|
||||||
node := nodes[rand.Int()%len(nodes)]
|
|
||||||
|
|
||||||
return fmt.Sprintf("http://%s", node.Address), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpHandler) String() string {
|
|
||||||
return "http"
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHandler returns a http proxy handler
|
|
||||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
|
|
||||||
return &httpHandler{
|
|
||||||
options: options,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithService creates a handler with a service
|
|
||||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
|
|
||||||
return &httpHandler{
|
|
||||||
options: options,
|
|
||||||
s: s,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
regRouter "github.com/micro/go-micro/v3/api/router/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/memory"
|
|
||||||
)
|
|
||||||
|
|
||||||
func testHttp(t *testing.T, path, service, ns string) {
|
|
||||||
r := memory.NewRegistry()
|
|
||||||
|
|
||||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer l.Close()
|
|
||||||
|
|
||||||
s := ®istry.Service{
|
|
||||||
Name: service,
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: service + "-1",
|
|
||||||
Address: l.Addr().String(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Register(s)
|
|
||||||
defer r.Deregister(s)
|
|
||||||
|
|
||||||
// setup the test handler
|
|
||||||
m := http.NewServeMux()
|
|
||||||
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte(`you got served`))
|
|
||||||
})
|
|
||||||
|
|
||||||
// start http test serve
|
|
||||||
go http.Serve(l, m)
|
|
||||||
|
|
||||||
// create new request and writer
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
req, err := http.NewRequest("POST", path, nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// initialise the handler
|
|
||||||
rt := regRouter.NewRouter(
|
|
||||||
router.WithHandler("http"),
|
|
||||||
router.WithRegistry(r),
|
|
||||||
router.WithResolver(vpath.NewResolver(
|
|
||||||
resolver.WithServicePrefix(ns),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
|
|
||||||
p := NewHandler(handler.WithRouter(rt))
|
|
||||||
|
|
||||||
// execute the handler
|
|
||||||
p.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != 200 {
|
|
||||||
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
if w.Body.String() != "you got served" {
|
|
||||||
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHttpHandler(t *testing.T) {
|
|
||||||
testData := []struct {
|
|
||||||
path string
|
|
||||||
service string
|
|
||||||
namespace string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
"/test/foo",
|
|
||||||
"go.micro.api.test",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/test/foo/baz",
|
|
||||||
"go.micro.api.test",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/v1/foo",
|
|
||||||
"go.micro.api.v1.foo",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/v1/foo/bar",
|
|
||||||
"go.micro.api.v1.foo",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/v2/baz",
|
|
||||||
"go.micro.api.v2.baz",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/v2/baz/bar",
|
|
||||||
"go.micro.api.v2.baz",
|
|
||||||
"go.micro.api",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"/v2/baz/bar",
|
|
||||||
"v2.baz",
|
|
||||||
"",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, d := range testData {
|
|
||||||
t.Run(d.service, func(t *testing.T) {
|
|
||||||
testHttp(t, d.path, d.service, d.namespace)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
"github.com/micro/go-micro/v3/client/grpc"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb
|
|
||||||
)
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
MaxRecvSize int64
|
|
||||||
Namespace string
|
|
||||||
Router router.Router
|
|
||||||
Client client.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
// NewOptions fills in the blanks
|
|
||||||
func NewOptions(opts ...Option) Options {
|
|
||||||
var options Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Client == nil {
|
|
||||||
WithClient(grpc.NewClient())(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set namespace if blank
|
|
||||||
if len(options.Namespace) == 0 {
|
|
||||||
WithNamespace("go.micro.api")(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.MaxRecvSize == 0 {
|
|
||||||
options.MaxRecvSize = DefaultMaxRecvSize
|
|
||||||
}
|
|
||||||
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithNamespace specifies the namespace for the handler
|
|
||||||
func WithNamespace(s string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Namespace = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithRouter specifies a router to be used by the handler
|
|
||||||
func WithRouter(r router.Router) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Router = r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithClient(c client.Client) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Client = c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithMaxRecvSize specifies max body size
|
|
||||||
func WithMaxRecvSize(size int64) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.MaxRecvSize = size
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,493 +0,0 @@
|
|||||||
// Package rpc is a go-micro rpc handler.
|
|
||||||
package rpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
jsonpatch "github.com/evanphx/json-patch/v5"
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/api/internal/proto"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
"github.com/micro/go-micro/v3/codec"
|
|
||||||
"github.com/micro/go-micro/v3/codec/jsonrpc"
|
|
||||||
"github.com/micro/go-micro/v3/codec/protorpc"
|
|
||||||
"github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/util/ctx"
|
|
||||||
"github.com/micro/go-micro/v3/util/qson"
|
|
||||||
"github.com/micro/go-micro/v3/util/router"
|
|
||||||
"github.com/oxtoacart/bpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Handler = "rpc"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// supported json codecs
|
|
||||||
jsonCodecs = []string{
|
|
||||||
"application/grpc+json",
|
|
||||||
"application/json",
|
|
||||||
"application/json-rpc",
|
|
||||||
}
|
|
||||||
|
|
||||||
// support proto codecs
|
|
||||||
protoCodecs = []string{
|
|
||||||
"application/grpc",
|
|
||||||
"application/grpc+proto",
|
|
||||||
"application/proto",
|
|
||||||
"application/protobuf",
|
|
||||||
"application/proto-rpc",
|
|
||||||
"application/octet-stream",
|
|
||||||
}
|
|
||||||
|
|
||||||
bufferPool = bpool.NewSizedBufferPool(1024, 8)
|
|
||||||
)
|
|
||||||
|
|
||||||
type rpcHandler struct {
|
|
||||||
opts handler.Options
|
|
||||||
s *api.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
type buffer struct {
|
|
||||||
io.ReadCloser
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *buffer) Write(_ []byte) (int, error) {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
bsize := handler.DefaultMaxRecvSize
|
|
||||||
if h.opts.MaxRecvSize > 0 {
|
|
||||||
bsize = h.opts.MaxRecvSize
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, bsize)
|
|
||||||
|
|
||||||
defer r.Body.Close()
|
|
||||||
var service *api.Service
|
|
||||||
|
|
||||||
if h.s != nil {
|
|
||||||
// we were given the service
|
|
||||||
service = h.s
|
|
||||||
} else if h.opts.Router != nil {
|
|
||||||
// try get service from router
|
|
||||||
s, err := h.opts.Router.Route(r)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, r, errors.InternalServerError("go.micro.api", err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
service = s
|
|
||||||
} else {
|
|
||||||
// we have no way of routing the request
|
|
||||||
writeError(w, r, errors.InternalServerError("go.micro.api", "no route found"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := r.Header.Get("Content-Type")
|
|
||||||
|
|
||||||
// Strip charset from Content-Type (like `application/json; charset=UTF-8`)
|
|
||||||
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
|
|
||||||
ct = ct[:idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
// micro client
|
|
||||||
c := h.opts.Client
|
|
||||||
|
|
||||||
// create context
|
|
||||||
cx := ctx.FromRequest(r)
|
|
||||||
|
|
||||||
// set merged context to request
|
|
||||||
*r = *r.Clone(cx)
|
|
||||||
// if stream we currently only support json
|
|
||||||
if isStream(r, service) {
|
|
||||||
serveWebsocket(cx, w, r, service, c)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// create custom router
|
|
||||||
callOpt := client.WithRouter(router.New(service.Services))
|
|
||||||
|
|
||||||
// walk the standard call path
|
|
||||||
// get payload
|
|
||||||
br, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var rsp []byte
|
|
||||||
|
|
||||||
switch {
|
|
||||||
// proto codecs
|
|
||||||
case hasCodec(ct, protoCodecs):
|
|
||||||
request := &proto.Message{}
|
|
||||||
// if the extracted payload isn't empty lets use it
|
|
||||||
if len(br) > 0 {
|
|
||||||
request = proto.NewMessage(br)
|
|
||||||
}
|
|
||||||
|
|
||||||
// create request/response
|
|
||||||
response := &proto.Message{}
|
|
||||||
|
|
||||||
req := c.NewRequest(
|
|
||||||
service.Name,
|
|
||||||
service.Endpoint.Name,
|
|
||||||
request,
|
|
||||||
client.WithContentType(ct),
|
|
||||||
)
|
|
||||||
|
|
||||||
// make the call
|
|
||||||
if err := c.Call(cx, req, response, callOpt); err != nil {
|
|
||||||
writeError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshall response
|
|
||||||
rsp, err = response.Marshal()
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
// if json codec is not present set to json
|
|
||||||
if !hasCodec(ct, jsonCodecs) {
|
|
||||||
ct = "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
// default to trying json
|
|
||||||
var request json.RawMessage
|
|
||||||
// if the extracted payload isn't empty lets use it
|
|
||||||
if len(br) > 0 {
|
|
||||||
request = json.RawMessage(br)
|
|
||||||
}
|
|
||||||
|
|
||||||
// create request/response
|
|
||||||
var response json.RawMessage
|
|
||||||
|
|
||||||
req := c.NewRequest(
|
|
||||||
service.Name,
|
|
||||||
service.Endpoint.Name,
|
|
||||||
&request,
|
|
||||||
client.WithContentType(ct),
|
|
||||||
)
|
|
||||||
// make the call
|
|
||||||
if err := c.Call(cx, req, &response, callOpt); err != nil {
|
|
||||||
writeError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshall response
|
|
||||||
rsp, err = response.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// write the response
|
|
||||||
writeResponse(w, r, rsp)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rh *rpcHandler) String() string {
|
|
||||||
return "rpc"
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasCodec(ct string, codecs []string) bool {
|
|
||||||
for _, codec := range codecs {
|
|
||||||
if ct == codec {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// requestPayload takes a *http.Request.
|
|
||||||
// If the request is a GET the query string parameters are extracted and marshaled to JSON and the raw bytes are returned.
|
|
||||||
// If the request method is a POST the request body is read and returned
|
|
||||||
func requestPayload(r *http.Request) ([]byte, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
// we have to decode json-rpc and proto-rpc because we suck
|
|
||||||
// well actually because there's no proxy codec right now
|
|
||||||
|
|
||||||
ct := r.Header.Get("Content-Type")
|
|
||||||
switch {
|
|
||||||
case strings.Contains(ct, "application/json-rpc"):
|
|
||||||
msg := codec.Message{
|
|
||||||
Type: codec.Request,
|
|
||||||
Header: make(map[string]string),
|
|
||||||
}
|
|
||||||
c := jsonrpc.NewCodec(&buffer{r.Body})
|
|
||||||
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var raw json.RawMessage
|
|
||||||
if err = c.ReadBody(&raw); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return ([]byte)(raw), nil
|
|
||||||
case strings.Contains(ct, "application/proto-rpc"), strings.Contains(ct, "application/octet-stream"):
|
|
||||||
msg := codec.Message{
|
|
||||||
Type: codec.Request,
|
|
||||||
Header: make(map[string]string),
|
|
||||||
}
|
|
||||||
c := protorpc.NewCodec(&buffer{r.Body})
|
|
||||||
if err = c.ReadHeader(&msg, codec.Request); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var raw proto.Message
|
|
||||||
if err = c.ReadBody(&raw); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return raw.Marshal()
|
|
||||||
case strings.Contains(ct, "application/www-x-form-urlencoded"):
|
|
||||||
r.ParseForm()
|
|
||||||
|
|
||||||
// generate a new set of values from the form
|
|
||||||
vals := make(map[string]string)
|
|
||||||
for k, v := range r.Form {
|
|
||||||
vals[k] = strings.Join(v, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshal
|
|
||||||
return json.Marshal(vals)
|
|
||||||
// TODO: application/grpc
|
|
||||||
}
|
|
||||||
|
|
||||||
// otherwise as per usual
|
|
||||||
ctx := r.Context()
|
|
||||||
// dont user metadata.FromContext as it mangles names
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(map[string]string)
|
|
||||||
}
|
|
||||||
|
|
||||||
// allocate maximum
|
|
||||||
matches := make(map[string]interface{}, len(md))
|
|
||||||
bodydst := ""
|
|
||||||
|
|
||||||
// get fields from url path
|
|
||||||
for k, v := range md {
|
|
||||||
k = strings.ToLower(k)
|
|
||||||
// filter own keys
|
|
||||||
if strings.HasPrefix(k, "x-api-field-") {
|
|
||||||
matches[strings.TrimPrefix(k, "x-api-field-")] = v
|
|
||||||
delete(md, k)
|
|
||||||
} else if k == "x-api-body" {
|
|
||||||
bodydst = v
|
|
||||||
delete(md, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// map of all fields
|
|
||||||
req := make(map[string]interface{}, len(md))
|
|
||||||
|
|
||||||
// get fields from url values
|
|
||||||
if len(r.URL.RawQuery) > 0 {
|
|
||||||
umd := make(map[string]interface{})
|
|
||||||
err = qson.Unmarshal(&umd, r.URL.RawQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for k, v := range umd {
|
|
||||||
matches[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// restore context without fields
|
|
||||||
*r = *r.Clone(metadata.NewContext(ctx, md))
|
|
||||||
|
|
||||||
for k, v := range matches {
|
|
||||||
ps := strings.Split(k, ".")
|
|
||||||
if len(ps) == 1 {
|
|
||||||
req[k] = v
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
em := make(map[string]interface{})
|
|
||||||
em[ps[len(ps)-1]] = v
|
|
||||||
for i := len(ps) - 2; i > 0; i-- {
|
|
||||||
nm := make(map[string]interface{})
|
|
||||||
nm[ps[i]] = em
|
|
||||||
em = nm
|
|
||||||
}
|
|
||||||
if vm, ok := req[ps[0]]; ok {
|
|
||||||
// nested map
|
|
||||||
nm := vm.(map[string]interface{})
|
|
||||||
for vk, vv := range em {
|
|
||||||
nm[vk] = vv
|
|
||||||
}
|
|
||||||
req[ps[0]] = nm
|
|
||||||
} else {
|
|
||||||
req[ps[0]] = em
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pathbuf := []byte("{}")
|
|
||||||
if len(req) > 0 {
|
|
||||||
pathbuf, err = json.Marshal(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
urlbuf := []byte("{}")
|
|
||||||
out, err := jsonpatch.MergeMergePatches(urlbuf, pathbuf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch r.Method {
|
|
||||||
case "GET":
|
|
||||||
// empty response
|
|
||||||
if strings.Contains(ct, "application/json") && string(out) == "{}" {
|
|
||||||
return out, nil
|
|
||||||
} else if string(out) == "{}" && !strings.Contains(ct, "application/json") {
|
|
||||||
return []byte{}, nil
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
case "PATCH", "POST", "PUT", "DELETE":
|
|
||||||
bodybuf := []byte("{}")
|
|
||||||
buf := bufferPool.Get()
|
|
||||||
defer bufferPool.Put(buf)
|
|
||||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if b := buf.Bytes(); len(b) > 0 {
|
|
||||||
bodybuf = b
|
|
||||||
}
|
|
||||||
if bodydst == "" || bodydst == "*" {
|
|
||||||
if out, err = jsonpatch.MergeMergePatches(out, bodybuf); err == nil {
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var jsonbody map[string]interface{}
|
|
||||||
if json.Valid(bodybuf) {
|
|
||||||
if err = json.Unmarshal(bodybuf, &jsonbody); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dstmap := make(map[string]interface{})
|
|
||||||
ps := strings.Split(bodydst, ".")
|
|
||||||
if len(ps) == 1 {
|
|
||||||
if jsonbody != nil {
|
|
||||||
dstmap[ps[0]] = jsonbody
|
|
||||||
} else {
|
|
||||||
// old unexpected behaviour
|
|
||||||
dstmap[ps[0]] = bodybuf
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
em := make(map[string]interface{})
|
|
||||||
if jsonbody != nil {
|
|
||||||
em[ps[len(ps)-1]] = jsonbody
|
|
||||||
} else {
|
|
||||||
// old unexpected behaviour
|
|
||||||
em[ps[len(ps)-1]] = bodybuf
|
|
||||||
}
|
|
||||||
for i := len(ps) - 2; i > 0; i-- {
|
|
||||||
nm := make(map[string]interface{})
|
|
||||||
nm[ps[i]] = em
|
|
||||||
em = nm
|
|
||||||
}
|
|
||||||
dstmap[ps[0]] = em
|
|
||||||
}
|
|
||||||
|
|
||||||
bodyout, err := json.Marshal(dstmap)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if out, err = jsonpatch.MergeMergePatches(out, bodyout); err == nil {
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//fallback to previous unknown behaviour
|
|
||||||
return bodybuf, nil
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return []byte{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeError(w http.ResponseWriter, r *http.Request, err error) {
|
|
||||||
ce := errors.Parse(err.Error())
|
|
||||||
|
|
||||||
switch ce.Code {
|
|
||||||
case 0:
|
|
||||||
// assuming it's totally screwed
|
|
||||||
ce.Code = 500
|
|
||||||
ce.Id = "go.micro.api"
|
|
||||||
ce.Status = http.StatusText(500)
|
|
||||||
ce.Detail = "error during request: " + ce.Detail
|
|
||||||
w.WriteHeader(500)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(int(ce.Code))
|
|
||||||
}
|
|
||||||
|
|
||||||
// response content type
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
// Set trailers
|
|
||||||
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
|
|
||||||
w.Header().Set("Trailer", "grpc-status")
|
|
||||||
w.Header().Set("Trailer", "grpc-message")
|
|
||||||
w.Header().Set("grpc-status", "13")
|
|
||||||
w.Header().Set("grpc-message", ce.Detail)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, werr := w.Write([]byte(ce.Error()))
|
|
||||||
if werr != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(werr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeResponse(w http.ResponseWriter, r *http.Request, rsp []byte) {
|
|
||||||
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
|
|
||||||
w.Header().Set("Content-Length", strconv.Itoa(len(rsp)))
|
|
||||||
|
|
||||||
// Set trailers
|
|
||||||
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
|
|
||||||
w.Header().Set("Trailer", "grpc-status")
|
|
||||||
w.Header().Set("Trailer", "grpc-message")
|
|
||||||
w.Header().Set("grpc-status", "0")
|
|
||||||
w.Header().Set("grpc-message", "")
|
|
||||||
}
|
|
||||||
|
|
||||||
// write 204 status if rsp is nil
|
|
||||||
if len(rsp) == 0 {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
}
|
|
||||||
|
|
||||||
// write response
|
|
||||||
_, err := w.Write(rsp)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
return &rpcHandler{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
return &rpcHandler{
|
|
||||||
opts: options,
|
|
||||||
s: s,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package rpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/golang/protobuf/proto"
|
|
||||||
go_api "github.com/micro/go-micro/v3/api/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRequestPayloadFromRequest(t *testing.T) {
|
|
||||||
|
|
||||||
// our test event so that we can validate serialising / deserializing of true protos works
|
|
||||||
protoEvent := go_api.Event{
|
|
||||||
Name: "Test",
|
|
||||||
}
|
|
||||||
|
|
||||||
protoBytes, err := proto.Marshal(&protoEvent)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("Failed to marshal proto", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonBytes, err := json.Marshal(protoEvent)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("Failed to marshal proto to JSON ", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonUrlBytes := []byte(`{"key1":"val1","key2":"val2","name":"Test"}`)
|
|
||||||
|
|
||||||
t.Run("extracting a json from a POST request with url params", func(t *testing.T) {
|
|
||||||
r, err := http.NewRequest("POST", "http://localhost/my/path?key1=val1&key2=val2", bytes.NewReader(jsonBytes))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
extByte, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
|
||||||
}
|
|
||||||
if string(extByte) != string(jsonUrlBytes) {
|
|
||||||
t.Fatalf("Expected %v and %v to match", string(extByte), jsonUrlBytes)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("extracting a proto from a POST request", func(t *testing.T) {
|
|
||||||
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(protoBytes))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
extByte, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
|
||||||
}
|
|
||||||
if string(extByte) != string(protoBytes) {
|
|
||||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(protoBytes))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("extracting JSON from a POST request", func(t *testing.T) {
|
|
||||||
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(jsonBytes))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
extByte, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
|
||||||
}
|
|
||||||
if string(extByte) != string(jsonBytes) {
|
|
||||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("extracting params from a GET request", func(t *testing.T) {
|
|
||||||
|
|
||||||
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
q := r.URL.Query()
|
|
||||||
q.Add("name", "Test")
|
|
||||||
r.URL.RawQuery = q.Encode()
|
|
||||||
|
|
||||||
extByte, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
|
||||||
}
|
|
||||||
if string(extByte) != string(jsonBytes) {
|
|
||||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("GET request with no params", func(t *testing.T) {
|
|
||||||
|
|
||||||
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
extByte, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
|
||||||
}
|
|
||||||
if string(extByte) != "" {
|
|
||||||
t.Fatalf("Expected %v and %v to match", string(extByte), "")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,261 +0,0 @@
|
|||||||
package rpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gobwas/httphead"
|
|
||||||
"github.com/gobwas/ws"
|
|
||||||
"github.com/gobwas/ws/wsutil"
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
raw "github.com/micro/go-micro/v3/codec/bytes"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/util/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
// serveWebsocket will stream rpc back over websockets assuming json
|
|
||||||
func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request, service *api.Service, c client.Client) {
|
|
||||||
var op ws.OpCode
|
|
||||||
|
|
||||||
ct := r.Header.Get("Content-Type")
|
|
||||||
// Strip charset from Content-Type (like `application/json; charset=UTF-8`)
|
|
||||||
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
|
|
||||||
ct = ct[:idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
// check proto from request
|
|
||||||
switch ct {
|
|
||||||
case "application/json":
|
|
||||||
op = ws.OpText
|
|
||||||
default:
|
|
||||||
op = ws.OpBinary
|
|
||||||
}
|
|
||||||
|
|
||||||
hdr := make(http.Header)
|
|
||||||
if proto, ok := r.Header["Sec-WebSocket-Protocol"]; ok {
|
|
||||||
for _, p := range proto {
|
|
||||||
switch p {
|
|
||||||
case "binary":
|
|
||||||
hdr["Sec-WebSocket-Protocol"] = []string{"binary"}
|
|
||||||
op = ws.OpBinary
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
payload, err := requestPayload(r)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
upgrader := ws.HTTPUpgrader{Timeout: 5 * time.Second,
|
|
||||||
Protocol: func(proto string) bool {
|
|
||||||
if strings.Contains(proto, "binary") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
// fallback to support all protocols now
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
Extension: func(httphead.Option) bool {
|
|
||||||
// disable extensions for compatibility
|
|
||||||
return false
|
|
||||||
},
|
|
||||||
Header: hdr,
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, rw, _, err := upgrader.Upgrade(r, w)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if err := conn.Close(); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var request interface{}
|
|
||||||
if !bytes.Equal(payload, []byte(`{}`)) {
|
|
||||||
switch ct {
|
|
||||||
case "application/json", "":
|
|
||||||
m := json.RawMessage(payload)
|
|
||||||
request = &m
|
|
||||||
default:
|
|
||||||
request = &raw.Frame{Data: payload}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// we always need to set content type for message
|
|
||||||
if ct == "" {
|
|
||||||
ct = "application/json"
|
|
||||||
}
|
|
||||||
req := c.NewRequest(
|
|
||||||
service.Name,
|
|
||||||
service.Endpoint.Name,
|
|
||||||
request,
|
|
||||||
client.WithContentType(ct),
|
|
||||||
client.StreamingRequest(),
|
|
||||||
)
|
|
||||||
|
|
||||||
// create custom router
|
|
||||||
callOpt := client.WithRouter(router.New(service.Services))
|
|
||||||
|
|
||||||
// create a new stream
|
|
||||||
stream, err := c.Stream(ctx, req, callOpt)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if request != nil {
|
|
||||||
if err = stream.Send(request); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
go writeLoop(rw, stream)
|
|
||||||
|
|
||||||
rsp := stream.Response()
|
|
||||||
|
|
||||||
// receive from stream and send to client
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-stream.Context().Done():
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
// read backend response body
|
|
||||||
buf, err := rsp.Read()
|
|
||||||
if err != nil {
|
|
||||||
// wants to avoid import grpc/status.Status
|
|
||||||
if strings.Contains(err.Error(), "context canceled") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// write the response
|
|
||||||
if err := wsutil.WriteServerMessage(rw, op, buf); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err = rw.Flush(); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeLoop
|
|
||||||
func writeLoop(rw io.ReadWriter, stream client.Stream) {
|
|
||||||
// close stream when done
|
|
||||||
defer stream.Close()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-stream.Context().Done():
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
buf, op, err := wsutil.ReadClientData(rw)
|
|
||||||
if err != nil {
|
|
||||||
if wserr, ok := err.(wsutil.ClosedError); ok {
|
|
||||||
switch wserr.Code {
|
|
||||||
case ws.StatusGoingAway:
|
|
||||||
// this happens when user leave the page
|
|
||||||
return
|
|
||||||
case ws.StatusNormalClosure, ws.StatusNoStatusRcvd:
|
|
||||||
// this happens when user close ws connection, or we don't get any status
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch op {
|
|
||||||
default:
|
|
||||||
// not relevant
|
|
||||||
continue
|
|
||||||
case ws.OpText, ws.OpBinary:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// send to backend
|
|
||||||
// default to trying json
|
|
||||||
// if the extracted payload isn't empty lets use it
|
|
||||||
request := &raw.Frame{Data: buf}
|
|
||||||
if err := stream.Send(request); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isStream(r *http.Request, srv *api.Service) bool {
|
|
||||||
// check if it's a web socket
|
|
||||||
if !isWebSocket(r) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
// check if the endpoint supports streaming
|
|
||||||
for _, service := range srv.Services {
|
|
||||||
for _, ep := range service.Endpoints {
|
|
||||||
// skip if it doesn't match the name
|
|
||||||
if ep.Name != srv.Endpoint.Name {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// matched if the name
|
|
||||||
if v := ep.Metadata["stream"]; v == "true" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func isWebSocket(r *http.Request) bool {
|
|
||||||
contains := func(key, val string) bool {
|
|
||||||
vv := strings.Split(r.Header.Get(key), ",")
|
|
||||||
for _, v := range vv {
|
|
||||||
if val == strings.ToLower(strings.TrimSpace(v)) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
// Package web contains the web handler including websocket support
|
|
||||||
package web
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"math/rand"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httputil"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Handler = "web"
|
|
||||||
)
|
|
||||||
|
|
||||||
type webHandler struct {
|
|
||||||
opts handler.Options
|
|
||||||
s *api.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
service, err := wh.getService(r)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(service) == 0 {
|
|
||||||
w.WriteHeader(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rp, err := url.Parse(service)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if isWebSocket(r) {
|
|
||||||
wh.serveWebSocket(rp.Host, w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getService returns the service for this request from the selector
|
|
||||||
func (wh *webHandler) getService(r *http.Request) (string, error) {
|
|
||||||
var service *api.Service
|
|
||||||
|
|
||||||
if wh.s != nil {
|
|
||||||
// we were given the service
|
|
||||||
service = wh.s
|
|
||||||
} else if wh.opts.Router != nil {
|
|
||||||
// try get service from router
|
|
||||||
s, err := wh.opts.Router.Route(r)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
service = s
|
|
||||||
} else {
|
|
||||||
// we have no way of routing the request
|
|
||||||
return "", errors.New("no route found")
|
|
||||||
}
|
|
||||||
|
|
||||||
// get the nodes
|
|
||||||
var nodes []*registry.Node
|
|
||||||
for _, srv := range service.Services {
|
|
||||||
nodes = append(nodes, srv.Nodes...)
|
|
||||||
}
|
|
||||||
if len(nodes) == 0 {
|
|
||||||
return "", errors.New("no route found")
|
|
||||||
}
|
|
||||||
|
|
||||||
// select a random node
|
|
||||||
node := nodes[rand.Int()%len(nodes)]
|
|
||||||
|
|
||||||
return fmt.Sprintf("http://%s", node.Address), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// serveWebSocket used to serve a web socket proxied connection
|
|
||||||
func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) {
|
|
||||||
req := new(http.Request)
|
|
||||||
*req = *r
|
|
||||||
|
|
||||||
if len(host) == 0 {
|
|
||||||
http.Error(w, "invalid host", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// set x-forward-for
|
|
||||||
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
|
||||||
if ips, ok := req.Header["X-Forwarded-For"]; ok {
|
|
||||||
clientIP = strings.Join(ips, ", ") + ", " + clientIP
|
|
||||||
}
|
|
||||||
req.Header.Set("X-Forwarded-For", clientIP)
|
|
||||||
}
|
|
||||||
|
|
||||||
// connect to the backend host
|
|
||||||
conn, err := net.Dial("tcp", host)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// hijack the connection
|
|
||||||
hj, ok := w.(http.Hijacker)
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, "failed to connect", 500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
nc, _, err := hj.Hijack()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer nc.Close()
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
if err = req.Write(conn); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
errCh := make(chan error, 2)
|
|
||||||
|
|
||||||
cp := func(dst io.Writer, src io.Reader) {
|
|
||||||
_, err := io.Copy(dst, src)
|
|
||||||
errCh <- err
|
|
||||||
}
|
|
||||||
|
|
||||||
go cp(conn, nc)
|
|
||||||
go cp(nc, conn)
|
|
||||||
|
|
||||||
<-errCh
|
|
||||||
}
|
|
||||||
|
|
||||||
func isWebSocket(r *http.Request) bool {
|
|
||||||
contains := func(key, val string) bool {
|
|
||||||
vv := strings.Split(r.Header.Get(key), ",")
|
|
||||||
for _, v := range vv {
|
|
||||||
if val == strings.ToLower(strings.TrimSpace(v)) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wh *webHandler) String() string {
|
|
||||||
return "web"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
|
||||||
return &webHandler{
|
|
||||||
opts: handler.NewOptions(opts...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
|
||||||
options := handler.NewOptions(opts...)
|
|
||||||
|
|
||||||
return &webHandler{
|
|
||||||
opts: options,
|
|
||||||
s: s,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package proto
|
|
||||||
|
|
||||||
type Message struct {
|
|
||||||
data []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Message) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (m *Message) Reset() {
|
|
||||||
*m = Message{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Message) String() string {
|
|
||||||
return string(m.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Message) Marshal() ([]byte, error) {
|
|
||||||
return m.data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Message) Unmarshal(data []byte) error {
|
|
||||||
m.data = data
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMessage(data []byte) *Message {
|
|
||||||
return &Message{data}
|
|
||||||
}
|
|
||||||
@@ -1,335 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// source: api/proto/api.proto
|
|
||||||
|
|
||||||
package go_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
type Pair struct {
|
|
||||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
|
||||||
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Pair) Reset() { *m = Pair{} }
|
|
||||||
func (m *Pair) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Pair) ProtoMessage() {}
|
|
||||||
func (*Pair) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_2df576b66d12087a, []int{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Pair) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Pair.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Pair.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Pair.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Pair.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Pair) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Pair.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Pair proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Pair) GetKey() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Key
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Pair) GetValues() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Values
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP request as RPC
|
|
||||||
// Forward by the api handler
|
|
||||||
type Request struct {
|
|
||||||
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
|
||||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
|
||||||
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"`
|
|
||||||
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) Reset() { *m = Request{} }
|
|
||||||
func (m *Request) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Request) ProtoMessage() {}
|
|
||||||
func (*Request) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_2df576b66d12087a, []int{1}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Request.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Request.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Request.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Request.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Request) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Request.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Request proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Request) GetMethod() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Method
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetPath() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Path
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetHeader() map[string]*Pair {
|
|
||||||
if m != nil {
|
|
||||||
return m.Header
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetGet() map[string]*Pair {
|
|
||||||
if m != nil {
|
|
||||||
return m.Get
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetPost() map[string]*Pair {
|
|
||||||
if m != nil {
|
|
||||||
return m.Post
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetBody() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Body
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Request) GetUrl() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Url
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP response as RPC
|
|
||||||
// Expected response for the api handler
|
|
||||||
type Response struct {
|
|
||||||
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
|
||||||
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Response) Reset() { *m = Response{} }
|
|
||||||
func (m *Response) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Response) ProtoMessage() {}
|
|
||||||
func (*Response) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_2df576b66d12087a, []int{2}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Response) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Response.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Response.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Response.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Response) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Response.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Response proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Response) GetStatusCode() int32 {
|
|
||||||
if m != nil {
|
|
||||||
return m.StatusCode
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Response) GetHeader() map[string]*Pair {
|
|
||||||
if m != nil {
|
|
||||||
return m.Header
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Response) GetBody() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Body
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP event as RPC
|
|
||||||
// Forwarded by the event handler
|
|
||||||
type Event struct {
|
|
||||||
// e.g login
|
|
||||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
|
||||||
// uuid
|
|
||||||
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
|
|
||||||
// unix timestamp of event
|
|
||||||
Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
|
||||||
// event headers
|
|
||||||
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
|
||||||
// the event data
|
|
||||||
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) Reset() { *m = Event{} }
|
|
||||||
func (m *Event) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Event) ProtoMessage() {}
|
|
||||||
func (*Event) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_2df576b66d12087a, []int{3}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Event.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Event.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Event.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Event) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Event.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Event proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Event) GetName() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Name
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) GetId() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Id
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) GetTimestamp() int64 {
|
|
||||||
if m != nil {
|
|
||||||
return m.Timestamp
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) GetHeader() map[string]*Pair {
|
|
||||||
if m != nil {
|
|
||||||
return m.Header
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Event) GetData() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Data
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
proto.RegisterType((*Pair)(nil), "go.api.Pair")
|
|
||||||
proto.RegisterType((*Request)(nil), "go.api.Request")
|
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.GetEntry")
|
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.HeaderEntry")
|
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.PostEntry")
|
|
||||||
proto.RegisterType((*Response)(nil), "go.api.Response")
|
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Response.HeaderEntry")
|
|
||||||
proto.RegisterType((*Event)(nil), "go.api.Event")
|
|
||||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Event.HeaderEntry")
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() { proto.RegisterFile("api/proto/api.proto", fileDescriptor_2df576b66d12087a) }
|
|
||||||
|
|
||||||
var fileDescriptor_2df576b66d12087a = []byte{
|
|
||||||
// 393 bytes of a gzipped FileDescriptorProto
|
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0xcd, 0xce, 0xd3, 0x30,
|
|
||||||
0x10, 0x54, 0xe2, 0x24, 0x6d, 0xb6, 0x08, 0x21, 0x23, 0x21, 0x53, 0x2a, 0x54, 0xe5, 0x54, 0x21,
|
|
||||||
0x91, 0x42, 0xcb, 0x01, 0x71, 0x85, 0xaa, 0x1c, 0x2b, 0xbf, 0x81, 0xab, 0x58, 0x6d, 0x44, 0x13,
|
|
||||||
0x9b, 0xd8, 0xa9, 0xd4, 0x87, 0xe3, 0xc0, 0x63, 0xf0, 0x36, 0xc8, 0x1b, 0xf7, 0xe7, 0xab, 0xfa,
|
|
||||||
0x5d, 0xbe, 0xaf, 0xb7, 0x89, 0x3d, 0x3b, 0x3b, 0x3b, 0xeb, 0xc0, 0x6b, 0xa1, 0xcb, 0xa9, 0x6e,
|
|
||||||
0x94, 0x55, 0x53, 0xa1, 0xcb, 0x1c, 0x11, 0x4d, 0x36, 0x2a, 0x17, 0xba, 0xcc, 0x3e, 0x41, 0xb4,
|
|
||||||
0x12, 0x65, 0x43, 0x5f, 0x01, 0xf9, 0x25, 0x0f, 0x2c, 0x18, 0x07, 0x93, 0x94, 0x3b, 0x48, 0xdf,
|
|
||||||
0x40, 0xb2, 0x17, 0xbb, 0x56, 0x1a, 0x16, 0x8e, 0xc9, 0x24, 0xe5, 0xfe, 0x2b, 0xfb, 0x4b, 0xa0,
|
|
||||||
0xc7, 0xe5, 0xef, 0x56, 0x1a, 0xeb, 0x38, 0x95, 0xb4, 0x5b, 0x55, 0xf8, 0x42, 0xff, 0x45, 0x29,
|
|
||||||
0x44, 0x5a, 0xd8, 0x2d, 0x0b, 0xf1, 0x14, 0x31, 0x9d, 0x43, 0xb2, 0x95, 0xa2, 0x90, 0x0d, 0x23,
|
|
||||||
0x63, 0x32, 0x19, 0xcc, 0xde, 0xe5, 0x9d, 0x85, 0xdc, 0x8b, 0xe5, 0x3f, 0xf1, 0x76, 0x51, 0xdb,
|
|
||||||
0xe6, 0xc0, 0x3d, 0x95, 0x7e, 0x00, 0xb2, 0x91, 0x96, 0x45, 0x58, 0xc1, 0xae, 0x2b, 0x96, 0xd2,
|
|
||||||
0x76, 0x74, 0x47, 0xa2, 0x1f, 0x21, 0xd2, 0xca, 0x58, 0x16, 0x23, 0xf9, 0xed, 0x35, 0x79, 0xa5,
|
|
||||||
0x8c, 0x67, 0x23, 0xcd, 0x79, 0x5c, 0xab, 0xe2, 0xc0, 0x92, 0xce, 0xa3, 0xc3, 0x2e, 0x85, 0xb6,
|
|
||||||
0xd9, 0xb1, 0x5e, 0x97, 0x42, 0xdb, 0xec, 0x86, 0x4b, 0x18, 0x5c, 0xf8, 0xba, 0x11, 0x53, 0x06,
|
|
||||||
0x31, 0x06, 0x83, 0xb3, 0x0e, 0x66, 0x2f, 0x8e, 0x6d, 0x5d, 0xaa, 0xbc, 0xbb, 0xfa, 0x16, 0x7e,
|
|
||||||
0x0d, 0x86, 0x3f, 0xa0, 0x7f, 0xb4, 0xfb, 0x0c, 0x95, 0x05, 0xa4, 0xa7, 0x39, 0x9e, 0x2e, 0x93,
|
|
||||||
0xfd, 0x09, 0xa0, 0xcf, 0xa5, 0xd1, 0xaa, 0x36, 0x92, 0xbe, 0x07, 0x30, 0x56, 0xd8, 0xd6, 0x7c,
|
|
||||||
0x57, 0x85, 0x44, 0xb5, 0x98, 0x5f, 0x9c, 0xd0, 0x2f, 0xa7, 0xc5, 0x85, 0x98, 0xec, 0xe8, 0x9c,
|
|
||||||
0x6c, 0xa7, 0x70, 0x73, 0x73, 0xc7, 0x78, 0xc9, 0x39, 0xde, 0xbb, 0x85, 0x99, 0xfd, 0x0b, 0x20,
|
|
||||||
0x5e, 0xec, 0x65, 0x8d, 0x5b, 0xac, 0x45, 0x25, 0xbd, 0x08, 0x62, 0xfa, 0x12, 0xc2, 0xb2, 0xf0,
|
|
||||||
0x6f, 0x2f, 0x2c, 0x0b, 0x3a, 0x82, 0xd4, 0x96, 0x95, 0x34, 0x56, 0x54, 0x1a, 0xfd, 0x10, 0x7e,
|
|
||||||
0x3e, 0xa0, 0x9f, 0x4f, 0xe3, 0x45, 0x0f, 0x1f, 0x0e, 0x36, 0x78, 0x6c, 0xb6, 0x42, 0x58, 0xc1,
|
|
||||||
0xe2, 0xae, 0xa9, 0xc3, 0x77, 0x9b, 0x6d, 0x9d, 0xe0, 0x0f, 0x3a, 0xff, 0x1f, 0x00, 0x00, 0xff,
|
|
||||||
0xff, 0xd4, 0x6d, 0x70, 0x51, 0xb7, 0x03, 0x00, 0x00,
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
|
||||||
// source: api/proto/api.proto
|
|
||||||
|
|
||||||
package go_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package go.api;
|
|
||||||
|
|
||||||
message Pair {
|
|
||||||
string key = 1;
|
|
||||||
repeated string values = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP request as RPC
|
|
||||||
// Forward by the api handler
|
|
||||||
message Request {
|
|
||||||
string method = 1;
|
|
||||||
string path = 2;
|
|
||||||
map<string, Pair> header = 3;
|
|
||||||
map<string, Pair> get = 4;
|
|
||||||
map<string, Pair> post = 5;
|
|
||||||
string body = 6; // raw request body; if not application/x-www-form-urlencoded
|
|
||||||
string url = 7;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP response as RPC
|
|
||||||
// Expected response for the api handler
|
|
||||||
message Response {
|
|
||||||
int32 statusCode = 1;
|
|
||||||
map<string, Pair> header = 2;
|
|
||||||
string body = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A HTTP event as RPC
|
|
||||||
// Forwarded by the event handler
|
|
||||||
message Event {
|
|
||||||
// e.g login
|
|
||||||
string name = 1;
|
|
||||||
// uuid
|
|
||||||
string id = 2;
|
|
||||||
// unix timestamp of event
|
|
||||||
int64 timestamp = 3;
|
|
||||||
// event headers
|
|
||||||
map<string, Pair> header = 4;
|
|
||||||
// the event data
|
|
||||||
string data = 5;
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
// Package grpc resolves a grpc service like /greeter.Say/Hello to greeter service
|
|
||||||
package grpc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
opts resolver.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
|
||||||
// parse options
|
|
||||||
options := resolver.NewResolveOptions(opts...)
|
|
||||||
|
|
||||||
// /foo.Bar/Service
|
|
||||||
if req.URL.Path == "/" {
|
|
||||||
return nil, errors.New("unknown name")
|
|
||||||
}
|
|
||||||
// [foo.Bar, Service]
|
|
||||||
parts := strings.Split(req.URL.Path[1:], "/")
|
|
||||||
// [foo, Bar]
|
|
||||||
name := strings.Split(parts[0], ".")
|
|
||||||
// foo
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: strings.Join(name[:len(name)-1], "."),
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) String() string {
|
|
||||||
return "grpc"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
|
||||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
// Package host resolves using http host
|
|
||||||
package host
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
opts resolver.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
|
||||||
// parse options
|
|
||||||
options := resolver.NewResolveOptions(opts...)
|
|
||||||
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: req.Host,
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) String() string {
|
|
||||||
return "host"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
|
||||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package resolver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
Handler string
|
|
||||||
ServicePrefix string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
// WithHandler sets the handler being used
|
|
||||||
func WithHandler(h string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Handler = h
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithServicePrefix sets the ServicePrefix option
|
|
||||||
func WithServicePrefix(p string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.ServicePrefix = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewOptions returns new initialised options
|
|
||||||
func NewOptions(opts ...Option) Options {
|
|
||||||
var options Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolveOptions are used when resolving a request
|
|
||||||
type ResolveOptions struct {
|
|
||||||
Domain string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolveOption sets an option
|
|
||||||
type ResolveOption func(*ResolveOptions)
|
|
||||||
|
|
||||||
// Domain sets the resolve Domain option
|
|
||||||
func Domain(n string) ResolveOption {
|
|
||||||
return func(o *ResolveOptions) {
|
|
||||||
o.Domain = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewResolveOptions returns new initialised resolve options
|
|
||||||
func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
|
|
||||||
var options ResolveOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
if len(options.Domain) == 0 {
|
|
||||||
options.Domain = registry.DefaultDomain
|
|
||||||
}
|
|
||||||
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
// Package path resolves using http path
|
|
||||||
package path
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
opts resolver.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
|
||||||
// parse options
|
|
||||||
options := resolver.NewResolveOptions(opts...)
|
|
||||||
|
|
||||||
if req.URL.Path == "/" {
|
|
||||||
return nil, resolver.ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(req.URL.Path[1:], "/")
|
|
||||||
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: r.opts.ServicePrefix + "." + parts[0],
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) String() string {
|
|
||||||
return "path"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
|
||||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
// Package resolver resolves a http request to an endpoint
|
|
||||||
package resolver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrNotFound = errors.New("not found")
|
|
||||||
ErrInvalidPath = errors.New("invalid path")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Resolver resolves requests to endpoints
|
|
||||||
type Resolver interface {
|
|
||||||
Resolve(r *http.Request, opts ...ResolveOption) (*Endpoint, error)
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Endpoint is the endpoint for a http request
|
|
||||||
type Endpoint struct {
|
|
||||||
// e.g greeter
|
|
||||||
Name string
|
|
||||||
// HTTP Host e.g example.com
|
|
||||||
Host string
|
|
||||||
// HTTP Methods e.g GET, POST
|
|
||||||
Method string
|
|
||||||
// HTTP Path e.g /greeter.
|
|
||||||
Path string
|
|
||||||
// Domain endpoint exists within
|
|
||||||
Domain string
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
// Package subdomain is a resolver which uses the subdomain to determine the domain to route to. It
|
|
||||||
// offloads the endpoint resolution to a child resolver which is provided in New.
|
|
||||||
package subdomain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"golang.org/x/net/publicsuffix"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver {
|
|
||||||
options := resolver.NewOptions(opts...)
|
|
||||||
return &Resolver{options, parent}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
opts resolver.Options
|
|
||||||
resolver.Resolver
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
|
||||||
if dom := r.Domain(req); len(dom) > 0 {
|
|
||||||
opts = append(opts, resolver.Domain(dom))
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.Resolver.Resolve(req, opts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) Domain(req *http.Request) string {
|
|
||||||
// determine the host, e.g. foobar.m3o.app
|
|
||||||
host := req.URL.Hostname()
|
|
||||||
if len(host) == 0 {
|
|
||||||
if h, _, err := net.SplitHostPort(req.Host); err == nil {
|
|
||||||
host = h // host does contain a port
|
|
||||||
} else if strings.Contains(err.Error(), "missing port in address") {
|
|
||||||
host = req.Host // host does not contain a port
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// check for an ip address
|
|
||||||
if net.ParseIP(host) != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// check for dev enviroment
|
|
||||||
if host == "localhost" || host == "127.0.0.1" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// extract the top level domain plus one (e.g. 'myapp.com')
|
|
||||||
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
|
|
||||||
if err != nil {
|
|
||||||
logger.Debugf("Unable to extract domain from %v", host)
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// there was no subdomain
|
|
||||||
if host == domain {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// remove the domain from the host, leaving the subdomain, e.g. "staging.foo.myapp.com" => "staging.foo"
|
|
||||||
subdomain := strings.TrimSuffix(host, "."+domain)
|
|
||||||
|
|
||||||
// ignore the API subdomain
|
|
||||||
if subdomain == "api" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// return the reversed subdomain as the namespace, e.g. "staging.foo" => "foo-staging"
|
|
||||||
comps := strings.Split(subdomain, ".")
|
|
||||||
for i := len(comps)/2 - 1; i >= 0; i-- {
|
|
||||||
opp := len(comps) - 1 - i
|
|
||||||
comps[i], comps[opp] = comps[opp], comps[i]
|
|
||||||
}
|
|
||||||
return strings.Join(comps, "-")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) String() string {
|
|
||||||
return "subdomain"
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package subdomain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestResolve(t *testing.T) {
|
|
||||||
tt := []struct {
|
|
||||||
Name string
|
|
||||||
Host string
|
|
||||||
Result string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
Name: "Top level domain",
|
|
||||||
Host: "micro.mu",
|
|
||||||
Result: "micro",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Effective top level domain",
|
|
||||||
Host: "micro.com.au",
|
|
||||||
Result: "micro",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Subdomain dev",
|
|
||||||
Host: "dev.micro.mu",
|
|
||||||
Result: "dev",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Subdomain foo",
|
|
||||||
Host: "foo.micro.mu",
|
|
||||||
Result: "foo",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Multi-level subdomain",
|
|
||||||
Host: "staging.myapp.m3o.app",
|
|
||||||
Result: "myapp-staging",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Dev host",
|
|
||||||
Host: "127.0.0.1",
|
|
||||||
Result: "micro",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "Localhost",
|
|
||||||
Host: "localhost",
|
|
||||||
Result: "micro",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "IP host",
|
|
||||||
Host: "81.151.101.146",
|
|
||||||
Result: "micro",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tt {
|
|
||||||
t.Run(tc.Name, func(t *testing.T) {
|
|
||||||
r := NewResolver(vpath.NewResolver())
|
|
||||||
result, err := r.Resolve(&http.Request{URL: &url.URL{Host: tc.Host, Path: "foo/bar"}})
|
|
||||||
assert.Nil(t, err, "Expecter err to be nil")
|
|
||||||
if result != nil {
|
|
||||||
assert.Equal(t, tc.Result, result.Domain, "Expected %v but got %v", tc.Result, result.Domain)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
// Package vpath resolves using http path and recognised versioned urls
|
|
||||||
package vpath
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
|
||||||
return &Resolver{opts: resolver.NewOptions(opts...)}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
opts resolver.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
re = regexp.MustCompile("^v[0-9]+$")
|
|
||||||
)
|
|
||||||
|
|
||||||
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
|
|
||||||
if req.URL.Path == "/" {
|
|
||||||
return nil, errors.New("unknown name")
|
|
||||||
}
|
|
||||||
|
|
||||||
options := resolver.NewResolveOptions(opts...)
|
|
||||||
|
|
||||||
parts := strings.Split(req.URL.Path[1:], "/")
|
|
||||||
if len(parts) == 1 {
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: r.withPrefix(parts...),
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// /v1/foo
|
|
||||||
if re.MatchString(parts[0]) {
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: r.withPrefix(parts[0:2]...),
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &resolver.Endpoint{
|
|
||||||
Name: r.withPrefix(parts[0]),
|
|
||||||
Host: req.Host,
|
|
||||||
Method: req.Method,
|
|
||||||
Path: req.URL.Path,
|
|
||||||
Domain: options.Domain,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) String() string {
|
|
||||||
return "path"
|
|
||||||
}
|
|
||||||
|
|
||||||
// withPrefix transforms "foo" into "go.micro.api.foo"
|
|
||||||
func (r *Resolver) withPrefix(parts ...string) string {
|
|
||||||
p := r.opts.ServicePrefix
|
|
||||||
if len(p) > 0 {
|
|
||||||
parts = append([]string{p}, parts...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.Join(parts, ".")
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
package router
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver/vpath"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
Handler string
|
|
||||||
Registry registry.Registry
|
|
||||||
Resolver resolver.Resolver
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
func NewOptions(opts ...Option) Options {
|
|
||||||
options := Options{
|
|
||||||
Handler: "meta",
|
|
||||||
Registry: mdns.NewRegistry(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
if options.Resolver == nil {
|
|
||||||
options.Resolver = vpath.NewResolver(
|
|
||||||
resolver.WithHandler(options.Handler),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithHandler(h string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Handler = h
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithRegistry(r registry.Registry) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Registry = r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithResolver(r resolver.Resolver) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Resolver = r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,501 +0,0 @@
|
|||||||
// Package registry provides a dynamic api service router
|
|
||||||
package registry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/cache"
|
|
||||||
util "github.com/micro/go-micro/v3/util/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
// endpoint struct, that holds compiled pcre
|
|
||||||
type endpoint struct {
|
|
||||||
hostregs []*regexp.Regexp
|
|
||||||
pathregs []util.Pattern
|
|
||||||
pcreregs []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
// router is the default router
|
|
||||||
type registryRouter struct {
|
|
||||||
exit chan bool
|
|
||||||
opts router.Options
|
|
||||||
|
|
||||||
// registry cache
|
|
||||||
rc cache.Cache
|
|
||||||
|
|
||||||
sync.RWMutex
|
|
||||||
eps map[string]*api.Service
|
|
||||||
// compiled regexp for host and path
|
|
||||||
ceps map[string]*endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) isClosed() bool {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// refresh list of api services
|
|
||||||
func (r *registryRouter) refresh() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
services, err := r.opts.Registry.ListServices()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to list services: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
// for each service, get service and store endpoints
|
|
||||||
for _, s := range services {
|
|
||||||
service, err := r.rc.GetService(s.Name)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to get service: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
r.store(service)
|
|
||||||
}
|
|
||||||
|
|
||||||
// refresh list in 10 minutes... cruft
|
|
||||||
// use registry watching
|
|
||||||
select {
|
|
||||||
case <-time.After(time.Minute * 10):
|
|
||||||
case <-r.exit:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// process watch event
|
|
||||||
func (r *registryRouter) process(res *registry.Result) {
|
|
||||||
// skip these things
|
|
||||||
if res == nil || res.Service == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// get entry from cache
|
|
||||||
service, err := r.rc.GetService(res.Service.Name)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("unable to get %v service: %v", res.Service.Name, err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// update our local endpoints
|
|
||||||
r.store(service)
|
|
||||||
}
|
|
||||||
|
|
||||||
// store local endpoint cache
|
|
||||||
func (r *registryRouter) store(services []*registry.Service) {
|
|
||||||
// endpoints
|
|
||||||
eps := map[string]*api.Service{}
|
|
||||||
|
|
||||||
// services
|
|
||||||
names := map[string]bool{}
|
|
||||||
|
|
||||||
// create a new endpoint mapping
|
|
||||||
for _, service := range services {
|
|
||||||
// set names we need later
|
|
||||||
names[service.Name] = true
|
|
||||||
|
|
||||||
// map per endpoint
|
|
||||||
for _, sep := range service.Endpoints {
|
|
||||||
// create a key service:endpoint_name
|
|
||||||
key := fmt.Sprintf("%s.%s", service.Name, sep.Name)
|
|
||||||
// decode endpoint
|
|
||||||
end := api.Decode(sep.Metadata)
|
|
||||||
// no endpoint or no name
|
|
||||||
if end == nil || len(end.Name) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// if we got nothing skip
|
|
||||||
if err := api.Validate(end); err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint validation failed: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get endpoint
|
|
||||||
ep, ok := eps[key]
|
|
||||||
if !ok {
|
|
||||||
ep = &api.Service{Name: service.Name}
|
|
||||||
}
|
|
||||||
|
|
||||||
// overwrite the endpoint
|
|
||||||
ep.Endpoint = end
|
|
||||||
// append services
|
|
||||||
ep.Services = append(ep.Services, service)
|
|
||||||
// store it
|
|
||||||
eps[key] = ep
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Lock()
|
|
||||||
defer r.Unlock()
|
|
||||||
|
|
||||||
// delete any existing eps for services we know
|
|
||||||
for key, service := range r.eps {
|
|
||||||
// skip what we don't care about
|
|
||||||
if !names[service.Name] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// ok we know this thing
|
|
||||||
// delete delete delete
|
|
||||||
delete(r.eps, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// now set the eps we have
|
|
||||||
for name, ep := range eps {
|
|
||||||
r.eps[name] = ep
|
|
||||||
cep := &endpoint{}
|
|
||||||
|
|
||||||
for _, h := range ep.Endpoint.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
hostreg, err := regexp.CompilePOSIX(h)
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid host regexp: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
cep.hostregs = append(cep.hostregs, hostreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range ep.Endpoint.Path {
|
|
||||||
var pcreok bool
|
|
||||||
|
|
||||||
if p[0] == '^' && p[len(p)-1] == '$' {
|
|
||||||
pcrereg, err := regexp.CompilePOSIX(p)
|
|
||||||
if err == nil {
|
|
||||||
cep.pcreregs = append(cep.pcreregs, pcrereg)
|
|
||||||
pcreok = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rule, err := util.Parse(p)
|
|
||||||
if err != nil && !pcreok {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid path pattern: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
} else if err != nil && pcreok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
tpl := rule.Compile()
|
|
||||||
pathreg, err := util.NewPattern(tpl.Version, tpl.OpCodes, tpl.Pool, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
|
|
||||||
logger.Tracef("endpoint have invalid path pattern: %v", err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
cep.pathregs = append(cep.pathregs, pathreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.ceps[name] = cep
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for endpoint changes
|
|
||||||
func (r *registryRouter) watch() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
if r.isClosed() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for changes
|
|
||||||
w, err := r.opts.Registry.Watch()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("error watching endpoints: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan bool)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-ch:
|
|
||||||
w.Stop()
|
|
||||||
case <-r.exit:
|
|
||||||
w.Stop()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// reset if we get here
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
for {
|
|
||||||
// process next event
|
|
||||||
res, err := w.Next()
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Errorf("error getting next endpoint: %v", err)
|
|
||||||
}
|
|
||||||
close(ch)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
r.process(res)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Options() router.Options {
|
|
||||||
return r.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Close() error {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(r.exit)
|
|
||||||
r.rc.Stop()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Register(ep *api.Endpoint) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Deregister(ep *api.Endpoint) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.RLock()
|
|
||||||
defer r.RUnlock()
|
|
||||||
|
|
||||||
var idx int
|
|
||||||
if len(req.URL.Path) > 0 && req.URL.Path != "/" {
|
|
||||||
idx = 1
|
|
||||||
}
|
|
||||||
path := strings.Split(req.URL.Path[idx:], "/")
|
|
||||||
|
|
||||||
// use the first match
|
|
||||||
// TODO: weighted matching
|
|
||||||
for n, e := range r.eps {
|
|
||||||
cep, ok := r.ceps[n]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ep := e.Endpoint
|
|
||||||
var mMatch, hMatch, pMatch bool
|
|
||||||
// 1. try method
|
|
||||||
for _, m := range ep.Method {
|
|
||||||
if m == req.Method {
|
|
||||||
mMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !mMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api method match %s", req.Method)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. try host
|
|
||||||
if len(ep.Host) == 0 {
|
|
||||||
hMatch = true
|
|
||||||
} else {
|
|
||||||
for idx, h := range ep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if cep.hostregs[idx].MatchString(req.URL.Host) {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api host match %s", req.URL.Host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. try path via google.api path matching
|
|
||||||
for _, pathreg := range cep.pathregs {
|
|
||||||
matches, err := pathreg.Match(path, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath match %s = %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
ctx := req.Context()
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(metadata.Metadata)
|
|
||||||
}
|
|
||||||
for k, v := range matches {
|
|
||||||
md[fmt.Sprintf("x-api-field-%s", k)] = v
|
|
||||||
}
|
|
||||||
md["x-api-body"] = ep.Body
|
|
||||||
*req = *req.Clone(metadata.NewContext(ctx, md))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
// 4. try path via pcre path matching
|
|
||||||
for _, pathreg := range cep.pcreregs {
|
|
||||||
if !pathreg.MatchString(req.URL.Path) {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Percentage traffic
|
|
||||||
// we got here, so its a match
|
|
||||||
return e, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// no match
|
|
||||||
return nil, errors.New("not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *registryRouter) Route(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get an endpoint
|
|
||||||
ep, err := r.Endpoint(req)
|
|
||||||
if err == nil {
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// error not nil
|
|
||||||
// ignore that shit
|
|
||||||
// TODO: don't ignore that shit
|
|
||||||
|
|
||||||
// get the service name
|
|
||||||
rp, err := r.opts.Resolver.Resolve(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// service name
|
|
||||||
name := rp.Name
|
|
||||||
|
|
||||||
// get service
|
|
||||||
services, err := r.rc.GetService(name, registry.GetDomain(rp.Domain))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// only use endpoint matching when the meta handler is set aka api.Default
|
|
||||||
switch r.opts.Handler {
|
|
||||||
// rpc handlers
|
|
||||||
case "meta", "api", "rpc":
|
|
||||||
handler := r.opts.Handler
|
|
||||||
|
|
||||||
// set default handler to api
|
|
||||||
if r.opts.Handler == "meta" {
|
|
||||||
handler = "rpc"
|
|
||||||
}
|
|
||||||
|
|
||||||
// construct api service
|
|
||||||
return &api.Service{
|
|
||||||
Name: name,
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: rp.Method,
|
|
||||||
Handler: handler,
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}, nil
|
|
||||||
// http handler
|
|
||||||
case "http", "proxy", "web":
|
|
||||||
// construct api service
|
|
||||||
return &api.Service{
|
|
||||||
Name: name,
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: req.URL.String(),
|
|
||||||
Handler: r.opts.Handler,
|
|
||||||
Host: []string{req.Host},
|
|
||||||
Method: []string{req.Method},
|
|
||||||
Path: []string{req.URL.Path},
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, errors.New("unknown handler")
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRouter(opts ...router.Option) *registryRouter {
|
|
||||||
options := router.NewOptions(opts...)
|
|
||||||
r := ®istryRouter{
|
|
||||||
exit: make(chan bool),
|
|
||||||
opts: options,
|
|
||||||
rc: cache.New(options.Registry),
|
|
||||||
eps: make(map[string]*api.Service),
|
|
||||||
ceps: make(map[string]*endpoint),
|
|
||||||
}
|
|
||||||
go r.watch()
|
|
||||||
go r.refresh()
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRouter returns the default router
|
|
||||||
func NewRouter(opts ...router.Option) router.Router {
|
|
||||||
return newRouter(opts...)
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package registry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestStoreRegex(t *testing.T) {
|
|
||||||
router := newRouter()
|
|
||||||
router.store([]*registry.Service{
|
|
||||||
{
|
|
||||||
Name: "Foobar",
|
|
||||||
Version: "latest",
|
|
||||||
Endpoints: []*registry.Endpoint{
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Metadata: map[string]string{
|
|
||||||
"endpoint": "FooEndpoint",
|
|
||||||
"description": "Some description",
|
|
||||||
"method": "POST",
|
|
||||||
"path": "^/foo/$",
|
|
||||||
"handler": "rpc",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Metadata: map[string]string{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Len(t, router.ceps["Foobar.foo"].pcreregs, 1)
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
// Package router provides api service routing
|
|
||||||
package router
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Router is used to determine an endpoint for a request
|
|
||||||
type Router interface {
|
|
||||||
// Returns options
|
|
||||||
Options() Options
|
|
||||||
// Stop the router
|
|
||||||
Close() error
|
|
||||||
// Endpoint returns an api.Service endpoint or an error if it does not exist
|
|
||||||
Endpoint(r *http.Request) (*api.Service, error)
|
|
||||||
// Register endpoint in router
|
|
||||||
Register(ep *api.Endpoint) error
|
|
||||||
// Deregister endpoint from router
|
|
||||||
Deregister(ep *api.Endpoint) error
|
|
||||||
// Route returns an api.Service route
|
|
||||||
Route(r *http.Request) (*api.Service, error)
|
|
||||||
}
|
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
package router_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler"
|
|
||||||
"github.com/micro/go-micro/v3/api/handler/rpc"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
rregistry "github.com/micro/go-micro/v3/api/router/registry"
|
|
||||||
rstatic "github.com/micro/go-micro/v3/api/router/static"
|
|
||||||
"github.com/micro/go-micro/v3/client"
|
|
||||||
gcli "github.com/micro/go-micro/v3/client/grpc"
|
|
||||||
rmemory "github.com/micro/go-micro/v3/registry/memory"
|
|
||||||
rt "github.com/micro/go-micro/v3/router"
|
|
||||||
regRouter "github.com/micro/go-micro/v3/router/registry"
|
|
||||||
"github.com/micro/go-micro/v3/server"
|
|
||||||
gsrv "github.com/micro/go-micro/v3/server/grpc"
|
|
||||||
pb "github.com/micro/go-micro/v3/server/grpc/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
// server is used to implement helloworld.GreeterServer.
|
|
||||||
type testServer struct {
|
|
||||||
msgCount int
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) CallPcre(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHello implements helloworld.GreeterServer
|
|
||||||
func (s *testServer) CallPcreInvalid(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
|
|
||||||
rsp.Msg = "Hello " + req.Uuid
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initial(t *testing.T) (server.Server, client.Client) {
|
|
||||||
r := rmemory.NewRegistry()
|
|
||||||
|
|
||||||
// create a new client
|
|
||||||
s := gsrv.NewServer(
|
|
||||||
server.Name("foo"),
|
|
||||||
server.Registry(r),
|
|
||||||
)
|
|
||||||
|
|
||||||
rtr := regRouter.NewRouter(
|
|
||||||
rt.Registry(r),
|
|
||||||
)
|
|
||||||
|
|
||||||
// create a new server
|
|
||||||
c := gcli.NewClient(
|
|
||||||
client.Router(rtr),
|
|
||||||
)
|
|
||||||
|
|
||||||
h := &testServer{}
|
|
||||||
pb.RegisterTestHandler(s, h)
|
|
||||||
|
|
||||||
if err := s.Start(); err != nil {
|
|
||||||
t.Fatalf("failed to start: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return s, c
|
|
||||||
}
|
|
||||||
|
|
||||||
func check(t *testing.T, addr string, path string, expected string) {
|
|
||||||
req, err := http.NewRequest("POST", fmt.Sprintf(path, addr), nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rsp, err := (&http.Client{}).Do(req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to created http.Request: %v", err)
|
|
||||||
}
|
|
||||||
defer rsp.Body.Close()
|
|
||||||
|
|
||||||
buf, err := ioutil.ReadAll(rsp.Body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonMsg := expected
|
|
||||||
if string(buf) != jsonMsg {
|
|
||||||
t.Fatalf("invalid message received, parsing error %s != %s", buf, jsonMsg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterRegistryPcre(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rregistry.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
|
|
||||||
defer hsrv.Close()
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call/TEST", `{"msg":"Hello TEST"}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticPcre(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
err := router.Register(&api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"^/api/v0/test/call/?$"},
|
|
||||||
Handler: "rpc",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
defer hsrv.Close()
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call", `{"msg":"Hello "}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticGpath(t *testing.T) {
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
err := router.Register(&api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"/api/v0/test/call/{uuid}"},
|
|
||||||
Handler: "rpc",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hrpc := rpc.NewHandler(
|
|
||||||
handler.WithClient(c),
|
|
||||||
handler.WithRouter(router),
|
|
||||||
)
|
|
||||||
hsrv := &http.Server{
|
|
||||||
Handler: hrpc,
|
|
||||||
Addr: "127.0.0.1:6543",
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
IdleTimeout: 20 * time.Second,
|
|
||||||
MaxHeaderBytes: 1024 * 1024 * 1, // 1Mb
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Println(hsrv.ListenAndServe())
|
|
||||||
}()
|
|
||||||
defer hsrv.Close()
|
|
||||||
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
check(t, hsrv.Addr, "http://%s/api/v0/test/call/TEST", `{"msg":"Hello TEST"}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRouterStaticPcreInvalid(t *testing.T) {
|
|
||||||
var ep *api.Endpoint
|
|
||||||
var err error
|
|
||||||
|
|
||||||
s, c := initial(t)
|
|
||||||
defer s.Stop()
|
|
||||||
|
|
||||||
router := rstatic.NewRouter(
|
|
||||||
router.WithHandler(rpc.Handler),
|
|
||||||
router.WithRegistry(s.Options().Registry),
|
|
||||||
)
|
|
||||||
|
|
||||||
ep = &api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"^/api/v0/test/call/?"},
|
|
||||||
Handler: "rpc",
|
|
||||||
}
|
|
||||||
|
|
||||||
err = router.Register(ep)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("invalid endpoint %v", ep)
|
|
||||||
}
|
|
||||||
|
|
||||||
ep = &api.Endpoint{
|
|
||||||
Name: "foo.Test.Call",
|
|
||||||
Method: []string{"POST"},
|
|
||||||
Path: []string{"/api/v0/test/call/?$"},
|
|
||||||
Handler: "rpc",
|
|
||||||
}
|
|
||||||
|
|
||||||
err = router.Register(ep)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("invalid endpoint %v", ep)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = c
|
|
||||||
}
|
|
||||||
@@ -1,356 +0,0 @@
|
|||||||
package static
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api"
|
|
||||||
"github.com/micro/go-micro/v3/api/router"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/metadata"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
rutil "github.com/micro/go-micro/v3/util/registry"
|
|
||||||
util "github.com/micro/go-micro/v3/util/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type endpoint struct {
|
|
||||||
apiep *api.Endpoint
|
|
||||||
hostregs []*regexp.Regexp
|
|
||||||
pathregs []util.Pattern
|
|
||||||
pcreregs []*regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
// router is the default router
|
|
||||||
type staticRouter struct {
|
|
||||||
exit chan bool
|
|
||||||
opts router.Options
|
|
||||||
sync.RWMutex
|
|
||||||
eps map[string]*endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) isClosed() bool {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
// watch for endpoint changes
|
|
||||||
func (r *staticRouter) watch() {
|
|
||||||
var attempts int
|
|
||||||
|
|
||||||
for {
|
|
||||||
if r.isClosed() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// watch for changes
|
|
||||||
w, err := r.opts.Registry.Watch()
|
|
||||||
if err != nil {
|
|
||||||
attempts++
|
|
||||||
log.Println("Error watching endpoints", err)
|
|
||||||
time.Sleep(time.Duration(attempts) * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
ch := make(chan bool)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
select {
|
|
||||||
case <-ch:
|
|
||||||
w.Stop()
|
|
||||||
case <-r.exit:
|
|
||||||
w.Stop()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// reset if we get here
|
|
||||||
attempts = 0
|
|
||||||
|
|
||||||
for {
|
|
||||||
// process next event
|
|
||||||
res, err := w.Next()
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Error getting next endpoint", err)
|
|
||||||
close(ch)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
r.process(res)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
func (r *staticRouter) Register(ep *api.Endpoint) error {
|
|
||||||
if err := api.Validate(ep); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var pathregs []util.Pattern
|
|
||||||
var hostregs []*regexp.Regexp
|
|
||||||
var pcreregs []*regexp.Regexp
|
|
||||||
|
|
||||||
for _, h := range ep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
hostreg, err := regexp.CompilePOSIX(h)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
hostregs = append(hostregs, hostreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range ep.Path {
|
|
||||||
var pcreok bool
|
|
||||||
|
|
||||||
// pcre only when we have start and end markers
|
|
||||||
if p[0] == '^' && p[len(p)-1] == '$' {
|
|
||||||
pcrereg, err := regexp.CompilePOSIX(p)
|
|
||||||
if err == nil {
|
|
||||||
pcreregs = append(pcreregs, pcrereg)
|
|
||||||
pcreok = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rule, err := util.Parse(p)
|
|
||||||
if err != nil && !pcreok {
|
|
||||||
return err
|
|
||||||
} else if err != nil && pcreok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
tpl := rule.Compile()
|
|
||||||
pathreg, err := util.NewPattern(tpl.Version, tpl.OpCodes, tpl.Pool, "")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
pathregs = append(pathregs, pathreg)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Lock()
|
|
||||||
r.eps[ep.Name] = &endpoint{
|
|
||||||
apiep: ep,
|
|
||||||
pcreregs: pcreregs,
|
|
||||||
pathregs: pathregs,
|
|
||||||
hostregs: hostregs,
|
|
||||||
}
|
|
||||||
r.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Deregister(ep *api.Endpoint) error {
|
|
||||||
if err := api.Validate(ep); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.Lock()
|
|
||||||
delete(r.eps, ep.Name)
|
|
||||||
r.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Options() router.Options {
|
|
||||||
return r.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Close() error {
|
|
||||||
select {
|
|
||||||
case <-r.exit:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
close(r.exit)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Endpoint(req *http.Request) (*api.Service, error) {
|
|
||||||
ep, err := r.endpoint(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
epf := strings.Split(ep.apiep.Name, ".")
|
|
||||||
services, err := r.opts.Registry.GetService(epf[0])
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// hack for stream endpoint
|
|
||||||
if ep.apiep.Stream {
|
|
||||||
svcs := rutil.Copy(services)
|
|
||||||
for _, svc := range svcs {
|
|
||||||
if len(svc.Endpoints) == 0 {
|
|
||||||
e := ®istry.Endpoint{}
|
|
||||||
e.Name = strings.Join(epf[1:], ".")
|
|
||||||
e.Metadata = make(map[string]string)
|
|
||||||
e.Metadata["stream"] = "true"
|
|
||||||
svc.Endpoints = append(svc.Endpoints, e)
|
|
||||||
}
|
|
||||||
for _, e := range svc.Endpoints {
|
|
||||||
e.Name = strings.Join(epf[1:], ".")
|
|
||||||
e.Metadata = make(map[string]string)
|
|
||||||
e.Metadata["stream"] = "true"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
services = svcs
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := &api.Service{
|
|
||||||
Name: epf[0],
|
|
||||||
Endpoint: &api.Endpoint{
|
|
||||||
Name: strings.Join(epf[1:], "."),
|
|
||||||
Handler: "rpc",
|
|
||||||
Host: ep.apiep.Host,
|
|
||||||
Method: ep.apiep.Method,
|
|
||||||
Path: ep.apiep.Path,
|
|
||||||
Body: ep.apiep.Body,
|
|
||||||
Stream: ep.apiep.Stream,
|
|
||||||
},
|
|
||||||
Services: services,
|
|
||||||
}
|
|
||||||
|
|
||||||
return svc, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) endpoint(req *http.Request) (*endpoint, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.RLock()
|
|
||||||
defer r.RUnlock()
|
|
||||||
|
|
||||||
var idx int
|
|
||||||
if len(req.URL.Path) > 0 && req.URL.Path != "/" {
|
|
||||||
idx = 1
|
|
||||||
}
|
|
||||||
path := strings.Split(req.URL.Path[idx:], "/")
|
|
||||||
// use the first match
|
|
||||||
// TODO: weighted matching
|
|
||||||
|
|
||||||
for _, ep := range r.eps {
|
|
||||||
var mMatch, hMatch, pMatch bool
|
|
||||||
|
|
||||||
// 1. try method
|
|
||||||
for _, m := range ep.apiep.Method {
|
|
||||||
if m == req.Method {
|
|
||||||
mMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !mMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api method match %s", req.Method)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. try host
|
|
||||||
if len(ep.apiep.Host) == 0 {
|
|
||||||
hMatch = true
|
|
||||||
} else {
|
|
||||||
for idx, h := range ep.apiep.Host {
|
|
||||||
if h == "" || h == "*" {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if ep.hostregs[idx].MatchString(req.URL.Host) {
|
|
||||||
hMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api host match %s", req.URL.Host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. try google.api path
|
|
||||||
for _, pathreg := range ep.pathregs {
|
|
||||||
matches, err := pathreg.Match(path, "")
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath not match %s != %v", path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api gpath match %s = %v", path, pathreg)
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
ctx := req.Context()
|
|
||||||
md, ok := metadata.FromContext(ctx)
|
|
||||||
if !ok {
|
|
||||||
md = make(metadata.Metadata)
|
|
||||||
}
|
|
||||||
for k, v := range matches {
|
|
||||||
md[fmt.Sprintf("x-api-field-%s", k)] = v
|
|
||||||
}
|
|
||||||
md["x-api-body"] = ep.apiep.Body
|
|
||||||
*req = *req.Clone(metadata.NewContext(ctx, md))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
// 4. try path via pcre path matching
|
|
||||||
for _, pathreg := range ep.pcreregs {
|
|
||||||
if !pathreg.MatchString(req.URL.Path) {
|
|
||||||
if logger.V(logger.DebugLevel, logger.DefaultLogger) {
|
|
||||||
logger.Debugf("api pcre path not match %s != %v", req.URL.Path, pathreg)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
pMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !pMatch {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// TODO: Percentage traffic
|
|
||||||
|
|
||||||
// we got here, so its a match
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// no match
|
|
||||||
return nil, fmt.Errorf("endpoint not found for %v", req.URL)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *staticRouter) Route(req *http.Request) (*api.Service, error) {
|
|
||||||
if r.isClosed() {
|
|
||||||
return nil, errors.New("router closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// try get an endpoint
|
|
||||||
ep, err := r.Endpoint(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ep, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRouter(opts ...router.Option) *staticRouter {
|
|
||||||
options := router.NewOptions(opts...)
|
|
||||||
r := &staticRouter{
|
|
||||||
exit: make(chan bool),
|
|
||||||
opts: options,
|
|
||||||
eps: make(map[string]*endpoint),
|
|
||||||
}
|
|
||||||
//go r.watch()
|
|
||||||
//go r.refresh()
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
// Package acme abstracts away various ACME libraries
|
|
||||||
package acme
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrProviderNotImplemented can be returned when attempting to
|
|
||||||
// instantiate an unimplemented provider
|
|
||||||
ErrProviderNotImplemented = errors.New("Provider not implemented")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Provider is a ACME provider interface
|
|
||||||
type Provider interface {
|
|
||||||
// Listen returns a new listener
|
|
||||||
Listen(...string) (net.Listener, error)
|
|
||||||
// TLSConfig returns a tls config
|
|
||||||
TLSConfig(...string) (*tls.Config, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Let's Encrypt ACME endpoints
|
|
||||||
const (
|
|
||||||
LetsEncryptStagingCA = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
|
||||||
LetsEncryptProductionCA = "https://acme-v02.api.letsencrypt.org/directory"
|
|
||||||
)
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
// Package autocert is the ACME provider from golang.org/x/crypto/acme/autocert
|
|
||||||
// This provider does not take any config.
|
|
||||||
package autocert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"golang.org/x/crypto/acme/autocert"
|
|
||||||
)
|
|
||||||
|
|
||||||
// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert
|
|
||||||
type autocertProvider struct{}
|
|
||||||
|
|
||||||
// Listen implements acme.Provider
|
|
||||||
func (a *autocertProvider) Listen(hosts ...string) (net.Listener, error) {
|
|
||||||
return autocert.NewListener(hosts...), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TLSConfig returns a new tls config
|
|
||||||
func (a *autocertProvider) TLSConfig(hosts ...string) (*tls.Config, error) {
|
|
||||||
// create a new manager
|
|
||||||
m := &autocert.Manager{
|
|
||||||
Prompt: autocert.AcceptTOS,
|
|
||||||
}
|
|
||||||
if len(hosts) > 0 {
|
|
||||||
m.HostPolicy = autocert.HostWhitelist(hosts...)
|
|
||||||
}
|
|
||||||
dir := cacheDir()
|
|
||||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
|
||||||
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
|
|
||||||
logger.Infof("warning: autocert not using a cache: %v", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
m.Cache = autocert.DirCache(dir)
|
|
||||||
}
|
|
||||||
return m.TLSConfig(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns an autocert acme.Provider
|
|
||||||
func NewProvider() acme.Provider {
|
|
||||||
return &autocertProvider{}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package autocert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestAutocert(t *testing.T) {
|
|
||||||
l := NewProvider()
|
|
||||||
if _, ok := l.(*autocertProvider); !ok {
|
|
||||||
t.Error("NewProvider() didn't return an autocertProvider")
|
|
||||||
}
|
|
||||||
// TODO: Travis CI doesn't let us bind :443
|
|
||||||
// if _, err := l.NewListener(); err != nil {
|
|
||||||
// t.Error(err.Error())
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package autocert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
)
|
|
||||||
|
|
||||||
func homeDir() string {
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
|
|
||||||
}
|
|
||||||
if h := os.Getenv("HOME"); h != "" {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
return "/"
|
|
||||||
}
|
|
||||||
|
|
||||||
func cacheDir() string {
|
|
||||||
const base = "golang-autocert"
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "darwin":
|
|
||||||
return filepath.Join(homeDir(), "Library", "Caches", base)
|
|
||||||
case "windows":
|
|
||||||
for _, ev := range []string{"APPDATA", "CSIDL_APPDATA", "TEMP", "TMP"} {
|
|
||||||
if v := os.Getenv(ev); v != "" {
|
|
||||||
return filepath.Join(v, base)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Worst case:
|
|
||||||
return filepath.Join(homeDir(), base)
|
|
||||||
}
|
|
||||||
if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" {
|
|
||||||
return filepath.Join(xdg, base)
|
|
||||||
}
|
|
||||||
return filepath.Join(homeDir(), ".cache", base)
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
// Package certmagic is the ACME provider from github.com/caddyserver/certmagic
|
|
||||||
package certmagic
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"math/rand"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type certmagicProvider struct {
|
|
||||||
opts acme.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: set self-contained options
|
|
||||||
func (c *certmagicProvider) setup() {
|
|
||||||
certmagic.DefaultACME.CA = c.opts.CA
|
|
||||||
if c.opts.ChallengeProvider != nil {
|
|
||||||
// Enabling DNS Challenge disables the other challenges
|
|
||||||
certmagic.DefaultACME.DNSProvider = c.opts.ChallengeProvider
|
|
||||||
}
|
|
||||||
if c.opts.OnDemand {
|
|
||||||
certmagic.Default.OnDemand = new(certmagic.OnDemandConfig)
|
|
||||||
}
|
|
||||||
if c.opts.Cache != nil {
|
|
||||||
// already validated by new()
|
|
||||||
certmagic.Default.Storage = c.opts.Cache.(certmagic.Storage)
|
|
||||||
}
|
|
||||||
// If multiple instances of the provider are running, inject some
|
|
||||||
// randomness so they don't collide
|
|
||||||
// RenewalWindowRatio [0.33 - 0.50)
|
|
||||||
rand.Seed(time.Now().UnixNano())
|
|
||||||
randomRatio := float64(rand.Intn(17)+33) * 0.01
|
|
||||||
certmagic.Default.RenewalWindowRatio = randomRatio
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *certmagicProvider) Listen(hosts ...string) (net.Listener, error) {
|
|
||||||
c.setup()
|
|
||||||
return certmagic.Listen(hosts)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *certmagicProvider) TLSConfig(hosts ...string) (*tls.Config, error) {
|
|
||||||
c.setup()
|
|
||||||
return certmagic.TLS(hosts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewProvider returns a certmagic provider
|
|
||||||
func NewProvider(options ...acme.Option) acme.Provider {
|
|
||||||
opts := acme.DefaultOptions()
|
|
||||||
|
|
||||||
for _, o := range options {
|
|
||||||
o(&opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.Cache != nil {
|
|
||||||
if _, ok := opts.Cache.(certmagic.Storage); !ok {
|
|
||||||
logger.Fatal("ACME: cache provided doesn't implement certmagic's Storage interface")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &certmagicProvider{
|
|
||||||
opts: opts,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
package certmagic
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/gob"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"path"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
"github.com/micro/go-micro/v3/store"
|
|
||||||
"github.com/micro/go-micro/v3/sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// File represents a "File" that will be stored in store.Store - the contents and last modified time
|
|
||||||
type File struct {
|
|
||||||
// last modified time
|
|
||||||
LastModified time.Time
|
|
||||||
// Contents
|
|
||||||
Contents []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// storage is an implementation of certmagic.Storage using micro's sync.Map and store.Store interfaces.
|
|
||||||
// As certmagic storage expects a filesystem (with stat() abilities) we have to implement
|
|
||||||
// the bare minimum of metadata.
|
|
||||||
type storage struct {
|
|
||||||
lock sync.Sync
|
|
||||||
store store.Store
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Lock(key string) error {
|
|
||||||
return s.lock.Lock(key, sync.LockTTL(10*time.Minute))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Unlock(key string) error {
|
|
||||||
return s.lock.Unlock(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Store(key string, value []byte) error {
|
|
||||||
f := File{
|
|
||||||
LastModified: time.Now(),
|
|
||||||
Contents: value,
|
|
||||||
}
|
|
||||||
buf := &bytes.Buffer{}
|
|
||||||
e := gob.NewEncoder(buf)
|
|
||||||
if err := e.Encode(f); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r := &store.Record{
|
|
||||||
Key: key,
|
|
||||||
Value: buf.Bytes(),
|
|
||||||
}
|
|
||||||
return s.store.Write(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Load(key string) ([]byte, error) {
|
|
||||||
if !s.Exists(key) {
|
|
||||||
return nil, certmagic.ErrNotExist(errors.New(key + " doesn't exist"))
|
|
||||||
}
|
|
||||||
records, err := s.store.Read(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(records) != 1 {
|
|
||||||
return nil, fmt.Errorf("ACME Storage: multiple records matched key %s", key)
|
|
||||||
}
|
|
||||||
b := bytes.NewBuffer(records[0].Value)
|
|
||||||
d := gob.NewDecoder(b)
|
|
||||||
var f File
|
|
||||||
err = d.Decode(&f)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return f.Contents, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Delete(key string) error {
|
|
||||||
return s.store.Delete(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Exists(key string) bool {
|
|
||||||
if _, err := s.store.Read(key); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) List(prefix string, recursive bool) ([]string, error) {
|
|
||||||
keys, err := s.store.List()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:prealloc
|
|
||||||
var results []string
|
|
||||||
for _, k := range keys {
|
|
||||||
if strings.HasPrefix(k, prefix) {
|
|
||||||
results = append(results, k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if recursive {
|
|
||||||
return results, nil
|
|
||||||
}
|
|
||||||
keysMap := make(map[string]bool)
|
|
||||||
for _, key := range results {
|
|
||||||
dir := strings.Split(strings.TrimPrefix(key, prefix+"/"), "/")
|
|
||||||
keysMap[dir[0]] = true
|
|
||||||
}
|
|
||||||
results = make([]string, 0)
|
|
||||||
for k := range keysMap {
|
|
||||||
results = append(results, path.Join(prefix, k))
|
|
||||||
}
|
|
||||||
return results, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *storage) Stat(key string) (certmagic.KeyInfo, error) {
|
|
||||||
records, err := s.store.Read(key)
|
|
||||||
if err != nil {
|
|
||||||
return certmagic.KeyInfo{}, err
|
|
||||||
}
|
|
||||||
if len(records) != 1 {
|
|
||||||
return certmagic.KeyInfo{}, fmt.Errorf("ACME Storage: multiple records matched key %s", key)
|
|
||||||
}
|
|
||||||
b := bytes.NewBuffer(records[0].Value)
|
|
||||||
d := gob.NewDecoder(b)
|
|
||||||
var f File
|
|
||||||
err = d.Decode(&f)
|
|
||||||
if err != nil {
|
|
||||||
return certmagic.KeyInfo{}, err
|
|
||||||
}
|
|
||||||
return certmagic.KeyInfo{
|
|
||||||
Key: key,
|
|
||||||
Modified: f.LastModified,
|
|
||||||
Size: int64(len(f.Contents)),
|
|
||||||
IsTerminal: false,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewStorage returns a certmagic.Storage backed by a go-micro/lock and go-micro/store
|
|
||||||
func NewStorage(lock sync.Sync, store store.Store) certmagic.Storage {
|
|
||||||
return &storage{
|
|
||||||
lock: lock,
|
|
||||||
store: store,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package acme
|
|
||||||
|
|
||||||
import "github.com/go-acme/lego/v3/challenge"
|
|
||||||
|
|
||||||
// Option (or Options) are passed to New() to configure providers
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
// Options represents various options you can present to ACME providers
|
|
||||||
type Options struct {
|
|
||||||
// AcceptTLS must be set to true to indicate that you have read your
|
|
||||||
// provider's terms of service.
|
|
||||||
AcceptToS bool
|
|
||||||
// CA is the CA to use
|
|
||||||
CA string
|
|
||||||
// ChallengeProvider is a go-acme/lego challenge provider. Set this if you
|
|
||||||
// want to use DNS Challenges. Otherwise, tls-alpn-01 will be used
|
|
||||||
ChallengeProvider challenge.Provider
|
|
||||||
// Issue certificates for domains on demand. Otherwise, certs will be
|
|
||||||
// retrieved / issued on start-up.
|
|
||||||
OnDemand bool
|
|
||||||
// Cache is a storage interface. Most ACME libraries have an cache, but
|
|
||||||
// there's no defined interface, so if you consume this option
|
|
||||||
// sanity check it before using.
|
|
||||||
Cache interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AcceptToS indicates whether you accept your CA's terms of service
|
|
||||||
func AcceptToS(b bool) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.AcceptToS = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// CA sets the CA of an acme.Options
|
|
||||||
func CA(CA string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.CA = CA
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChallengeProvider sets the Challenge provider of an acme.Options
|
|
||||||
// if set, it enables the DNS challenge, otherwise tls-alpn-01 will be used.
|
|
||||||
func ChallengeProvider(p challenge.Provider) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.ChallengeProvider = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// OnDemand enables on-demand certificate issuance. Not recommended for use
|
|
||||||
// with the DNS challenge, as the first connection may be very slow.
|
|
||||||
func OnDemand(b bool) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.OnDemand = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache provides a cache / storage interface to the underlying ACME library
|
|
||||||
// as there is no standard, this needs to be validated by the underlying
|
|
||||||
// implentation.
|
|
||||||
func Cache(c interface{}) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Cache = c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultOptions uses the Let's Encrypt Production CA, with DNS Challenge disabled.
|
|
||||||
func DefaultOptions() Options {
|
|
||||||
return Options{
|
|
||||||
AcceptToS: true,
|
|
||||||
CA: LetsEncryptProductionCA,
|
|
||||||
OnDemand: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package cors
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CombinedCORSHandler wraps a server and provides CORS headers
|
|
||||||
func CombinedCORSHandler(h http.Handler) http.Handler {
|
|
||||||
return corsHandler{h}
|
|
||||||
}
|
|
||||||
|
|
||||||
type corsHandler struct {
|
|
||||||
handler http.Handler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
||||||
SetHeaders(w, r)
|
|
||||||
|
|
||||||
if r.Method == "OPTIONS" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.handler.ServeHTTP(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeaders sets the CORS headers
|
|
||||||
func SetHeaders(w http.ResponseWriter, r *http.Request) {
|
|
||||||
set := func(w http.ResponseWriter, k, v string) {
|
|
||||||
if v := w.Header().Get(k); len(v) > 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
if origin := r.Header.Get("Origin"); len(origin) > 0 {
|
|
||||||
set(w, "Access-Control-Allow-Origin", origin)
|
|
||||||
} else {
|
|
||||||
set(w, "Access-Control-Allow-Origin", "*")
|
|
||||||
}
|
|
||||||
|
|
||||||
set(w, "Access-Control-Allow-Credentials", "true")
|
|
||||||
set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE")
|
|
||||||
set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
// Package http provides a http server with features; acme, cors, etc
|
|
||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
|
||||||
"github.com/micro/go-micro/v3/api/server"
|
|
||||||
"github.com/micro/go-micro/v3/api/server/cors"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
type httpServer struct {
|
|
||||||
mux *http.ServeMux
|
|
||||||
opts server.Options
|
|
||||||
|
|
||||||
mtx sync.RWMutex
|
|
||||||
address string
|
|
||||||
exit chan chan error
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewServer(address string, opts ...server.Option) server.Server {
|
|
||||||
var options server.Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &httpServer{
|
|
||||||
opts: options,
|
|
||||||
mux: http.NewServeMux(),
|
|
||||||
address: address,
|
|
||||||
exit: make(chan chan error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) Address() string {
|
|
||||||
s.mtx.RLock()
|
|
||||||
defer s.mtx.RUnlock()
|
|
||||||
return s.address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) Init(opts ...server.Option) error {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&s.opts)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) Handle(path string, handler http.Handler) {
|
|
||||||
// TODO: move this stuff out to one place with ServeHTTP
|
|
||||||
|
|
||||||
// apply the wrappers, e.g. auth
|
|
||||||
for _, wrapper := range s.opts.Wrappers {
|
|
||||||
handler = wrapper(handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
// wrap with cors
|
|
||||||
if s.opts.EnableCORS {
|
|
||||||
handler = cors.CombinedCORSHandler(handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
// wrap with logger
|
|
||||||
handler = handlers.CombinedLoggingHandler(os.Stdout, handler)
|
|
||||||
|
|
||||||
s.mux.Handle(path, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) Start() error {
|
|
||||||
var l net.Listener
|
|
||||||
var err error
|
|
||||||
|
|
||||||
if s.opts.EnableACME && s.opts.ACMEProvider != nil {
|
|
||||||
// should we check the address to make sure its using :443?
|
|
||||||
l, err = s.opts.ACMEProvider.Listen(s.opts.ACMEHosts...)
|
|
||||||
} else if s.opts.EnableTLS && s.opts.TLSConfig != nil {
|
|
||||||
l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
|
|
||||||
} else {
|
|
||||||
// otherwise plain listen
|
|
||||||
l, err = net.Listen("tcp", s.address)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
|
|
||||||
logger.Infof("HTTP API Listening on %s", l.Addr().String())
|
|
||||||
}
|
|
||||||
|
|
||||||
s.mtx.Lock()
|
|
||||||
s.address = l.Addr().String()
|
|
||||||
s.mtx.Unlock()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
if err := http.Serve(l, s.mux); err != nil {
|
|
||||||
// temporary fix
|
|
||||||
//logger.Fatal(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
ch := <-s.exit
|
|
||||||
ch <- l.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) Stop() error {
|
|
||||||
ch := make(chan error)
|
|
||||||
s.exit <- ch
|
|
||||||
return <-ch
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *httpServer) String() string {
|
|
||||||
return "http"
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHTTPServer(t *testing.T) {
|
|
||||||
testResponse := "hello world"
|
|
||||||
|
|
||||||
s := NewServer("localhost:0")
|
|
||||||
|
|
||||||
s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
fmt.Fprint(w, testResponse)
|
|
||||||
}))
|
|
||||||
|
|
||||||
if err := s.Start(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
rsp, err := http.Get(fmt.Sprintf("http://%s/", s.Address()))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer rsp.Body.Close()
|
|
||||||
|
|
||||||
b, err := ioutil.ReadAll(rsp.Body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if string(b) != testResponse {
|
|
||||||
t.Fatalf("Unexpected response, got %s, expected %s", string(b), testResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.Stop(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
package server
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/api/resolver"
|
|
||||||
"github.com/micro/go-micro/v3/api/server/acme"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
EnableACME bool
|
|
||||||
EnableCORS bool
|
|
||||||
ACMEProvider acme.Provider
|
|
||||||
EnableTLS bool
|
|
||||||
ACMEHosts []string
|
|
||||||
TLSConfig *tls.Config
|
|
||||||
Resolver resolver.Resolver
|
|
||||||
Wrappers []Wrapper
|
|
||||||
}
|
|
||||||
|
|
||||||
type Wrapper func(h http.Handler) http.Handler
|
|
||||||
|
|
||||||
func WrapHandler(w ...Wrapper) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Wrappers = append(o.Wrappers, w...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func EnableCORS(b bool) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.EnableCORS = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func EnableACME(b bool) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.EnableACME = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ACMEHosts(hosts ...string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.ACMEHosts = hosts
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ACMEProvider(p acme.Provider) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.ACMEProvider = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func EnableTLS(b bool) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.EnableTLS = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TLSConfig(t *tls.Config) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.TLSConfig = t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Resolver(r resolver.Resolver) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Resolver = r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
// Package server provides an API gateway server which handles inbound requests
|
|
||||||
package server
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Server serves api requests
|
|
||||||
type Server interface {
|
|
||||||
Address() string
|
|
||||||
Init(opts ...Option) error
|
|
||||||
Handle(path string, handler http.Handler)
|
|
||||||
Start() error
|
|
||||||
Stop() error
|
|
||||||
}
|
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// source: api/service/proto/api.proto
|
|
||||||
|
|
||||||
package go_micro_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
grpc "google.golang.org/grpc"
|
|
||||||
codes "google.golang.org/grpc/codes"
|
|
||||||
status "google.golang.org/grpc/status"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
type Endpoint struct {
|
|
||||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
|
||||||
Host []string `protobuf:"bytes,2,rep,name=host,proto3" json:"host,omitempty"`
|
|
||||||
Path []string `protobuf:"bytes,3,rep,name=path,proto3" json:"path,omitempty"`
|
|
||||||
Method []string `protobuf:"bytes,4,rep,name=method,proto3" json:"method,omitempty"`
|
|
||||||
Stream bool `protobuf:"varint,5,opt,name=stream,proto3" json:"stream,omitempty"`
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) Reset() { *m = Endpoint{} }
|
|
||||||
func (m *Endpoint) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*Endpoint) ProtoMessage() {}
|
|
||||||
func (*Endpoint) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_c4a48b6b680b5c31, []int{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_Endpoint.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_Endpoint.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_Endpoint.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_Endpoint.Size(m)
|
|
||||||
}
|
|
||||||
func (m *Endpoint) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_Endpoint.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_Endpoint proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func (m *Endpoint) GetName() string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Name
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetHost() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Host
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetPath() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Path
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetMethod() []string {
|
|
||||||
if m != nil {
|
|
||||||
return m.Method
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Endpoint) GetStream() bool {
|
|
||||||
if m != nil {
|
|
||||||
return m.Stream
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type EmptyResponse struct {
|
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
|
||||||
XXX_unrecognized []byte `json:"-"`
|
|
||||||
XXX_sizecache int32 `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *EmptyResponse) Reset() { *m = EmptyResponse{} }
|
|
||||||
func (m *EmptyResponse) String() string { return proto.CompactTextString(m) }
|
|
||||||
func (*EmptyResponse) ProtoMessage() {}
|
|
||||||
func (*EmptyResponse) Descriptor() ([]byte, []int) {
|
|
||||||
return fileDescriptor_c4a48b6b680b5c31, []int{1}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *EmptyResponse) XXX_Unmarshal(b []byte) error {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Unmarshal(m, b)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Marshal(b, m, deterministic)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Merge(src proto.Message) {
|
|
||||||
xxx_messageInfo_EmptyResponse.Merge(m, src)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_Size() int {
|
|
||||||
return xxx_messageInfo_EmptyResponse.Size(m)
|
|
||||||
}
|
|
||||||
func (m *EmptyResponse) XXX_DiscardUnknown() {
|
|
||||||
xxx_messageInfo_EmptyResponse.DiscardUnknown(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
var xxx_messageInfo_EmptyResponse proto.InternalMessageInfo
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
proto.RegisterType((*Endpoint)(nil), "go.micro.api.Endpoint")
|
|
||||||
proto.RegisterType((*EmptyResponse)(nil), "go.micro.api.EmptyResponse")
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() { proto.RegisterFile("api/service/proto/api.proto", fileDescriptor_c4a48b6b680b5c31) }
|
|
||||||
|
|
||||||
var fileDescriptor_c4a48b6b680b5c31 = []byte{
|
|
||||||
// 212 bytes of a gzipped FileDescriptorProto
|
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0xd0, 0xc1, 0x4a, 0x03, 0x31,
|
|
||||||
0x10, 0x80, 0x61, 0xd7, 0xad, 0x65, 0x1d, 0x14, 0x21, 0x87, 0x12, 0xec, 0x65, 0xd9, 0x53, 0x4f,
|
|
||||||
0x59, 0xd0, 0x27, 0x28, 0xda, 0x17, 0xd8, 0x37, 0x88, 0xed, 0xd0, 0x9d, 0x43, 0x32, 0x43, 0x32,
|
|
||||||
0x14, 0x7c, 0x08, 0xdf, 0x59, 0x12, 0x2b, 0x2c, 0x5e, 0xbd, 0xfd, 0xf3, 0x1d, 0x86, 0x61, 0x60,
|
|
||||||
0xeb, 0x85, 0xc6, 0x8c, 0xe9, 0x42, 0x47, 0x1c, 0x25, 0xb1, 0xf2, 0xe8, 0x85, 0x5c, 0x2d, 0xf3,
|
|
||||||
0x70, 0x66, 0x17, 0xe8, 0x98, 0xd8, 0x79, 0xa1, 0xe1, 0x02, 0xdd, 0x21, 0x9e, 0x84, 0x29, 0xaa,
|
|
||||||
0x31, 0xb0, 0x8a, 0x3e, 0xa0, 0x6d, 0xfa, 0x66, 0x77, 0x3f, 0xd5, 0x2e, 0x36, 0x73, 0x56, 0x7b,
|
|
||||||
0xdb, 0xb7, 0xc5, 0x4a, 0x17, 0x13, 0xaf, 0xb3, 0x6d, 0x7f, 0xac, 0xb4, 0xd9, 0xc0, 0x3a, 0xa0,
|
|
||||||
0xce, 0x7c, 0xb2, 0xab, 0xaa, 0xd7, 0xa9, 0x78, 0xd6, 0x84, 0x3e, 0xd8, 0xbb, 0xbe, 0xd9, 0x75,
|
|
||||||
0xd3, 0x75, 0x1a, 0x9e, 0xe0, 0xf1, 0x10, 0x44, 0x3f, 0x27, 0xcc, 0xc2, 0x31, 0xe3, 0xcb, 0x57,
|
|
||||||
0x03, 0xed, 0x5e, 0xc8, 0xec, 0xa1, 0x9b, 0xf0, 0x4c, 0x59, 0x31, 0x99, 0x8d, 0x5b, 0xde, 0xea,
|
|
||||||
0x7e, 0x0f, 0x7d, 0xde, 0xfe, 0xf1, 0xe5, 0xa2, 0xe1, 0xc6, 0xbc, 0x01, 0xbc, 0x63, 0xfa, 0xdf,
|
|
||||||
0x92, 0x8f, 0x75, 0xfd, 0xd6, 0xeb, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0x46, 0x62, 0x67, 0x30,
|
|
||||||
0x4c, 0x01, 0x00, 0x00,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ context.Context
|
|
||||||
var _ grpc.ClientConn
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the grpc package it is being compiled against.
|
|
||||||
const _ = grpc.SupportPackageIsVersion4
|
|
||||||
|
|
||||||
// ApiClient is the client API for Api service.
|
|
||||||
//
|
|
||||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
|
|
||||||
type ApiClient interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error)
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiClient struct {
|
|
||||||
cc *grpc.ClientConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewApiClient(cc *grpc.ClientConn) ApiClient {
|
|
||||||
return &apiClient{cc}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiClient) Register(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error) {
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.api.Api/Register", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiClient) Deregister(ctx context.Context, in *Endpoint, opts ...grpc.CallOption) (*EmptyResponse, error) {
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.cc.Invoke(ctx, "/go.micro.api.Api/Deregister", in, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApiServer is the server API for Api service.
|
|
||||||
type ApiServer interface {
|
|
||||||
Register(context.Context, *Endpoint) (*EmptyResponse, error)
|
|
||||||
Deregister(context.Context, *Endpoint) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnimplementedApiServer can be embedded to have forward compatible implementations.
|
|
||||||
type UnimplementedApiServer struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*UnimplementedApiServer) Register(ctx context.Context, req *Endpoint) (*EmptyResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Register not implemented")
|
|
||||||
}
|
|
||||||
func (*UnimplementedApiServer) Deregister(ctx context.Context, req *Endpoint) (*EmptyResponse, error) {
|
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Deregister not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterApiServer(s *grpc.Server, srv ApiServer) {
|
|
||||||
s.RegisterService(&_Api_serviceDesc, srv)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Api_Register_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(Endpoint)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(ApiServer).Register(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.api.Api/Register",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(ApiServer).Register(ctx, req.(*Endpoint))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _Api_Deregister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
||||||
in := new(Endpoint)
|
|
||||||
if err := dec(in); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if interceptor == nil {
|
|
||||||
return srv.(ApiServer).Deregister(ctx, in)
|
|
||||||
}
|
|
||||||
info := &grpc.UnaryServerInfo{
|
|
||||||
Server: srv,
|
|
||||||
FullMethod: "/go.micro.api.Api/Deregister",
|
|
||||||
}
|
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
||||||
return srv.(ApiServer).Deregister(ctx, req.(*Endpoint))
|
|
||||||
}
|
|
||||||
return interceptor(ctx, in, info, handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
var _Api_serviceDesc = grpc.ServiceDesc{
|
|
||||||
ServiceName: "go.micro.api.Api",
|
|
||||||
HandlerType: (*ApiServer)(nil),
|
|
||||||
Methods: []grpc.MethodDesc{
|
|
||||||
{
|
|
||||||
MethodName: "Register",
|
|
||||||
Handler: _Api_Register_Handler,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
MethodName: "Deregister",
|
|
||||||
Handler: _Api_Deregister_Handler,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Streams: []grpc.StreamDesc{},
|
|
||||||
Metadata: "api/service/proto/api.proto",
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
|
||||||
// source: api/service/proto/api.proto
|
|
||||||
|
|
||||||
package go_micro_api
|
|
||||||
|
|
||||||
import (
|
|
||||||
fmt "fmt"
|
|
||||||
proto "github.com/golang/protobuf/proto"
|
|
||||||
math "math"
|
|
||||||
)
|
|
||||||
|
|
||||||
import (
|
|
||||||
context "context"
|
|
||||||
api "github.com/micro/go-micro/v3/api"
|
|
||||||
client "github.com/micro/go-micro/v3/client"
|
|
||||||
server "github.com/micro/go-micro/v3/server"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ = proto.Marshal
|
|
||||||
var _ = fmt.Errorf
|
|
||||||
var _ = math.Inf
|
|
||||||
|
|
||||||
// This is a compile-time assertion to ensure that this generated file
|
|
||||||
// is compatible with the proto package it is being compiled against.
|
|
||||||
// A compilation error at this line likely means your copy of the
|
|
||||||
// proto package needs to be updated.
|
|
||||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
|
||||||
|
|
||||||
// Reference imports to suppress errors if they are not otherwise used.
|
|
||||||
var _ api.Endpoint
|
|
||||||
var _ context.Context
|
|
||||||
var _ client.Option
|
|
||||||
var _ server.Option
|
|
||||||
|
|
||||||
// Api Endpoints for Api service
|
|
||||||
|
|
||||||
func NewApiEndpoints() []*api.Endpoint {
|
|
||||||
return []*api.Endpoint{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client API for Api service
|
|
||||||
|
|
||||||
type ApiService interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error)
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiService struct {
|
|
||||||
c client.Client
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewApiService(name string, c client.Client) ApiService {
|
|
||||||
return &apiService{
|
|
||||||
c: c,
|
|
||||||
name: name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiService) Register(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Api.Register", in)
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *apiService) Deregister(ctx context.Context, in *Endpoint, opts ...client.CallOption) (*EmptyResponse, error) {
|
|
||||||
req := c.c.NewRequest(c.name, "Api.Deregister", in)
|
|
||||||
out := new(EmptyResponse)
|
|
||||||
err := c.c.Call(ctx, req, out, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server API for Api service
|
|
||||||
|
|
||||||
type ApiHandler interface {
|
|
||||||
Register(context.Context, *Endpoint, *EmptyResponse) error
|
|
||||||
Deregister(context.Context, *Endpoint, *EmptyResponse) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterApiHandler(s server.Server, hdlr ApiHandler, opts ...server.HandlerOption) error {
|
|
||||||
type api interface {
|
|
||||||
Register(ctx context.Context, in *Endpoint, out *EmptyResponse) error
|
|
||||||
Deregister(ctx context.Context, in *Endpoint, out *EmptyResponse) error
|
|
||||||
}
|
|
||||||
type Api struct {
|
|
||||||
api
|
|
||||||
}
|
|
||||||
h := &apiHandler{hdlr}
|
|
||||||
return s.Handle(s.NewHandler(&Api{h}, opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiHandler struct {
|
|
||||||
ApiHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *apiHandler) Register(ctx context.Context, in *Endpoint, out *EmptyResponse) error {
|
|
||||||
return h.ApiHandler.Register(ctx, in, out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *apiHandler) Deregister(ctx context.Context, in *Endpoint, out *EmptyResponse) error {
|
|
||||||
return h.ApiHandler.Deregister(ctx, in, out)
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package go.micro.api;
|
|
||||||
|
|
||||||
service Api {
|
|
||||||
rpc Register(Endpoint) returns (EmptyResponse) {};
|
|
||||||
rpc Deregister(Endpoint) returns (EmptyResponse) {};
|
|
||||||
}
|
|
||||||
|
|
||||||
message Endpoint {
|
|
||||||
string name = 1;
|
|
||||||
repeated string host = 2;
|
|
||||||
repeated string path = 3;
|
|
||||||
repeated string method = 4;
|
|
||||||
bool stream = 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EmptyResponse {}
|
|
||||||
133
auth/auth.go
133
auth/auth.go
@@ -1,133 +0,0 @@
|
|||||||
// Package auth provides authentication and authorization capability
|
|
||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// BearerScheme used for Authorization header
|
|
||||||
BearerScheme = "Bearer "
|
|
||||||
// ScopePublic is the scope applied to a rule to allow access to the public
|
|
||||||
ScopePublic = ""
|
|
||||||
// ScopeAccount is the scope applied to a rule to limit to users with any valid account
|
|
||||||
ScopeAccount = "*"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrInvalidToken is when the token provided is not valid
|
|
||||||
ErrInvalidToken = errors.New("invalid token provided")
|
|
||||||
// ErrForbidden is when a user does not have the necessary scope to access a resource
|
|
||||||
ErrForbidden = errors.New("resource forbidden")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Auth provides authentication and authorization
|
|
||||||
type Auth interface {
|
|
||||||
// Init the auth
|
|
||||||
Init(opts ...Option)
|
|
||||||
// Options set for auth
|
|
||||||
Options() Options
|
|
||||||
// Generate a new account
|
|
||||||
Generate(id string, opts ...GenerateOption) (*Account, error)
|
|
||||||
// Verify an account has access to a resource using the rules
|
|
||||||
Verify(acc *Account, res *Resource, opts ...VerifyOption) error
|
|
||||||
// Inspect a token
|
|
||||||
Inspect(token string) (*Account, error)
|
|
||||||
// Token generated using refresh token or credentials
|
|
||||||
Token(opts ...TokenOption) (*Token, error)
|
|
||||||
// Grant access to a resource
|
|
||||||
Grant(rule *Rule) error
|
|
||||||
// Revoke access to a resource
|
|
||||||
Revoke(rule *Rule) error
|
|
||||||
// Rules returns all the rules used to verify requests
|
|
||||||
Rules(...RulesOption) ([]*Rule, error)
|
|
||||||
// String returns the name of the implementation
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Account provided by an auth provider
|
|
||||||
type Account struct {
|
|
||||||
// ID of the account e.g. email
|
|
||||||
ID string `json:"id"`
|
|
||||||
// Type of the account, e.g. service
|
|
||||||
Type string `json:"type"`
|
|
||||||
// Issuer of the account
|
|
||||||
Issuer string `json:"issuer"`
|
|
||||||
// Any other associated metadata
|
|
||||||
Metadata map[string]string `json:"metadata"`
|
|
||||||
// Scopes the account has access to
|
|
||||||
Scopes []string `json:"scopes"`
|
|
||||||
// Secret for the account, e.g. the password
|
|
||||||
Secret string `json:"secret"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Token can be short or long lived
|
|
||||||
type Token struct {
|
|
||||||
// The token to be used for accessing resources
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
// RefreshToken to be used to generate a new token
|
|
||||||
RefreshToken string `json:"refresh_token"`
|
|
||||||
// Time of token creation
|
|
||||||
Created time.Time `json:"created"`
|
|
||||||
// Time of token expiry
|
|
||||||
Expiry time.Time `json:"expiry"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Expired returns a boolean indicating if the token needs to be refreshed
|
|
||||||
func (t *Token) Expired() bool {
|
|
||||||
return t.Expiry.Unix() < time.Now().Unix()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resource is an entity such as a user or
|
|
||||||
type Resource struct {
|
|
||||||
// Name of the resource, e.g. go.micro.service.notes
|
|
||||||
Name string `json:"name"`
|
|
||||||
// Type of resource, e.g. service
|
|
||||||
Type string `json:"type"`
|
|
||||||
// Endpoint resource e.g NotesService.Create
|
|
||||||
Endpoint string `json:"endpoint"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Access defines the type of access a rule grants
|
|
||||||
type Access int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// AccessGranted to a resource
|
|
||||||
AccessGranted Access = iota
|
|
||||||
// AccessDenied to a resource
|
|
||||||
AccessDenied
|
|
||||||
)
|
|
||||||
|
|
||||||
// Rule is used to verify access to a resource
|
|
||||||
type Rule struct {
|
|
||||||
// ID of the rule, e.g. "public"
|
|
||||||
ID string
|
|
||||||
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
|
|
||||||
// applies to any valid account
|
|
||||||
Scope string
|
|
||||||
// Resource the rule applies to
|
|
||||||
Resource *Resource
|
|
||||||
// Access determines if the rule grants or denies access to the resource
|
|
||||||
Access Access
|
|
||||||
// Priority the rule should take when verifying a request, the higher the value the sooner the
|
|
||||||
// rule will be applied
|
|
||||||
Priority int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type accountKey struct{}
|
|
||||||
|
|
||||||
// AccountFromContext gets the account from the context, which
|
|
||||||
// is set by the auth wrapper at the start of a call. If the account
|
|
||||||
// is not set, a nil account will be returned. The error is only returned
|
|
||||||
// when there was a problem retrieving an account
|
|
||||||
func AccountFromContext(ctx context.Context) (*Account, bool) {
|
|
||||||
acc, ok := ctx.Value(accountKey{}).(*Account)
|
|
||||||
return acc, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
// ContextWithAccount sets the account in the context
|
|
||||||
func ContextWithAccount(ctx context.Context, account *Account) context.Context {
|
|
||||||
return context.WithValue(ctx, accountKey{}, account)
|
|
||||||
}
|
|
||||||
151
auth/jwt/jwt.go
151
auth/jwt/jwt.go
@@ -1,151 +0,0 @@
|
|||||||
// Package jwt is a jwt implementation of the auth interface
|
|
||||||
package jwt
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/auth"
|
|
||||||
"github.com/micro/go-micro/v3/util/token"
|
|
||||||
"github.com/micro/go-micro/v3/util/token/jwt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewAuth returns a new instance of the Auth service
|
|
||||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
|
||||||
j := new(jwtAuth)
|
|
||||||
j.Init(opts...)
|
|
||||||
return j
|
|
||||||
}
|
|
||||||
|
|
||||||
type jwtAuth struct {
|
|
||||||
options auth.Options
|
|
||||||
token token.Provider
|
|
||||||
rules []*auth.Rule
|
|
||||||
|
|
||||||
sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) String() string {
|
|
||||||
return "jwt"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Init(opts ...auth.Option) {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&j.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
j.token = jwt.NewTokenProvider(
|
|
||||||
token.WithPrivateKey(j.options.PrivateKey),
|
|
||||||
token.WithPublicKey(j.options.PublicKey),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Options() auth.Options {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
return j.options
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) {
|
|
||||||
options := auth.NewGenerateOptions(opts...)
|
|
||||||
if len(options.Issuer) == 0 {
|
|
||||||
options.Issuer = j.Options().Issuer
|
|
||||||
}
|
|
||||||
|
|
||||||
account := &auth.Account{
|
|
||||||
ID: id,
|
|
||||||
Type: options.Type,
|
|
||||||
Scopes: options.Scopes,
|
|
||||||
Metadata: options.Metadata,
|
|
||||||
Issuer: options.Issuer,
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate a JWT secret which can be provided to the Token() method
|
|
||||||
// and exchanged for an access token
|
|
||||||
secret, err := j.token.Generate(account, token.WithExpiry(time.Hour*24*365))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
account.Secret = secret.Token
|
|
||||||
|
|
||||||
// return the account
|
|
||||||
return account, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Grant(rule *auth.Rule) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
j.rules = append(j.rules, rule)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Revoke(rule *auth.Rule) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
rules := []*auth.Rule{}
|
|
||||||
for _, r := range j.rules {
|
|
||||||
if r.ID != rule.ID {
|
|
||||||
rules = append(rules, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
j.rules = rules
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
|
|
||||||
var options auth.VerifyOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return auth.VerifyAccess(j.rules, acc, res)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) {
|
|
||||||
j.Lock()
|
|
||||||
defer j.Unlock()
|
|
||||||
return j.rules, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Inspect(token string) (*auth.Account, error) {
|
|
||||||
return j.token.Inspect(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *jwtAuth) Token(opts ...auth.TokenOption) (*auth.Token, error) {
|
|
||||||
options := auth.NewTokenOptions(opts...)
|
|
||||||
|
|
||||||
secret := options.RefreshToken
|
|
||||||
if len(options.Secret) > 0 {
|
|
||||||
secret = options.Secret
|
|
||||||
}
|
|
||||||
|
|
||||||
account, err := j.token.Inspect(secret)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
access, err := j.token.Generate(account, token.WithExpiry(options.Expiry))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
refresh, err := j.token.Generate(account, token.WithExpiry(options.Expiry+time.Hour))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &auth.Token{
|
|
||||||
Created: access.Created,
|
|
||||||
Expiry: access.Expiry,
|
|
||||||
AccessToken: access.Token,
|
|
||||||
RefreshToken: refresh.Token,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package noop
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
|
||||||
var options auth.Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &noop{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type noop struct {
|
|
||||||
opts auth.Options
|
|
||||||
}
|
|
||||||
|
|
||||||
// String returns the name of the implementation
|
|
||||||
func (n *noop) String() string {
|
|
||||||
return "noop"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Init the auth
|
|
||||||
func (n *noop) Init(opts ...auth.Option) {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&n.opts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Options set for auth
|
|
||||||
func (n *noop) Options() auth.Options {
|
|
||||||
return n.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate a new account
|
|
||||||
func (n *noop) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) {
|
|
||||||
options := auth.NewGenerateOptions(opts...)
|
|
||||||
|
|
||||||
return &auth.Account{
|
|
||||||
ID: id,
|
|
||||||
Secret: options.Secret,
|
|
||||||
Metadata: options.Metadata,
|
|
||||||
Scopes: options.Scopes,
|
|
||||||
Issuer: n.Options().Issuer,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Grant access to a resource
|
|
||||||
func (n *noop) Grant(rule *auth.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Revoke access to a resource
|
|
||||||
func (n *noop) Revoke(rule *auth.Rule) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rules used to verify requests
|
|
||||||
func (n *noop) Rules(opts ...auth.RulesOption) ([]*auth.Rule, error) {
|
|
||||||
return []*auth.Rule{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify an account has access to a resource
|
|
||||||
func (n *noop) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inspect a token
|
|
||||||
func (n *noop) Inspect(token string) (*auth.Account, error) {
|
|
||||||
return &auth.Account{ID: uuid.New().String(), Issuer: n.Options().Issuer}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Token generation using an account id and secret
|
|
||||||
func (n *noop) Token(opts ...auth.TokenOption) (*auth.Token, error) {
|
|
||||||
return &auth.Token{}, nil
|
|
||||||
}
|
|
||||||
259
auth/options.go
259
auth/options.go
@@ -1,259 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/store"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewOptions(opts ...Option) Options {
|
|
||||||
var options Options
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
// Issuer of the service's account
|
|
||||||
Issuer string
|
|
||||||
// ID is the services auth ID
|
|
||||||
ID string
|
|
||||||
// Secret is used to authenticate the service
|
|
||||||
Secret string
|
|
||||||
// Token is the services token used to authenticate itself
|
|
||||||
Token *Token
|
|
||||||
// PublicKey for decoding JWTs
|
|
||||||
PublicKey string
|
|
||||||
// PrivateKey for encoding JWTs
|
|
||||||
PrivateKey string
|
|
||||||
// LoginURL is the relative url path where a user can login
|
|
||||||
LoginURL string
|
|
||||||
// Store to back auth
|
|
||||||
Store store.Store
|
|
||||||
// Addrs sets the addresses of auth
|
|
||||||
Addrs []string
|
|
||||||
// Context to store other options
|
|
||||||
Context context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option func(o *Options)
|
|
||||||
|
|
||||||
// Addrs is the auth addresses to use
|
|
||||||
func Addrs(addrs ...string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Addrs = addrs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issuer of the services account
|
|
||||||
func Issuer(i string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Issuer = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store to back auth
|
|
||||||
func Store(s store.Store) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Store = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublicKey is the JWT public key
|
|
||||||
func PublicKey(key string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.PublicKey = key
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrivateKey is the JWT private key
|
|
||||||
func PrivateKey(key string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.PrivateKey = key
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Credentials sets the auth credentials
|
|
||||||
func Credentials(id, secret string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.ID = id
|
|
||||||
o.Secret = secret
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClientToken sets the auth token to use when making requests
|
|
||||||
func ClientToken(token *Token) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.Token = token
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginURL sets the auth LoginURL
|
|
||||||
func LoginURL(url string) Option {
|
|
||||||
return func(o *Options) {
|
|
||||||
o.LoginURL = url
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type GenerateOptions struct {
|
|
||||||
// Metadata associated with the account
|
|
||||||
Metadata map[string]string
|
|
||||||
// Scopes the account has access too
|
|
||||||
Scopes []string
|
|
||||||
// Provider of the account, e.g. oauth
|
|
||||||
Provider string
|
|
||||||
// Type of the account, e.g. user
|
|
||||||
Type string
|
|
||||||
// Secret used to authenticate the account
|
|
||||||
Secret string
|
|
||||||
// Issuer of the account, e.g. micro
|
|
||||||
Issuer string
|
|
||||||
}
|
|
||||||
|
|
||||||
type GenerateOption func(o *GenerateOptions)
|
|
||||||
|
|
||||||
// WithSecret for the generated account
|
|
||||||
func WithSecret(s string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Secret = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithType for the generated account
|
|
||||||
func WithType(t string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Type = t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithMetadata for the generated account
|
|
||||||
func WithMetadata(md map[string]string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Metadata = md
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithProvider for the generated account
|
|
||||||
func WithProvider(p string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Provider = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithScopes for the generated account
|
|
||||||
func WithScopes(s ...string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Scopes = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithIssuer for the generated account
|
|
||||||
func WithIssuer(i string) GenerateOption {
|
|
||||||
return func(o *GenerateOptions) {
|
|
||||||
o.Issuer = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewGenerateOptions from a slice of options
|
|
||||||
func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
|
||||||
var options GenerateOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokenOptions struct {
|
|
||||||
// ID for the account
|
|
||||||
ID string
|
|
||||||
// Secret for the account
|
|
||||||
Secret string
|
|
||||||
// RefreshToken is used to refesh a token
|
|
||||||
RefreshToken string
|
|
||||||
// Expiry is the time the token should live for
|
|
||||||
Expiry time.Duration
|
|
||||||
// Issuer of the account
|
|
||||||
Issuer string
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokenOption func(o *TokenOptions)
|
|
||||||
|
|
||||||
// WithExpiry for the token
|
|
||||||
func WithExpiry(ex time.Duration) TokenOption {
|
|
||||||
return func(o *TokenOptions) {
|
|
||||||
o.Expiry = ex
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithCredentials(id, secret string) TokenOption {
|
|
||||||
return func(o *TokenOptions) {
|
|
||||||
o.ID = id
|
|
||||||
o.Secret = secret
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithToken(rt string) TokenOption {
|
|
||||||
return func(o *TokenOptions) {
|
|
||||||
o.RefreshToken = rt
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithTokenIssuer(iss string) TokenOption {
|
|
||||||
return func(o *TokenOptions) {
|
|
||||||
o.Issuer = iss
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTokenOptions from a slice of options
|
|
||||||
func NewTokenOptions(opts ...TokenOption) TokenOptions {
|
|
||||||
var options TokenOptions
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set defualt expiry of token
|
|
||||||
if options.Expiry == 0 {
|
|
||||||
options.Expiry = time.Minute
|
|
||||||
}
|
|
||||||
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
type VerifyOptions struct {
|
|
||||||
Context context.Context
|
|
||||||
Namespace string
|
|
||||||
}
|
|
||||||
|
|
||||||
type VerifyOption func(o *VerifyOptions)
|
|
||||||
|
|
||||||
func VerifyContext(ctx context.Context) VerifyOption {
|
|
||||||
return func(o *VerifyOptions) {
|
|
||||||
o.Context = ctx
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func VerifyNamespace(ns string) VerifyOption {
|
|
||||||
return func(o *VerifyOptions) {
|
|
||||||
o.Namespace = ns
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type RulesOptions struct {
|
|
||||||
Context context.Context
|
|
||||||
Namespace string
|
|
||||||
}
|
|
||||||
|
|
||||||
type RulesOption func(o *RulesOptions)
|
|
||||||
|
|
||||||
func RulesContext(ctx context.Context) RulesOption {
|
|
||||||
return func(o *RulesOptions) {
|
|
||||||
o.Context = ctx
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func RulesNamespace(ns string) RulesOption {
|
|
||||||
return func(o *RulesOptions) {
|
|
||||||
o.Namespace = ns
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// VerifyAccess an account has access to a resource using the rules provided. If the account does not have
|
|
||||||
// access an error will be returned. If there are no rules provided which match the resource, an error
|
|
||||||
// will be returned
|
|
||||||
func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error {
|
|
||||||
// the rule is only to be applied if the type matches the resource or is catch-all (*)
|
|
||||||
validTypes := []string{"*", res.Type}
|
|
||||||
|
|
||||||
// the rule is only to be applied if the name matches the resource or is catch-all (*)
|
|
||||||
validNames := []string{"*", res.Name}
|
|
||||||
|
|
||||||
// rules can have wildcard excludes on endpoints since this can also be a path for web services,
|
|
||||||
// e.g. /foo/* would include /foo/bar. We also want to check for wildcards and the exact endpoint
|
|
||||||
validEndpoints := []string{"*", res.Endpoint}
|
|
||||||
if comps := strings.Split(res.Endpoint, "/"); len(comps) > 1 {
|
|
||||||
for i := 1; i < len(comps)+1; i++ {
|
|
||||||
wildcard := fmt.Sprintf("%v/*", strings.Join(comps[0:i], "/"))
|
|
||||||
validEndpoints = append(validEndpoints, wildcard)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter the rules to the ones which match the criteria above
|
|
||||||
filteredRules := make([]*Rule, 0)
|
|
||||||
for _, rule := range rules {
|
|
||||||
if !include(validTypes, rule.Resource.Type) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !include(validNames, rule.Resource.Name) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !include(validEndpoints, rule.Resource.Endpoint) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
filteredRules = append(filteredRules, rule)
|
|
||||||
}
|
|
||||||
|
|
||||||
// sort the filtered rules by priority, highest to lowest
|
|
||||||
sort.SliceStable(filteredRules, func(i, j int) bool {
|
|
||||||
return filteredRules[i].Priority > filteredRules[j].Priority
|
|
||||||
})
|
|
||||||
|
|
||||||
// loop through the rules and check for a rule which applies to this account
|
|
||||||
for _, rule := range filteredRules {
|
|
||||||
// a blank scope indicates the rule applies to everyone, even nil accounts
|
|
||||||
if rule.Scope == ScopePublic && rule.Access == AccessDenied {
|
|
||||||
return ErrForbidden
|
|
||||||
} else if rule.Scope == ScopePublic && rule.Access == AccessGranted {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// all further checks require an account
|
|
||||||
if acc == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// this rule applies to any account
|
|
||||||
if rule.Scope == ScopeAccount && rule.Access == AccessDenied {
|
|
||||||
return ErrForbidden
|
|
||||||
} else if rule.Scope == ScopeAccount && rule.Access == AccessGranted {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// if the account has the necessary scope
|
|
||||||
if include(acc.Scopes, rule.Scope) && rule.Access == AccessDenied {
|
|
||||||
return ErrForbidden
|
|
||||||
} else if include(acc.Scopes, rule.Scope) && rule.Access == AccessGranted {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if no rules matched then return forbidden
|
|
||||||
return ErrForbidden
|
|
||||||
}
|
|
||||||
|
|
||||||
// include is a helper function which checks to see if the slice contains the value. includes is
|
|
||||||
// not case sensitive.
|
|
||||||
func include(slice []string, val string) bool {
|
|
||||||
for _, s := range slice {
|
|
||||||
if strings.ToLower(s) == strings.ToLower(val) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,288 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestVerify(t *testing.T) {
|
|
||||||
srvResource := &Resource{
|
|
||||||
Type: "service",
|
|
||||||
Name: "go.micro.service.foo",
|
|
||||||
Endpoint: "Foo.Bar",
|
|
||||||
}
|
|
||||||
|
|
||||||
webResource := &Resource{
|
|
||||||
Type: "service",
|
|
||||||
Name: "go.micro.web.foo",
|
|
||||||
Endpoint: "/foo/bar",
|
|
||||||
}
|
|
||||||
|
|
||||||
catchallResource := &Resource{
|
|
||||||
Type: "*",
|
|
||||||
Name: "*",
|
|
||||||
Endpoint: "*",
|
|
||||||
}
|
|
||||||
|
|
||||||
tt := []struct {
|
|
||||||
Name string
|
|
||||||
Rules []*Rule
|
|
||||||
Account *Account
|
|
||||||
Resource *Resource
|
|
||||||
Error error
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
Name: "NoRules",
|
|
||||||
Rules: []*Rule{},
|
|
||||||
Account: nil,
|
|
||||||
Resource: srvResource,
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallPublicAccount",
|
|
||||||
Account: &Account{},
|
|
||||||
Resource: srvResource,
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "",
|
|
||||||
Resource: catchallResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallPublicNoAccount",
|
|
||||||
Resource: srvResource,
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "",
|
|
||||||
Resource: catchallResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallPrivateAccount",
|
|
||||||
Account: &Account{},
|
|
||||||
Resource: srvResource,
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallPrivateNoAccount",
|
|
||||||
Resource: srvResource,
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallServiceRuleMatch",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: srvResource.Type,
|
|
||||||
Name: srvResource.Name,
|
|
||||||
Endpoint: "*",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallServiceRuleNoMatch",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: srvResource.Type,
|
|
||||||
Name: "wrongname",
|
|
||||||
Endpoint: "*",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "ExactRuleValidScope",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{
|
|
||||||
Scopes: []string{"neededscope"},
|
|
||||||
},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "neededscope",
|
|
||||||
Resource: srvResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "ExactRuleInvalidScope",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{
|
|
||||||
Scopes: []string{"neededscope"},
|
|
||||||
},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "invalidscope",
|
|
||||||
Resource: srvResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallDenyWithAccount",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessDenied,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "CatchallDenyWithNoAccount",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessDenied,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "RulePriorityGrantFirst",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessGranted,
|
|
||||||
Priority: 1,
|
|
||||||
},
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessDenied,
|
|
||||||
Priority: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "RulePriorityDenyFirst",
|
|
||||||
Resource: srvResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessGranted,
|
|
||||||
Priority: 0,
|
|
||||||
},
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: catchallResource,
|
|
||||||
Access: AccessDenied,
|
|
||||||
Priority: 1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "WebExactEndpointValid",
|
|
||||||
Resource: webResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: webResource,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "WebExactEndpointInalid",
|
|
||||||
Resource: webResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: webResource.Type,
|
|
||||||
Name: webResource.Name,
|
|
||||||
Endpoint: "invalidendpoint",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "WebWildcardEndpoint",
|
|
||||||
Resource: webResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: webResource.Type,
|
|
||||||
Name: webResource.Name,
|
|
||||||
Endpoint: "*",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "WebWildcardPathEndpointValid",
|
|
||||||
Resource: webResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: webResource.Type,
|
|
||||||
Name: webResource.Name,
|
|
||||||
Endpoint: "/foo/*",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "WebWildcardPathEndpointInvalid",
|
|
||||||
Resource: webResource,
|
|
||||||
Account: &Account{},
|
|
||||||
Rules: []*Rule{
|
|
||||||
&Rule{
|
|
||||||
Scope: "*",
|
|
||||||
Resource: &Resource{
|
|
||||||
Type: webResource.Type,
|
|
||||||
Name: webResource.Name,
|
|
||||||
Endpoint: "/bar/*",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Error: ErrForbidden,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range tt {
|
|
||||||
t.Run(tc.Name, func(t *testing.T) {
|
|
||||||
if err := VerifyAccess(tc.Rules, tc.Account, tc.Resource); err != tc.Error {
|
|
||||||
t.Errorf("Expected %v but got %v", tc.Error, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
123
broker/broker.go
123
broker/broker.go
@@ -1,31 +1,134 @@
|
|||||||
// Package broker is an interface used for asynchronous messaging
|
// Package broker is an interface used for asynchronous messaging
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.unistack.org/micro/v3/codec"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultBroker default memory broker
|
||||||
|
var DefaultBroker Broker = NewBroker()
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrNotConnected returns when broker used but not connected yet
|
||||||
|
ErrNotConnected = errors.New("broker not connected")
|
||||||
|
// ErrDisconnected returns when broker disconnected
|
||||||
|
ErrDisconnected = errors.New("broker disconnected")
|
||||||
|
// DefaultGracefulTimeout
|
||||||
|
DefaultGracefulTimeout = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
// Broker is an interface used for asynchronous messaging.
|
// Broker is an interface used for asynchronous messaging.
|
||||||
type Broker interface {
|
type Broker interface {
|
||||||
Init(...Option) error
|
// Name returns broker instance name
|
||||||
|
Name() string
|
||||||
|
// Init initilize broker
|
||||||
|
Init(opts ...Option) error
|
||||||
|
// Options returns broker options
|
||||||
Options() Options
|
Options() Options
|
||||||
|
// Address return configured address
|
||||||
Address() string
|
Address() string
|
||||||
Connect() error
|
// Connect connects to broker
|
||||||
Disconnect() error
|
Connect(ctx context.Context) error
|
||||||
Publish(topic string, m *Message, opts ...PublishOption) error
|
// Disconnect disconnect from broker
|
||||||
Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
|
Disconnect(ctx context.Context) error
|
||||||
|
// Publish message to broker topic
|
||||||
|
Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error
|
||||||
|
// Subscribe subscribes to topic message via handler
|
||||||
|
Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
|
||||||
|
// BatchPublish messages to broker with multiple topics
|
||||||
|
BatchPublish(ctx context.Context, msgs []*Message, opts ...PublishOption) error
|
||||||
|
// BatchSubscribe subscribes to topic messages via handler
|
||||||
|
BatchSubscribe(ctx context.Context, topic string, h BatchHandler, opts ...SubscribeOption) (Subscriber, error)
|
||||||
|
// String type of broker
|
||||||
String() string
|
String() string
|
||||||
|
// Live returns broker liveness
|
||||||
|
Live() bool
|
||||||
|
// Ready returns broker readiness
|
||||||
|
Ready() bool
|
||||||
|
// Health returns broker health
|
||||||
|
Health() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type (
|
||||||
|
FuncPublish func(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error
|
||||||
|
HookPublish func(next FuncPublish) FuncPublish
|
||||||
|
FuncBatchPublish func(ctx context.Context, msgs []*Message, opts ...PublishOption) error
|
||||||
|
HookBatchPublish func(next FuncBatchPublish) FuncBatchPublish
|
||||||
|
FuncSubscribe func(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
|
||||||
|
HookSubscribe func(next FuncSubscribe) FuncSubscribe
|
||||||
|
FuncBatchSubscribe func(ctx context.Context, topic string, h BatchHandler, opts ...SubscribeOption) (Subscriber, error)
|
||||||
|
HookBatchSubscribe func(next FuncBatchSubscribe) FuncBatchSubscribe
|
||||||
|
)
|
||||||
|
|
||||||
// Handler is used to process messages via a subscription of a topic.
|
// Handler is used to process messages via a subscription of a topic.
|
||||||
type Handler func(*Message) error
|
type Handler func(Event) error
|
||||||
|
|
||||||
type ErrorHandler func(*Message, error)
|
// Events contains multiple events
|
||||||
|
type Events []Event
|
||||||
|
|
||||||
|
// Ack try to ack all events and return
|
||||||
|
func (evs Events) Ack() error {
|
||||||
|
var err error
|
||||||
|
for _, ev := range evs {
|
||||||
|
if err = ev.Ack(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetError sets error on event
|
||||||
|
func (evs Events) SetError(err error) {
|
||||||
|
for _, ev := range evs {
|
||||||
|
ev.SetError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchHandler is used to process messages in batches via a subscription of a topic.
|
||||||
|
type BatchHandler func(Events) error
|
||||||
|
|
||||||
|
// Event is given to a subscription handler for processing
|
||||||
|
type Event interface {
|
||||||
|
// Context return context.Context for event
|
||||||
|
Context() context.Context
|
||||||
|
// Topic returns event topic
|
||||||
|
Topic() string
|
||||||
|
// Message returns broker message
|
||||||
|
Message() *Message
|
||||||
|
// Ack acknowledge message
|
||||||
|
Ack() error
|
||||||
|
// Error returns message error (like decoding errors or some other)
|
||||||
|
Error() error
|
||||||
|
// SetError set event processing error
|
||||||
|
SetError(err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message is used to transfer data
|
||||||
type Message struct {
|
type Message struct {
|
||||||
Header map[string]string
|
// Header contains message metadata
|
||||||
Body []byte
|
Header metadata.Metadata
|
||||||
|
// Body contains message body
|
||||||
|
Body codec.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessage create broker message with topic filled
|
||||||
|
func NewMessage(topic string) *Message {
|
||||||
|
m := &Message{Header: metadata.New(2)}
|
||||||
|
m.Header.Set(metadata.HeaderTopic, topic)
|
||||||
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscriber is a convenience return type for the Subscribe method
|
// Subscriber is a convenience return type for the Subscribe method
|
||||||
type Subscriber interface {
|
type Subscriber interface {
|
||||||
|
// Options returns subscriber options
|
||||||
Options() SubscribeOptions
|
Options() SubscribeOptions
|
||||||
|
// Topic returns topic for subscription
|
||||||
Topic() string
|
Topic() string
|
||||||
Unsubscribe() error
|
// Unsubscribe from topic
|
||||||
|
Unsubscribe(ctx context.Context) error
|
||||||
}
|
}
|
||||||
|
|||||||
63
broker/context.go
Normal file
63
broker/context.go
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
|
type brokerKey struct{}
|
||||||
|
|
||||||
|
// FromContext returns broker from passed context
|
||||||
|
func FromContext(ctx context.Context) (Broker, bool) {
|
||||||
|
if ctx == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
c, ok := ctx.Value(brokerKey{}).(Broker)
|
||||||
|
return c, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustContext returns broker from passed context
|
||||||
|
func MustContext(ctx context.Context) Broker {
|
||||||
|
b, ok := FromContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
panic("missing broker")
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewContext savess broker in context
|
||||||
|
func NewContext(ctx context.Context, s Broker) context.Context {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
return context.WithValue(ctx, brokerKey{}, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSubscribeOption returns a function to setup a context with given value
|
||||||
|
func SetSubscribeOption(k, v interface{}) SubscribeOption {
|
||||||
|
return func(o *SubscribeOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetOption returns a function to setup a context with given value
|
||||||
|
func SetOption(k, v interface{}) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPublishOption returns a function to setup a context with given value
|
||||||
|
func SetPublishOption(k, v interface{}) PublishOption {
|
||||||
|
return func(o *PublishOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
o.Context = context.WithValue(o.Context, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
72
broker/context_test.go
Normal file
72
broker/context_test.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFromContext(t *testing.T) {
|
||||||
|
ctx := context.WithValue(context.TODO(), brokerKey{}, NewBroker())
|
||||||
|
c, ok := FromContext(ctx)
|
||||||
|
if c == nil || !ok {
|
||||||
|
t.Fatal("FromContext not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFromNilContext(t *testing.T) {
|
||||||
|
// nolint: staticcheck
|
||||||
|
c, ok := FromContext(nil)
|
||||||
|
if ok || c != nil {
|
||||||
|
t.Fatal("FromContext not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewContext(t *testing.T) {
|
||||||
|
ctx := NewContext(context.TODO(), NewBroker())
|
||||||
|
c, ok := FromContext(ctx)
|
||||||
|
if c == nil || !ok {
|
||||||
|
t.Fatal("NewContext not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewNilContext(t *testing.T) {
|
||||||
|
// nolint: staticcheck
|
||||||
|
ctx := NewContext(nil, NewBroker())
|
||||||
|
c, ok := FromContext(ctx)
|
||||||
|
if c == nil || !ok {
|
||||||
|
t.Fatal("NewContext not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetSubscribeOption(t *testing.T) {
|
||||||
|
type key struct{}
|
||||||
|
o := SetSubscribeOption(key{}, "test")
|
||||||
|
opts := &SubscribeOptions{}
|
||||||
|
o(opts)
|
||||||
|
|
||||||
|
if v, ok := opts.Context.Value(key{}).(string); !ok || v == "" {
|
||||||
|
t.Fatal("SetSubscribeOption not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetPublishOption(t *testing.T) {
|
||||||
|
type key struct{}
|
||||||
|
o := SetPublishOption(key{}, "test")
|
||||||
|
opts := &PublishOptions{}
|
||||||
|
o(opts)
|
||||||
|
|
||||||
|
if v, ok := opts.Context.Value(key{}).(string); !ok || v == "" {
|
||||||
|
t.Fatal("SetPublishOption not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetOption(t *testing.T) {
|
||||||
|
type key struct{}
|
||||||
|
o := SetOption(key{}, "test")
|
||||||
|
opts := &Options{}
|
||||||
|
o(opts)
|
||||||
|
|
||||||
|
if v, ok := opts.Context.Value(key{}).(string); !ok || v == "" {
|
||||||
|
t.Fatal("SetOption not works")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,689 +0,0 @@
|
|||||||
// Package http provides a http based message broker
|
|
||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"math/rand"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/codec/json"
|
|
||||||
merr "github.com/micro/go-micro/v3/errors"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/cache"
|
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
|
||||||
maddr "github.com/micro/go-micro/v3/util/addr"
|
|
||||||
mnet "github.com/micro/go-micro/v3/util/net"
|
|
||||||
mls "github.com/micro/go-micro/v3/util/tls"
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTP Broker is a point to point async broker
|
|
||||||
type httpBroker struct {
|
|
||||||
id string
|
|
||||||
address string
|
|
||||||
opts broker.Options
|
|
||||||
|
|
||||||
mux *http.ServeMux
|
|
||||||
|
|
||||||
c *http.Client
|
|
||||||
r registry.Registry
|
|
||||||
|
|
||||||
sync.RWMutex
|
|
||||||
subscribers map[string][]*httpSubscriber
|
|
||||||
running bool
|
|
||||||
exit chan chan error
|
|
||||||
|
|
||||||
// offline message inbox
|
|
||||||
mtx sync.RWMutex
|
|
||||||
inbox map[string][][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
type httpSubscriber struct {
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
id string
|
|
||||||
topic string
|
|
||||||
fn broker.Handler
|
|
||||||
svc *registry.Service
|
|
||||||
hb *httpBroker
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
DefaultPath = "/"
|
|
||||||
DefaultAddress = "127.0.0.1:0"
|
|
||||||
serviceName = "micro.http.broker"
|
|
||||||
broadcastVersion = "ff.http.broadcast"
|
|
||||||
registerTTL = time.Minute
|
|
||||||
registerInterval = time.Second * 30
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
rand.Seed(time.Now().Unix())
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTransport(config *tls.Config) *http.Transport {
|
|
||||||
if config == nil {
|
|
||||||
config = &tls.Config{
|
|
||||||
InsecureSkipVerify: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dialTLS := func(network string, addr string) (net.Conn, error) {
|
|
||||||
return tls.Dial(network, addr, config)
|
|
||||||
}
|
|
||||||
|
|
||||||
t := &http.Transport{
|
|
||||||
Proxy: http.ProxyFromEnvironment,
|
|
||||||
Dial: (&net.Dialer{
|
|
||||||
Timeout: 30 * time.Second,
|
|
||||||
KeepAlive: 30 * time.Second,
|
|
||||||
}).Dial,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
DialTLS: dialTLS,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(&t, func(tr **http.Transport) {
|
|
||||||
(*tr).CloseIdleConnections()
|
|
||||||
})
|
|
||||||
|
|
||||||
// setup http2
|
|
||||||
http2.ConfigureTransport(t)
|
|
||||||
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
func newHttpBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
options := broker.Options{
|
|
||||||
Codec: json.Marshaler{},
|
|
||||||
Context: context.TODO(),
|
|
||||||
Registry: mdns.NewRegistry(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set address
|
|
||||||
addr := DefaultAddress
|
|
||||||
|
|
||||||
if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 {
|
|
||||||
addr = options.Addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
h := &httpBroker{
|
|
||||||
id: uuid.New().String(),
|
|
||||||
address: addr,
|
|
||||||
opts: options,
|
|
||||||
r: options.Registry,
|
|
||||||
c: &http.Client{Transport: newTransport(options.TLSConfig)},
|
|
||||||
subscribers: make(map[string][]*httpSubscriber),
|
|
||||||
exit: make(chan chan error),
|
|
||||||
mux: http.NewServeMux(),
|
|
||||||
inbox: make(map[string][][]byte),
|
|
||||||
}
|
|
||||||
|
|
||||||
// specify the message handler
|
|
||||||
h.mux.Handle(DefaultPath, h)
|
|
||||||
|
|
||||||
// get optional handlers
|
|
||||||
if h.opts.Context != nil {
|
|
||||||
handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler)
|
|
||||||
if ok {
|
|
||||||
for pattern, handler := range handlers {
|
|
||||||
h.mux.Handle(pattern, handler)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Options() broker.SubscribeOptions {
|
|
||||||
return h.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Topic() string {
|
|
||||||
return h.topic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpSubscriber) Unsubscribe() error {
|
|
||||||
return h.hb.unsubscribe(h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) saveMessage(topic string, msg []byte) {
|
|
||||||
h.mtx.Lock()
|
|
||||||
defer h.mtx.Unlock()
|
|
||||||
|
|
||||||
// get messages
|
|
||||||
c := h.inbox[topic]
|
|
||||||
|
|
||||||
// save message
|
|
||||||
c = append(c, msg)
|
|
||||||
|
|
||||||
// max length 64
|
|
||||||
if len(c) > 64 {
|
|
||||||
c = c[:64]
|
|
||||||
}
|
|
||||||
|
|
||||||
// save inbox
|
|
||||||
h.inbox[topic] = c
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) getMessage(topic string, num int) [][]byte {
|
|
||||||
h.mtx.Lock()
|
|
||||||
defer h.mtx.Unlock()
|
|
||||||
|
|
||||||
// get messages
|
|
||||||
c, ok := h.inbox[topic]
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// more message than requests
|
|
||||||
if len(c) >= num {
|
|
||||||
msg := c[:num]
|
|
||||||
h.inbox[topic] = c[num:]
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// reset inbox
|
|
||||||
h.inbox[topic] = nil
|
|
||||||
|
|
||||||
// return all messages
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) subscribe(s *httpSubscriber) error {
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
if err := h.r.Register(s.svc, registry.RegisterTTL(registerTTL)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
h.subscribers[s.topic] = append(h.subscribers[s.topic], s)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) unsubscribe(s *httpSubscriber) error {
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
//nolint:prealloc
|
|
||||||
var subscribers []*httpSubscriber
|
|
||||||
|
|
||||||
// look for subscriber
|
|
||||||
for _, sub := range h.subscribers[s.topic] {
|
|
||||||
// deregister and skip forward
|
|
||||||
if sub == s {
|
|
||||||
_ = h.r.Deregister(sub.svc)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// keep subscriber
|
|
||||||
subscribers = append(subscribers, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set subscribers
|
|
||||||
h.subscribers[s.topic] = subscribers
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) run(l net.Listener) {
|
|
||||||
t := time.NewTicker(registerInterval)
|
|
||||||
defer t.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
// heartbeat for each subscriber
|
|
||||||
case <-t.C:
|
|
||||||
h.RLock()
|
|
||||||
for _, subs := range h.subscribers {
|
|
||||||
for _, sub := range subs {
|
|
||||||
_ = h.r.Register(sub.svc, registry.RegisterTTL(registerTTL))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
// received exit signal
|
|
||||||
case ch := <-h.exit:
|
|
||||||
ch <- l.Close()
|
|
||||||
h.RLock()
|
|
||||||
for _, subs := range h.subscribers {
|
|
||||||
for _, sub := range subs {
|
|
||||||
_ = h.r.Deregister(sub.svc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
if req.Method != "POST" {
|
|
||||||
err := merr.BadRequest("go.micro.broker", "Method not allowed")
|
|
||||||
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer req.Body.Close()
|
|
||||||
|
|
||||||
req.ParseForm()
|
|
||||||
|
|
||||||
b, err := ioutil.ReadAll(req.Body)
|
|
||||||
if err != nil {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var msg *broker.Message
|
|
||||||
if err = h.opts.Codec.Unmarshal(b, &msg); err != nil {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
topic := msg.Header["Micro-Topic"]
|
|
||||||
|
|
||||||
if len(topic) == 0 {
|
|
||||||
errr := merr.InternalServerError("go.micro.broker", "Topic not found")
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte(errr.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
id := req.Form.Get("id")
|
|
||||||
|
|
||||||
//nolint:prealloc
|
|
||||||
var subs []broker.Handler
|
|
||||||
|
|
||||||
h.RLock()
|
|
||||||
for _, subscriber := range h.subscribers[topic] {
|
|
||||||
if id != subscriber.id {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
subs = append(subs, subscriber.fn)
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
// execute the handler
|
|
||||||
for _, fn := range subs {
|
|
||||||
fn(msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Address() string {
|
|
||||||
h.RLock()
|
|
||||||
defer h.RUnlock()
|
|
||||||
return h.address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Connect() error {
|
|
||||||
h.RLock()
|
|
||||||
if h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
var l net.Listener
|
|
||||||
var err error
|
|
||||||
|
|
||||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
|
||||||
config := h.opts.TLSConfig
|
|
||||||
|
|
||||||
fn := func(addr string) (net.Listener, error) {
|
|
||||||
if config == nil {
|
|
||||||
hosts := []string{addr}
|
|
||||||
|
|
||||||
// check if its a valid host:port
|
|
||||||
if host, _, err := net.SplitHostPort(addr); err == nil {
|
|
||||||
if len(host) == 0 {
|
|
||||||
hosts = maddr.IPs()
|
|
||||||
} else {
|
|
||||||
hosts = []string{host}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate a certificate
|
|
||||||
cert, err := mls.Certificate(hosts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
config = &tls.Config{Certificates: []tls.Certificate{cert}}
|
|
||||||
}
|
|
||||||
return tls.Listen("tcp", addr, config)
|
|
||||||
}
|
|
||||||
|
|
||||||
l, err = mnet.Listen(h.address, fn)
|
|
||||||
} else {
|
|
||||||
fn := func(addr string) (net.Listener, error) {
|
|
||||||
return net.Listen("tcp", addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
l, err = mnet.Listen(h.address, fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := h.address
|
|
||||||
h.address = l.Addr().String()
|
|
||||||
|
|
||||||
go http.Serve(l, h.mux)
|
|
||||||
go func() {
|
|
||||||
h.run(l)
|
|
||||||
h.Lock()
|
|
||||||
h.opts.Addrs = []string{addr}
|
|
||||||
h.address = addr
|
|
||||||
h.Unlock()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// get registry
|
|
||||||
reg := h.opts.Registry
|
|
||||||
if reg == nil {
|
|
||||||
reg = mdns.NewRegistry()
|
|
||||||
}
|
|
||||||
// set cache
|
|
||||||
h.r = cache.New(reg)
|
|
||||||
|
|
||||||
// set running
|
|
||||||
h.running = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Disconnect() error {
|
|
||||||
h.RLock()
|
|
||||||
if !h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
// stop cache
|
|
||||||
rc, ok := h.r.(cache.Cache)
|
|
||||||
if ok {
|
|
||||||
rc.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// exit and return err
|
|
||||||
ch := make(chan error)
|
|
||||||
h.exit <- ch
|
|
||||||
err := <-ch
|
|
||||||
|
|
||||||
// set not running
|
|
||||||
h.running = false
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Init(opts ...broker.Option) error {
|
|
||||||
h.RLock()
|
|
||||||
if h.running {
|
|
||||||
h.RUnlock()
|
|
||||||
return errors.New("cannot init while connected")
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
h.Lock()
|
|
||||||
defer h.Unlock()
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&h.opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(h.opts.Addrs) > 0 && len(h.opts.Addrs[0]) > 0 {
|
|
||||||
h.address = h.opts.Addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(h.id) == 0 {
|
|
||||||
h.id = "go.micro.http.broker-" + uuid.New().String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// get registry
|
|
||||||
reg := h.opts.Registry
|
|
||||||
if reg == nil {
|
|
||||||
reg = mdns.NewRegistry()
|
|
||||||
}
|
|
||||||
|
|
||||||
// get cache
|
|
||||||
if rc, ok := h.r.(cache.Cache); ok {
|
|
||||||
rc.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// set registry
|
|
||||||
h.r = cache.New(reg)
|
|
||||||
|
|
||||||
// reconfigure tls config
|
|
||||||
if c := h.opts.TLSConfig; c != nil {
|
|
||||||
h.c = &http.Client{
|
|
||||||
Transport: newTransport(c),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Options() broker.Options {
|
|
||||||
return h.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
|
||||||
// create the message first
|
|
||||||
m := &broker.Message{
|
|
||||||
Header: make(map[string]string),
|
|
||||||
Body: msg.Body,
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range msg.Header {
|
|
||||||
m.Header[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
m.Header["Micro-Topic"] = topic
|
|
||||||
|
|
||||||
// encode the message
|
|
||||||
b, err := h.opts.Codec.Marshal(m)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// save the message
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
|
|
||||||
// now attempt to get the service
|
|
||||||
h.RLock()
|
|
||||||
s, err := h.r.GetService(serviceName)
|
|
||||||
if err != nil {
|
|
||||||
h.RUnlock()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
|
||||||
|
|
||||||
pub := func(node *registry.Node, t string, b []byte) error {
|
|
||||||
scheme := "http"
|
|
||||||
|
|
||||||
// check if secure is added in metadata
|
|
||||||
if node.Metadata["secure"] == "true" {
|
|
||||||
scheme = "https"
|
|
||||||
}
|
|
||||||
|
|
||||||
vals := url.Values{}
|
|
||||||
vals.Add("id", node.Id)
|
|
||||||
|
|
||||||
uri := fmt.Sprintf("%s://%s%s?%s", scheme, node.Address, DefaultPath, vals.Encode())
|
|
||||||
r, err := h.c.Post(uri, "application/json", bytes.NewReader(b))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// discard response body
|
|
||||||
io.Copy(ioutil.Discard, r.Body)
|
|
||||||
r.Body.Close()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := func(s []*registry.Service, b []byte) {
|
|
||||||
for _, service := range s {
|
|
||||||
var nodes []*registry.Node
|
|
||||||
|
|
||||||
for _, node := range service.Nodes {
|
|
||||||
// only use nodes tagged with broker http
|
|
||||||
if node.Metadata["broker"] != "http" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// look for nodes for the topic
|
|
||||||
if node.Metadata["topic"] != topic {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes = append(nodes, node)
|
|
||||||
}
|
|
||||||
|
|
||||||
// only process if we have nodes
|
|
||||||
if len(nodes) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
switch service.Version {
|
|
||||||
// broadcast version means broadcast to all nodes
|
|
||||||
case broadcastVersion:
|
|
||||||
var success bool
|
|
||||||
|
|
||||||
// publish to all nodes
|
|
||||||
for _, node := range nodes {
|
|
||||||
// publish async
|
|
||||||
if err := pub(node, topic, b); err == nil {
|
|
||||||
success = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// save if it failed to publish at least once
|
|
||||||
if !success {
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// select node to publish to
|
|
||||||
node := nodes[rand.Int()%len(nodes)]
|
|
||||||
|
|
||||||
// publish async to one node
|
|
||||||
if err := pub(node, topic, b); err != nil {
|
|
||||||
// if failed save it
|
|
||||||
h.saveMessage(topic, b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// do the rest async
|
|
||||||
go func() {
|
|
||||||
// get a third of the backlog
|
|
||||||
messages := h.getMessage(topic, 8)
|
|
||||||
delay := (len(messages) > 1)
|
|
||||||
|
|
||||||
// publish all the messages
|
|
||||||
for _, msg := range messages {
|
|
||||||
// serialize here
|
|
||||||
srv(s, msg)
|
|
||||||
|
|
||||||
// sending a backlog of messages
|
|
||||||
if delay {
|
|
||||||
time.Sleep(time.Millisecond * 100)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
var err error
|
|
||||||
var host, port string
|
|
||||||
options := broker.NewSubscribeOptions(opts...)
|
|
||||||
|
|
||||||
// parse address for host, port
|
|
||||||
host, port, err = net.SplitHostPort(h.Address())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := maddr.Extract(host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var secure bool
|
|
||||||
|
|
||||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
|
||||||
secure = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// register service
|
|
||||||
node := ®istry.Node{
|
|
||||||
Id: topic + "-" + h.id,
|
|
||||||
Address: mnet.HostPort(addr, port),
|
|
||||||
Metadata: map[string]string{
|
|
||||||
"secure": fmt.Sprintf("%t", secure),
|
|
||||||
"broker": "http",
|
|
||||||
"topic": topic,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// check for queue group or broadcast queue
|
|
||||||
version := options.Queue
|
|
||||||
if len(version) == 0 {
|
|
||||||
version = broadcastVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
service := ®istry.Service{
|
|
||||||
Name: serviceName,
|
|
||||||
Version: version,
|
|
||||||
Nodes: []*registry.Node{node},
|
|
||||||
}
|
|
||||||
|
|
||||||
// generate subscriber
|
|
||||||
subscriber := &httpSubscriber{
|
|
||||||
opts: options,
|
|
||||||
hb: h,
|
|
||||||
id: node.Id,
|
|
||||||
topic: topic,
|
|
||||||
fn: handler,
|
|
||||||
svc: service,
|
|
||||||
}
|
|
||||||
|
|
||||||
// subscribe now
|
|
||||||
if err := h.subscribe(subscriber); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// return the subscriber
|
|
||||||
return subscriber, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *httpBroker) String() string {
|
|
||||||
return "http"
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBroker returns a new http broker
|
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
return newHttpBroker(opts...)
|
|
||||||
}
|
|
||||||
@@ -1,377 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/registry"
|
|
||||||
"github.com/micro/go-micro/v3/registry/memory"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// mock data
|
|
||||||
testData = map[string][]*registry.Service{
|
|
||||||
"foo": {
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.0",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.0-123",
|
|
||||||
Address: "localhost:9999",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.0-321",
|
|
||||||
Address: "localhost:9999",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.1",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.1-321",
|
|
||||||
Address: "localhost:6666",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "foo",
|
|
||||||
Version: "1.0.3",
|
|
||||||
Nodes: []*registry.Node{
|
|
||||||
{
|
|
||||||
Id: "foo-1.0.3-345",
|
|
||||||
Address: "localhost:8888",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func newTestRegistry() registry.Registry {
|
|
||||||
return memory.NewRegistry(memory.Services(testData))
|
|
||||||
}
|
|
||||||
|
|
||||||
func sub(be *testing.B, c int) {
|
|
||||||
be.StopTimer()
|
|
||||||
m := newTestRegistry()
|
|
||||||
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
topic := uuid.New().String()
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
be.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var subs []broker.Subscriber
|
|
||||||
done := make(chan bool, c)
|
|
||||||
|
|
||||||
for i := 0; i < c; i++ {
|
|
||||||
sub, err := b.Subscribe(topic, func(m *broker.Message) error {
|
|
||||||
done <- true
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}, broker.Queue("shared"))
|
|
||||||
if err != nil {
|
|
||||||
be.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
subs = append(subs, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < be.N; i++ {
|
|
||||||
be.StartTimer()
|
|
||||||
if err := b.Publish(topic, msg); err != nil {
|
|
||||||
be.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
<-done
|
|
||||||
be.StopTimer()
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
|
||||||
sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func pub(be *testing.B, c int) {
|
|
||||||
be.StopTimer()
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
topic := uuid.New().String()
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
be.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
done := make(chan bool, c*4)
|
|
||||||
|
|
||||||
sub, err := b.Subscribe(topic, func(m *broker.Message) error {
|
|
||||||
done <- true
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}, broker.Queue("shared"))
|
|
||||||
if err != nil {
|
|
||||||
be.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
ch := make(chan int, c*4)
|
|
||||||
be.StartTimer()
|
|
||||||
|
|
||||||
for i := 0; i < c; i++ {
|
|
||||||
go func() {
|
|
||||||
for range ch {
|
|
||||||
if err := b.Publish(topic, msg); err != nil {
|
|
||||||
be.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-done:
|
|
||||||
case <-time.After(time.Second):
|
|
||||||
}
|
|
||||||
wg.Done()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < be.N; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
ch <- i
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
be.StopTimer()
|
|
||||||
sub.Unsubscribe()
|
|
||||||
close(ch)
|
|
||||||
close(done)
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
be.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
done := make(chan bool)
|
|
||||||
|
|
||||||
sub, err := b.Subscribe("test", func(m *broker.Message) error {
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
close(done)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-done
|
|
||||||
sub.Unsubscribe()
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConcurrentSubBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var subs []broker.Subscriber
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
sub, err := b.Subscribe("test", func(m *broker.Message) error {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Add(1)
|
|
||||||
subs = append(subs, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
|
||||||
sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConcurrentPubBroker(t *testing.T) {
|
|
||||||
m := newTestRegistry()
|
|
||||||
b := NewBroker(broker.Registry(m))
|
|
||||||
|
|
||||||
if err := b.Init(); err != nil {
|
|
||||||
t.Fatalf("Unexpected init error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected connect error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := &broker.Message{
|
|
||||||
Header: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
Body: []byte(`{"message": "Hello World"}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
sub, err := b.Subscribe("test", func(m *broker.Message) error {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
if string(m.Body) != string(msg.Body) {
|
|
||||||
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Unexpected subscribe error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
|
|
||||||
if err := b.Publish("test", msg); err != nil {
|
|
||||||
t.Fatalf("Unexpected publish error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
sub.Unsubscribe()
|
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
|
||||||
t.Fatalf("Unexpected disconnect error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub1(b *testing.B) {
|
|
||||||
sub(b, 1)
|
|
||||||
}
|
|
||||||
func BenchmarkSub8(b *testing.B) {
|
|
||||||
sub(b, 8)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub32(b *testing.B) {
|
|
||||||
sub(b, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub64(b *testing.B) {
|
|
||||||
sub(b, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkSub128(b *testing.B) {
|
|
||||||
sub(b, 128)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub1(b *testing.B) {
|
|
||||||
pub(b, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub8(b *testing.B) {
|
|
||||||
pub(b, 8)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub32(b *testing.B) {
|
|
||||||
pub(b, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub64(b *testing.B) {
|
|
||||||
pub(b, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPub128(b *testing.B) {
|
|
||||||
pub(b, 128)
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handle registers the handler for the given pattern.
|
|
||||||
func Handle(pattern string, handler http.Handler) broker.Option {
|
|
||||||
return func(o *broker.Options) {
|
|
||||||
if o.Context == nil {
|
|
||||||
o.Context = context.Background()
|
|
||||||
}
|
|
||||||
handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler)
|
|
||||||
if !ok {
|
|
||||||
handlers = make(map[string]http.Handler)
|
|
||||||
}
|
|
||||||
handlers[pattern] = handler
|
|
||||||
o.Context = context.WithValue(o.Context, "http_handlers", handlers)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +1,46 @@
|
|||||||
// Package memory provides a memory broker
|
package broker
|
||||||
package memory
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"math/rand"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"github.com/micro/go-micro/v3/broker"
|
"go.unistack.org/micro/v3/logger"
|
||||||
maddr "github.com/micro/go-micro/v3/util/addr"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
mnet "github.com/micro/go-micro/v3/util/net"
|
"go.unistack.org/micro/v3/options"
|
||||||
|
maddr "go.unistack.org/micro/v3/util/addr"
|
||||||
|
"go.unistack.org/micro/v3/util/id"
|
||||||
|
mnet "go.unistack.org/micro/v3/util/net"
|
||||||
|
"go.unistack.org/micro/v3/util/rand"
|
||||||
)
|
)
|
||||||
|
|
||||||
type memoryBroker struct {
|
type memoryBroker struct {
|
||||||
opts broker.Options
|
funcPublish broker.FuncPublish
|
||||||
|
funcBatchPublish broker.FuncBatchPublish
|
||||||
addr string
|
funcSubscribe broker.FuncSubscribe
|
||||||
|
funcBatchSubscribe broker.FuncBatchSubscribe
|
||||||
|
subscribers map[string][]*memorySubscriber
|
||||||
|
addr string
|
||||||
|
opts broker.Options
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
connected bool
|
connected bool
|
||||||
Subscribers map[string][]*memorySubscriber
|
}
|
||||||
|
|
||||||
|
type memoryEvent struct {
|
||||||
|
err error
|
||||||
|
message interface{}
|
||||||
|
topic string
|
||||||
|
opts broker.Options
|
||||||
}
|
}
|
||||||
|
|
||||||
type memorySubscriber struct {
|
type memorySubscriber struct {
|
||||||
id string
|
ctx context.Context
|
||||||
topic string
|
exit chan bool
|
||||||
exit chan bool
|
handler broker.Handler
|
||||||
handler broker.Handler
|
batchhandler broker.BatchHandler
|
||||||
opts broker.SubscribeOptions
|
id string
|
||||||
|
topic string
|
||||||
|
opts broker.SubscribeOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memoryBroker) Options() broker.Options {
|
func (m *memoryBroker) Options() broker.Options {
|
||||||
@@ -39,7 +51,13 @@ func (m *memoryBroker) Address() string {
|
|||||||
return m.addr
|
return m.addr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memoryBroker) Connect() error {
|
func (m *memoryBroker) Connect(ctx context.Context) error {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
m.Lock()
|
m.Lock()
|
||||||
defer m.Unlock()
|
defer m.Unlock()
|
||||||
|
|
||||||
@@ -52,7 +70,8 @@ func (m *memoryBroker) Connect() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
i := rand.Intn(20000)
|
var rng rand.Rand
|
||||||
|
i := rng.Intn(20000)
|
||||||
// set addr with port
|
// set addr with port
|
||||||
addr = mnet.HostPort(addr, 10000+i)
|
addr = mnet.HostPort(addr, 10000+i)
|
||||||
|
|
||||||
@@ -62,7 +81,13 @@ func (m *memoryBroker) Connect() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memoryBroker) Disconnect() error {
|
func (m *memoryBroker) Disconnect(ctx context.Context) error {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
m.Lock()
|
m.Lock()
|
||||||
defer m.Unlock()
|
defer m.Unlock()
|
||||||
|
|
||||||
@@ -71,7 +96,6 @@ func (m *memoryBroker) Disconnect() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m.connected = false
|
m.connected = false
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,70 +103,228 @@ func (m *memoryBroker) Init(opts ...broker.Option) error {
|
|||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&m.opts)
|
o(&m.opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
m.funcPublish = m.fnPublish
|
||||||
|
m.funcBatchPublish = m.fnBatchPublish
|
||||||
|
m.funcSubscribe = m.fnSubscribe
|
||||||
|
m.funcBatchSubscribe = m.fnBatchSubscribe
|
||||||
|
|
||||||
|
m.opts.Hooks.EachPrev(func(hook options.Hook) {
|
||||||
|
switch h := hook.(type) {
|
||||||
|
case broker.HookPublish:
|
||||||
|
m.funcPublish = h(m.funcPublish)
|
||||||
|
case broker.HookBatchPublish:
|
||||||
|
m.funcBatchPublish = h(m.funcBatchPublish)
|
||||||
|
case broker.HookSubscribe:
|
||||||
|
m.funcSubscribe = h(m.funcSubscribe)
|
||||||
|
case broker.HookBatchSubscribe:
|
||||||
|
m.funcBatchSubscribe = h(m.funcBatchSubscribe)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memoryBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
func (m *memoryBroker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
||||||
|
return m.funcPublish(ctx, topic, msg, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) fnPublish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
||||||
|
msg.Header.Set(metadata.HeaderTopic, topic)
|
||||||
|
return m.publish(ctx, []*broker.Message{msg}, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||||
|
return m.funcBatchPublish(ctx, msgs, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) fnBatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||||
|
return m.publish(ctx, msgs, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||||
m.RLock()
|
m.RLock()
|
||||||
if !m.connected {
|
if !m.connected {
|
||||||
m.RUnlock()
|
m.RUnlock()
|
||||||
return errors.New("not connected")
|
return broker.ErrNotConnected
|
||||||
}
|
}
|
||||||
|
|
||||||
subs, ok := m.Subscribers[topic]
|
|
||||||
m.RUnlock()
|
m.RUnlock()
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sub := range subs {
|
var err error
|
||||||
if err := sub.handler(msg); err != nil {
|
|
||||||
if eh := sub.opts.ErrorHandler; eh != nil {
|
select {
|
||||||
eh(msg, err)
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
default:
|
||||||
|
options := broker.NewPublishOptions(opts...)
|
||||||
|
|
||||||
|
msgTopicMap := make(map[string]broker.Events)
|
||||||
|
for _, v := range msgs {
|
||||||
|
p := &memoryEvent{opts: m.opts}
|
||||||
|
|
||||||
|
if m.opts.Codec == nil || options.BodyOnly {
|
||||||
|
p.topic, _ = v.Header.Get(metadata.HeaderTopic)
|
||||||
|
p.message = v.Body
|
||||||
|
} else {
|
||||||
|
p.topic, _ = v.Header.Get(metadata.HeaderTopic)
|
||||||
|
p.message, err = m.opts.Codec.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
msgTopicMap[p.topic] = append(msgTopicMap[p.topic], p)
|
||||||
|
}
|
||||||
|
|
||||||
|
beh := m.opts.BatchErrorHandler
|
||||||
|
eh := m.opts.ErrorHandler
|
||||||
|
|
||||||
|
for t, ms := range msgTopicMap {
|
||||||
|
m.RLock()
|
||||||
|
subs, ok := m.subscribers[t]
|
||||||
|
m.RUnlock()
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, sub := range subs {
|
||||||
|
if sub.opts.BatchErrorHandler != nil {
|
||||||
|
beh = sub.opts.BatchErrorHandler
|
||||||
|
}
|
||||||
|
if sub.opts.ErrorHandler != nil {
|
||||||
|
eh = sub.opts.ErrorHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
// batch processing
|
||||||
|
case sub.batchhandler != nil:
|
||||||
|
if err = sub.batchhandler(ms); err != nil {
|
||||||
|
ms.SetError(err)
|
||||||
|
if beh != nil {
|
||||||
|
_ = beh(ms)
|
||||||
|
} else if m.opts.Logger.V(logger.ErrorLevel) {
|
||||||
|
m.opts.Logger.Error(m.opts.Context, err.Error())
|
||||||
|
}
|
||||||
|
} else if sub.opts.AutoAck {
|
||||||
|
if err = ms.Ack(); err != nil {
|
||||||
|
m.opts.Logger.Error(m.opts.Context, "broker ack error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// single processing
|
||||||
|
case sub.handler != nil:
|
||||||
|
for _, p := range ms {
|
||||||
|
if err = sub.handler(p); err != nil {
|
||||||
|
p.SetError(err)
|
||||||
|
if eh != nil {
|
||||||
|
_ = eh(p)
|
||||||
|
} else if m.opts.Logger.V(logger.ErrorLevel) {
|
||||||
|
m.opts.Logger.Error(m.opts.Context, "broker handler error", err)
|
||||||
|
}
|
||||||
|
} else if sub.opts.AutoAck {
|
||||||
|
if err = p.Ack(); err != nil {
|
||||||
|
m.opts.Logger.Error(m.opts.Context, "broker ack error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memoryBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
func (m *memoryBroker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
|
return m.funcBatchSubscribe(ctx, topic, handler, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) fnBatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
m.RLock()
|
m.RLock()
|
||||||
if !m.connected {
|
if !m.connected {
|
||||||
m.RUnlock()
|
m.RUnlock()
|
||||||
return nil, errors.New("not connected")
|
return nil, broker.ErrNotConnected
|
||||||
}
|
}
|
||||||
m.RUnlock()
|
m.RUnlock()
|
||||||
|
|
||||||
var options broker.SubscribeOptions
|
sid, err := id.New()
|
||||||
for _, o := range opts {
|
if err != nil {
|
||||||
o(&options)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
options := broker.NewSubscribeOptions(opts...)
|
||||||
|
|
||||||
sub := &memorySubscriber{
|
sub := &memorySubscriber{
|
||||||
exit: make(chan bool, 1),
|
exit: make(chan bool, 1),
|
||||||
id: uuid.New().String(),
|
id: sid,
|
||||||
topic: topic,
|
topic: topic,
|
||||||
handler: handler,
|
batchhandler: handler,
|
||||||
opts: options,
|
opts: options,
|
||||||
|
ctx: ctx,
|
||||||
}
|
}
|
||||||
|
|
||||||
m.Lock()
|
m.Lock()
|
||||||
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
|
m.subscribers[topic] = append(m.subscribers[topic], sub)
|
||||||
m.Unlock()
|
m.Unlock()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
<-sub.exit
|
<-sub.exit
|
||||||
m.Lock()
|
m.Lock()
|
||||||
var newSubscribers []*memorySubscriber
|
newSubscribers := make([]*memorySubscriber, 0, len(m.subscribers)-1)
|
||||||
for _, sb := range m.Subscribers[topic] {
|
for _, sb := range m.subscribers[topic] {
|
||||||
if sb.id == sub.id {
|
if sb.id == sub.id {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
newSubscribers = append(newSubscribers, sb)
|
newSubscribers = append(newSubscribers, sb)
|
||||||
}
|
}
|
||||||
m.Subscribers[topic] = newSubscribers
|
m.subscribers[topic] = newSubscribers
|
||||||
|
m.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
return sub, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
|
return m.funcSubscribe(ctx, topic, handler, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) fnSubscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
|
m.RLock()
|
||||||
|
if !m.connected {
|
||||||
|
m.RUnlock()
|
||||||
|
return nil, broker.ErrNotConnected
|
||||||
|
}
|
||||||
|
m.RUnlock()
|
||||||
|
|
||||||
|
sid, err := id.New()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
options := broker.NewSubscribeOptions(opts...)
|
||||||
|
|
||||||
|
sub := &memorySubscriber{
|
||||||
|
exit: make(chan bool, 1),
|
||||||
|
id: sid,
|
||||||
|
topic: topic,
|
||||||
|
handler: handler,
|
||||||
|
opts: options,
|
||||||
|
ctx: ctx,
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Lock()
|
||||||
|
m.subscribers[topic] = append(m.subscribers[topic], sub)
|
||||||
|
m.Unlock()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-sub.exit
|
||||||
|
m.Lock()
|
||||||
|
newSubscribers := make([]*memorySubscriber, 0, len(m.subscribers)-1)
|
||||||
|
for _, sb := range m.subscribers[topic] {
|
||||||
|
if sb.id == sub.id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newSubscribers = append(newSubscribers, sb)
|
||||||
|
}
|
||||||
|
m.subscribers[topic] = newSubscribers
|
||||||
m.Unlock()
|
m.Unlock()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@@ -153,6 +335,60 @@ func (m *memoryBroker) String() string {
|
|||||||
return "memory"
|
return "memory"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) Name() string {
|
||||||
|
return m.opts.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) Live() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) Ready() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryBroker) Health() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) Topic() string {
|
||||||
|
return m.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) Message() *broker.Message {
|
||||||
|
switch v := m.message.(type) {
|
||||||
|
case *broker.Message:
|
||||||
|
return v
|
||||||
|
case []byte:
|
||||||
|
msg := &broker.Message{}
|
||||||
|
if err := m.opts.Codec.Unmarshal(v, msg); err != nil {
|
||||||
|
if m.opts.Logger.V(logger.ErrorLevel) {
|
||||||
|
m.opts.Logger.Error(m.opts.Context, "[memory]: failed to unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) Ack() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) Error() error {
|
||||||
|
return m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) SetError(err error) {
|
||||||
|
m.err = err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memoryEvent) Context() context.Context {
|
||||||
|
return m.opts.Context
|
||||||
|
}
|
||||||
|
|
||||||
func (m *memorySubscriber) Options() broker.SubscribeOptions {
|
func (m *memorySubscriber) Options() broker.SubscribeOptions {
|
||||||
return m.opts
|
return m.opts
|
||||||
}
|
}
|
||||||
@@ -161,23 +397,15 @@ func (m *memorySubscriber) Topic() string {
|
|||||||
return m.topic
|
return m.topic
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memorySubscriber) Unsubscribe() error {
|
func (m *memorySubscriber) Unsubscribe(ctx context.Context) error {
|
||||||
m.exit <- true
|
m.exit <- true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewBroker return new memory broker
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
func NewBroker(opts ...broker.Option) broker.Broker {
|
||||||
options := broker.Options{
|
|
||||||
Context: context.Background(),
|
|
||||||
}
|
|
||||||
|
|
||||||
rand.Seed(time.Now().UnixNano())
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &memoryBroker{
|
return &memoryBroker{
|
||||||
opts: options,
|
opts: broker.NewOptions(opts...),
|
||||||
Subscribers: make(map[string][]*memorySubscriber),
|
subscribers: make(map[string][]*memorySubscriber),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +1,114 @@
|
|||||||
package memory
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMemoryBroker(t *testing.T) {
|
func TestMemoryBatchBroker(t *testing.T) {
|
||||||
b := NewBroker()
|
b := NewBroker()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
if err := b.Connect(); err != nil {
|
if err := b.Init(); err != nil {
|
||||||
|
t.Fatalf("Unexpected init error %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := b.Connect(ctx); err != nil {
|
||||||
t.Fatalf("Unexpected connect error %v", err)
|
t.Fatalf("Unexpected connect error %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
topic := "test"
|
topic := "test"
|
||||||
count := 10
|
count := 10
|
||||||
|
|
||||||
fn := func(m *broker.Message) error {
|
fn := func(evts broker.Events) error {
|
||||||
return nil
|
return evts.Ack()
|
||||||
}
|
}
|
||||||
|
|
||||||
sub, err := b.Subscribe(topic, fn)
|
sub, err := b.BatchSubscribe(ctx, topic, fn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Unexpected error subscribing %v", err)
|
t.Fatalf("Unexpected error subscribing %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
msgs := make([]*broker.Message, 0, count)
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
message := &broker.Message{
|
message := &broker.Message{
|
||||||
Header: map[string]string{
|
Header: map[string]string{
|
||||||
"foo": "bar",
|
metadata.HeaderTopic: topic,
|
||||||
"id": fmt.Sprintf("%d", i),
|
"foo": "bar",
|
||||||
|
"id": fmt.Sprintf("%d", i),
|
||||||
},
|
},
|
||||||
Body: []byte(`hello world`),
|
Body: []byte(`"hello world"`),
|
||||||
}
|
|
||||||
|
|
||||||
if err := b.Publish(topic, message); err != nil {
|
|
||||||
t.Fatalf("Unexpected error publishing %d", i)
|
|
||||||
}
|
}
|
||||||
|
msgs = append(msgs, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := sub.Unsubscribe(); err != nil {
|
if err := b.BatchPublish(ctx, msgs); err != nil {
|
||||||
|
t.Fatalf("Unexpected error publishing %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sub.Unsubscribe(ctx); err != nil {
|
||||||
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := b.Disconnect(); err != nil {
|
if err := b.Disconnect(ctx); err != nil {
|
||||||
|
t.Fatalf("Unexpected connect error %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMemoryBroker(t *testing.T) {
|
||||||
|
b := NewBroker()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := b.Init(); err != nil {
|
||||||
|
t.Fatalf("Unexpected init error %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := b.Connect(ctx); err != nil {
|
||||||
|
t.Fatalf("Unexpected connect error %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
topic := "test"
|
||||||
|
count := 10
|
||||||
|
|
||||||
|
fn := func(_ broker.Event) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
sub, err := b.Subscribe(ctx, topic, fn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Unexpected error subscribing %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs := make([]*broker.Message, 0, count)
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
message := &broker.Message{
|
||||||
|
Header: map[string]string{
|
||||||
|
metadata.HeaderTopic: topic,
|
||||||
|
"foo": "bar",
|
||||||
|
"id": fmt.Sprintf("%d", i),
|
||||||
|
},
|
||||||
|
Body: []byte(`"hello world"`),
|
||||||
|
}
|
||||||
|
msgs = append(msgs, message)
|
||||||
|
|
||||||
|
if err := b.Publish(ctx, topic, message); err != nil {
|
||||||
|
t.Fatalf("Unexpected error publishing %d err: %v", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := b.BatchPublish(ctx, msgs); err != nil {
|
||||||
|
t.Fatalf("Unexpected error publishing %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sub.Unsubscribe(ctx); err != nil {
|
||||||
|
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := b.Disconnect(ctx); err != nil {
|
||||||
t.Fatalf("Unexpected connect error %v", err)
|
t.Fatalf("Unexpected connect error %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setBrokerOption returns a function to setup a context with given value
|
|
||||||
func setBrokerOption(k, v interface{}) broker.Option {
|
|
||||||
return func(o *broker.Options) {
|
|
||||||
if o.Context == nil {
|
|
||||||
o.Context = context.Background()
|
|
||||||
}
|
|
||||||
o.Context = context.WithValue(o.Context, k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,294 +0,0 @@
|
|||||||
// Package nats provides a NATS broker
|
|
||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
"github.com/micro/go-micro/v3/codec/json"
|
|
||||||
"github.com/micro/go-micro/v3/logger"
|
|
||||||
"github.com/micro/go-micro/v3/registry/mdns"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type natsBroker struct {
|
|
||||||
sync.Once
|
|
||||||
sync.RWMutex
|
|
||||||
|
|
||||||
// indicate if we're connected
|
|
||||||
connected bool
|
|
||||||
|
|
||||||
addrs []string
|
|
||||||
conn *nats.Conn
|
|
||||||
opts broker.Options
|
|
||||||
nopts nats.Options
|
|
||||||
|
|
||||||
// should we drain the connection
|
|
||||||
drain bool
|
|
||||||
closeCh chan (error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type subscriber struct {
|
|
||||||
s *nats.Subscription
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Options() broker.SubscribeOptions {
|
|
||||||
return s.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Topic() string {
|
|
||||||
return s.s.Subject
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Unsubscribe() error {
|
|
||||||
return s.s.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Address() string {
|
|
||||||
if n.conn != nil && n.conn.IsConnected() {
|
|
||||||
return n.conn.ConnectedUrl()
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(n.addrs) > 0 {
|
|
||||||
return n.addrs[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) setAddrs(addrs []string) []string {
|
|
||||||
//nolint:prealloc
|
|
||||||
var cAddrs []string
|
|
||||||
for _, addr := range addrs {
|
|
||||||
if len(addr) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(addr, "nats://") {
|
|
||||||
addr = "nats://" + addr
|
|
||||||
}
|
|
||||||
cAddrs = append(cAddrs, addr)
|
|
||||||
}
|
|
||||||
if len(cAddrs) == 0 {
|
|
||||||
cAddrs = []string{nats.DefaultURL}
|
|
||||||
}
|
|
||||||
return cAddrs
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Connect() error {
|
|
||||||
n.Lock()
|
|
||||||
defer n.Unlock()
|
|
||||||
|
|
||||||
if n.connected {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
status := nats.CLOSED
|
|
||||||
if n.conn != nil {
|
|
||||||
status = n.conn.Status()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch status {
|
|
||||||
case nats.CONNECTED, nats.RECONNECTING, nats.CONNECTING:
|
|
||||||
n.connected = true
|
|
||||||
return nil
|
|
||||||
default: // DISCONNECTED or CLOSED or DRAINING
|
|
||||||
opts := n.nopts
|
|
||||||
opts.Servers = n.addrs
|
|
||||||
opts.Secure = n.opts.Secure
|
|
||||||
opts.TLSConfig = n.opts.TLSConfig
|
|
||||||
|
|
||||||
// secure might not be set
|
|
||||||
if n.opts.TLSConfig != nil {
|
|
||||||
opts.Secure = true
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := opts.Connect()
|
|
||||||
if err != nil {
|
|
||||||
if logger.V(logger.WarnLevel, logger.DefaultLogger) {
|
|
||||||
logger.Warnf("Error connecting to broker: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
n.conn = c
|
|
||||||
n.connected = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Disconnect() error {
|
|
||||||
n.Lock()
|
|
||||||
defer n.Unlock()
|
|
||||||
|
|
||||||
// drain the connection if specified
|
|
||||||
if n.drain {
|
|
||||||
n.conn.Drain()
|
|
||||||
n.closeCh <- nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// close the client connection
|
|
||||||
n.conn.Close()
|
|
||||||
|
|
||||||
// set not connected
|
|
||||||
n.connected = false
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Init(opts ...broker.Option) error {
|
|
||||||
n.setOption(opts...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Options() broker.Options {
|
|
||||||
return n.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
|
||||||
n.RLock()
|
|
||||||
defer n.RUnlock()
|
|
||||||
|
|
||||||
if n.conn == nil {
|
|
||||||
return errors.New("not connected")
|
|
||||||
}
|
|
||||||
|
|
||||||
b, err := n.opts.Codec.Marshal(msg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return n.conn.Publish(topic, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
n.RLock()
|
|
||||||
if n.conn == nil {
|
|
||||||
n.RUnlock()
|
|
||||||
return nil, errors.New("not connected")
|
|
||||||
}
|
|
||||||
n.RUnlock()
|
|
||||||
|
|
||||||
opt := broker.SubscribeOptions{
|
|
||||||
Context: context.Background(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn := func(msg *nats.Msg) {
|
|
||||||
var m *broker.Message
|
|
||||||
eh := opt.ErrorHandler
|
|
||||||
err := n.opts.Codec.Unmarshal(msg.Data, &m)
|
|
||||||
if err != nil {
|
|
||||||
m.Body = msg.Data
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
if eh != nil {
|
|
||||||
eh(m, err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := handler(m); err != nil {
|
|
||||||
if logger.V(logger.ErrorLevel, logger.DefaultLogger) {
|
|
||||||
logger.Error(err)
|
|
||||||
}
|
|
||||||
if eh != nil {
|
|
||||||
eh(m, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var sub *nats.Subscription
|
|
||||||
var err error
|
|
||||||
|
|
||||||
n.RLock()
|
|
||||||
if len(opt.Queue) > 0 {
|
|
||||||
sub, err = n.conn.QueueSubscribe(topic, opt.Queue, fn)
|
|
||||||
} else {
|
|
||||||
sub, err = n.conn.Subscribe(topic, fn)
|
|
||||||
}
|
|
||||||
n.RUnlock()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &subscriber{s: sub, opts: opt}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) String() string {
|
|
||||||
return "nats"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) setOption(opts ...broker.Option) {
|
|
||||||
for _, o := range opts {
|
|
||||||
o(&n.opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
n.Once.Do(func() {
|
|
||||||
n.nopts = nats.GetDefaultOptions()
|
|
||||||
})
|
|
||||||
|
|
||||||
if nopts, ok := n.opts.Context.Value(optionsKey{}).(nats.Options); ok {
|
|
||||||
n.nopts = nopts
|
|
||||||
}
|
|
||||||
|
|
||||||
// broker.Options have higher priority than nats.Options
|
|
||||||
// only if Addrs, Secure or TLSConfig were not set through a broker.Option
|
|
||||||
// we read them from nats.Option
|
|
||||||
if len(n.opts.Addrs) == 0 {
|
|
||||||
n.opts.Addrs = n.nopts.Servers
|
|
||||||
}
|
|
||||||
|
|
||||||
if !n.opts.Secure {
|
|
||||||
n.opts.Secure = n.nopts.Secure
|
|
||||||
}
|
|
||||||
|
|
||||||
if n.opts.TLSConfig == nil {
|
|
||||||
n.opts.TLSConfig = n.nopts.TLSConfig
|
|
||||||
}
|
|
||||||
n.addrs = n.setAddrs(n.opts.Addrs)
|
|
||||||
|
|
||||||
if n.opts.Context.Value(drainConnectionKey{}) != nil {
|
|
||||||
n.drain = true
|
|
||||||
n.closeCh = make(chan error)
|
|
||||||
n.nopts.ClosedCB = n.onClose
|
|
||||||
n.nopts.AsyncErrorCB = n.onAsyncError
|
|
||||||
n.nopts.DisconnectedErrCB = n.onDisconnectedError
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onClose(conn *nats.Conn) {
|
|
||||||
n.closeCh <- nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onAsyncError(conn *nats.Conn, sub *nats.Subscription, err error) {
|
|
||||||
// There are kinds of different async error nats might callback, but we are interested
|
|
||||||
// in ErrDrainTimeout only here.
|
|
||||||
if err == nats.ErrDrainTimeout {
|
|
||||||
n.closeCh <- err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *natsBroker) onDisconnectedError(conn *nats.Conn, err error) {
|
|
||||||
n.closeCh <- err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBroker(opts ...broker.Option) broker.Broker {
|
|
||||||
options := broker.Options{
|
|
||||||
// Default codec
|
|
||||||
Codec: json.Marshaler{},
|
|
||||||
Context: context.Background(),
|
|
||||||
Registry: mdns.NewRegistry(),
|
|
||||||
}
|
|
||||||
|
|
||||||
n := &natsBroker{
|
|
||||||
opts: options,
|
|
||||||
}
|
|
||||||
n.setOption(opts...)
|
|
||||||
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
var addrTestCases = []struct {
|
|
||||||
name string
|
|
||||||
description string
|
|
||||||
addrs map[string]string // expected address : set address
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
"brokerOpts",
|
|
||||||
"set broker addresses through a broker.Option in constructor",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"brokerInit",
|
|
||||||
"set broker addresses through a broker.Option in broker.Init()",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"natsOpts",
|
|
||||||
"set broker addresses through the nats.Option in constructor",
|
|
||||||
map[string]string{
|
|
||||||
"nats://192.168.10.1:5222": "192.168.10.1:5222",
|
|
||||||
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"default",
|
|
||||||
"check if default Address is set correctly",
|
|
||||||
map[string]string{
|
|
||||||
"nats://127.0.0.1:4222": "",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestInitAddrs tests issue #100. Ensures that if the addrs is set by an option in init it will be used.
|
|
||||||
func TestInitAddrs(t *testing.T) {
|
|
||||||
|
|
||||||
for _, tc := range addrTestCases {
|
|
||||||
t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {
|
|
||||||
|
|
||||||
var br broker.Broker
|
|
||||||
var addrs []string
|
|
||||||
|
|
||||||
for _, addr := range tc.addrs {
|
|
||||||
addrs = append(addrs, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch tc.name {
|
|
||||||
case "brokerOpts":
|
|
||||||
// we know that there are just two addrs in the dict
|
|
||||||
br = NewBroker(broker.Addrs(addrs[0], addrs[1]))
|
|
||||||
br.Init()
|
|
||||||
case "brokerInit":
|
|
||||||
br = NewBroker()
|
|
||||||
// we know that there are just two addrs in the dict
|
|
||||||
br.Init(broker.Addrs(addrs[0], addrs[1]))
|
|
||||||
case "natsOpts":
|
|
||||||
nopts := nats.GetDefaultOptions()
|
|
||||||
nopts.Servers = addrs
|
|
||||||
br = NewBroker(Options(nopts))
|
|
||||||
br.Init()
|
|
||||||
case "default":
|
|
||||||
br = NewBroker()
|
|
||||||
br.Init()
|
|
||||||
}
|
|
||||||
|
|
||||||
natsBroker, ok := br.(*natsBroker)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("Expected broker to be of types *natsBroker")
|
|
||||||
}
|
|
||||||
// check if the same amount of addrs we set has actually been set, default
|
|
||||||
// have only 1 address nats://127.0.0.1:4222 (current nats code) or
|
|
||||||
// nats://localhost:4222 (older code version)
|
|
||||||
if len(natsBroker.addrs) != len(tc.addrs) && tc.name != "default" {
|
|
||||||
t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
|
|
||||||
len(natsBroker.addrs), len(tc.addrs))
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, addr := range natsBroker.addrs {
|
|
||||||
_, ok := tc.addrs[addr]
|
|
||||||
if !ok {
|
|
||||||
t.Errorf("Expected '%s' has not been set", addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package nats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/micro/go-micro/v3/broker"
|
|
||||||
nats "github.com/nats-io/nats.go"
|
|
||||||
)
|
|
||||||
|
|
||||||
type optionsKey struct{}
|
|
||||||
type drainConnectionKey struct{}
|
|
||||||
|
|
||||||
// Options accepts nats.Options
|
|
||||||
func Options(opts nats.Options) broker.Option {
|
|
||||||
return setBrokerOption(optionsKey{}, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DrainConnection will drain subscription on close
|
|
||||||
func DrainConnection() broker.Option {
|
|
||||||
return setBrokerOption(drainConnectionKey{}, struct{}{})
|
|
||||||
}
|
|
||||||
140
broker/noop.go
Normal file
140
broker/noop.go
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"go.unistack.org/micro/v3/options"
|
||||||
|
)
|
||||||
|
|
||||||
|
type NoopBroker struct {
|
||||||
|
funcPublish FuncPublish
|
||||||
|
funcBatchPublish FuncBatchPublish
|
||||||
|
funcSubscribe FuncSubscribe
|
||||||
|
funcBatchSubscribe FuncBatchSubscribe
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBroker(opts ...Option) *NoopBroker {
|
||||||
|
b := &NoopBroker{opts: NewOptions(opts...)}
|
||||||
|
b.funcPublish = b.fnPublish
|
||||||
|
b.funcBatchPublish = b.fnBatchPublish
|
||||||
|
b.funcSubscribe = b.fnSubscribe
|
||||||
|
b.funcBatchSubscribe = b.fnBatchSubscribe
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Health() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Live() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Ready() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Name() string {
|
||||||
|
return b.opts.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) String() string {
|
||||||
|
return "noop"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Options() Options {
|
||||||
|
return b.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Init(opts ...Option) error {
|
||||||
|
for _, opt := range opts {
|
||||||
|
opt(&b.opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.funcPublish = b.fnPublish
|
||||||
|
b.funcBatchPublish = b.fnBatchPublish
|
||||||
|
b.funcSubscribe = b.fnSubscribe
|
||||||
|
b.funcBatchSubscribe = b.fnBatchSubscribe
|
||||||
|
|
||||||
|
b.opts.Hooks.EachPrev(func(hook options.Hook) {
|
||||||
|
switch h := hook.(type) {
|
||||||
|
case HookPublish:
|
||||||
|
b.funcPublish = h(b.funcPublish)
|
||||||
|
case HookBatchPublish:
|
||||||
|
b.funcBatchPublish = h(b.funcBatchPublish)
|
||||||
|
case HookSubscribe:
|
||||||
|
b.funcSubscribe = h(b.funcSubscribe)
|
||||||
|
case HookBatchSubscribe:
|
||||||
|
b.funcBatchSubscribe = h(b.funcBatchSubscribe)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Connect(_ context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Disconnect(_ context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Address() string {
|
||||||
|
return strings.Join(b.opts.Addrs, ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) fnBatchPublish(_ context.Context, _ []*Message, _ ...PublishOption) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) BatchPublish(ctx context.Context, msgs []*Message, opts ...PublishOption) error {
|
||||||
|
return b.funcBatchPublish(ctx, msgs, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) fnPublish(_ context.Context, _ string, _ *Message, _ ...PublishOption) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error {
|
||||||
|
return b.funcPublish(ctx, topic, msg, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type NoopSubscriber struct {
|
||||||
|
ctx context.Context
|
||||||
|
topic string
|
||||||
|
handler Handler
|
||||||
|
batchHandler BatchHandler
|
||||||
|
opts SubscribeOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) fnBatchSubscribe(ctx context.Context, topic string, handler BatchHandler, opts ...SubscribeOption) (Subscriber, error) {
|
||||||
|
return &NoopSubscriber{ctx: ctx, topic: topic, opts: NewSubscribeOptions(opts...), batchHandler: handler}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) BatchSubscribe(ctx context.Context, topic string, handler BatchHandler, opts ...SubscribeOption) (Subscriber, error) {
|
||||||
|
return b.funcBatchSubscribe(ctx, topic, handler, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) fnSubscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||||
|
return &NoopSubscriber{ctx: ctx, topic: topic, opts: NewSubscribeOptions(opts...), handler: handler}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *NoopBroker) Subscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
|
||||||
|
return b.funcSubscribe(ctx, topic, handler, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *NoopSubscriber) Options() SubscribeOptions {
|
||||||
|
return s.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *NoopSubscriber) Topic() string {
|
||||||
|
return s.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *NoopSubscriber) Unsubscribe(_ context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user