├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── README_ZH.md ├── cache ├── cache.go ├── cache_pool.go ├── mem_cache_pool.go ├── redis_cache_pool.go └── util.go ├── config ├── cfg.toml └── init.go ├── go.mod ├── go.sum ├── handler ├── auth.go ├── cache.go ├── headers.go ├── proxy.go ├── rebalance.go └── status.go ├── interface └── cacher.go ├── server.go ├── test ├── config │ └── cfg.toml └── server_test.go └── tool ├── hashring.go ├── regexp.go └── util.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | .idea/ 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - "1.10.x" 5 | - "1.11.x" 6 | - "1.12.x" 7 | - "1.13.x" 8 | - master 9 | 10 | env: 11 | - GO111MODULE=on 12 | 13 | before_install: 14 | - go get -t -v ./... 15 | 16 | services: 17 | - redis-server 18 | 19 | script: 20 | - go test -v ./test/... 21 | 22 | after_success: 23 | - tail -n 100 ./test/logs/*.log.* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | [![Build Status](https://travis-ci.org/panjf2000/goproxy.svg?branch=master)](https://travis-ci.org/panjf2000/goproxy) 5 | [![Goproxy on Sourcegraph](https://sourcegraph.com/github.com/panjf2000/goproxy/-/badge.svg)](https://sourcegraph.com/github.com/panjf2000/goproxy?badge) 6 | [![GPL Licence](https://badges.frapsoft.com/os/gpl/gpl.svg?v=103)](https://opensource.org/licenses/GPL-3.0/) 7 | [![Open Source Love](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badges/) 8 | 9 | Engilish|[🇨🇳中文](README_ZH.md) 10 | 11 | ## goproxy 12 | 13 | goproxy is a load-balancing, reverse-proxy server implemented in go, supporting cache( in memory or Redis). As a load-balancing server, it supports 4 algorithms: Randomized Algorithm, Weight Round Robin Algorithm, Power of Two Choices (P2C) Algorithm, IP Hash Algorithm, Consistent Hashing with Bounded Loads Algorithm, besides, goproxy can dominate the http requests: filtering and blocking specific requests and even rewriting them. 14 | 15 | Sometimes your program needs to call some third party API and wants to customize the responses from it, in that case, goproxy will be your great choice. 16 | 17 | ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/reverseproxy.png) 18 | 19 | ## 🚀 Features: 20 | 21 | - Supporting reverse-proxy, 7 load-balancing algorithms in goproxy: Random, IP Hash, Round Robin, Weight Round Robin, Power of Two Choices (P2C), Consistent Hashing with Bounded Loads, Least Load 22 | - Supporting GET/POST/PUT/DELETE Methods in http and CONNECT method in https in goproxy 23 | - Supporting HTTP authentication 24 | - Filtering and blocking specific http requests and even rewriting them in goproxy 25 | - Customizing responses from third-party API 26 | - Cache support with memory or Redis to speed up the responding and the expired time of caches is configurable 27 | - Flexible and eager-loading configurations 28 | 29 | ## 🎉 How to use goproxy 30 | 31 | ### 1.Get source code 32 | 33 | ```powershell 34 | go get github.com/panjf2000/goproxy 35 | ``` 36 | 37 | **Besides, you also need a Redis to support caching responses if you enable Redis config in goproxy.** 38 | 39 | ### 2.Compile the source code 40 | 41 | ```powershell 42 | cd $GOPATH/src/github.com/panjf2000/goproxy 43 | 44 | go build 45 | ``` 46 | 47 | ### 3.Run 48 | 49 | goproxy uses cfg.toml as its configurations file which is located in `/etc/proxy/cfg.toml` of your server, you should create a cfg.toml in there previously, here is a typical example: 50 | 51 | ```toml 52 | # toml file for goproxy 53 | 54 | title = "TOML config for goproxy" 55 | 56 | [server] 57 | port = ":8080" 58 | reverse = true 59 | proxy_pass = ["127.0.0.1:6000"] 60 | # 0 - random, 1 - loop, 2 - power of two choices(p2c), 3 - hash, 4 - consistent hashing, 5 - least load 61 | inverse_mode = 2 62 | auth = false 63 | cache = true 64 | cache_timeout = 60 65 | cache_type = "redis" 66 | log = 1 67 | log_path = "./logs" 68 | user = { agent = "proxy" } 69 | http_read_timeout = 10 70 | http_write_timeout = 10 71 | 72 | [redis] 73 | redis_host = "localhost:6379" 74 | redis_pass = "" 75 | max_idle = 5 76 | idle_timeout = 10 77 | max_active = 10 78 | 79 | [mem] 80 | capacity = 1000 81 | cache_replacement_policy = "LRU" 82 | ``` 83 | 84 | ### Configurations: 85 | #### [server] 86 | - **port**:the port goroxy will listen to 87 | - **reverse**:enable the reverse-proxy feature or not 88 | - **proxy_pass**:back-end servers that actually provide services, like ["127.0.0.1:80^10","127.0.0.1:88^5","127.0.0.1:8088^2","127.0.0.1:8888"], weight can be assigned to every single server 89 | - **inverse_mode**:load-balancing algoritms:0 for Randomized Algorithm; 1 for Weight Round Robin Algorithm; 2 for Power of Two Choices (P2C) Algorithm; 3 for IP Hash Algorithm based on hash ring; 4 for Consistent Hashing with Bounded Loads Algorithm 90 | - **auth**:enable http authentication or not 91 | - **cache**:enable responses caching or not 92 | - **cache_timeout**:expired time of responses caching, in seconds 93 | - **cache_type**: redis or memory 94 | - **log**:log level, 1 for Debug,0 for info 95 | - **log_path**:the path of log files 96 | - **user**:user name from http authentication 97 | - **http_read_timeout**:duration for waiting response from the back-end server, if goproxy don't get the response after this duration, it will throw an exception 98 | - **http_write_timeout**:duration for back-end server writing response to goproxy, if back-end server takes a longer time than this duration to write its response into goproxy, goproxy will throw an exception 99 | 100 | #### [redis] 101 | - **redis_host**:redis host 102 | - **redis_pass**:redis password 103 | - **max_idle**:the maximum idle connections of redis connection pool 104 | - **idle_timeout**:duration for idle redis connection to close 105 | - **max_active**:maximum size of redis connection pool 106 | 107 | #### [mem] 108 | 109 | - **capacity**: cache capacity of items 110 | - **cache_replacement_policy**: LRU or LFU 111 | 112 | There should be a binary named `goproxy` as the same of project name after executing the `go build` command and that binary can be run directly to start a goproxy server. 113 | 114 | The running goproxy server listens in the port set in cfg.toml and it will forward your http requests to the back-end servers set in cfg.toml by going through that port in goproxy. 115 | 116 | ## 🎱 Secondary development 117 | 118 | Up to present, goproxy has implemented all basic functionalities like reverse-proxy, load-blancing, http caching, http requests controlling, etc and if you want to customize the responses more accurately, you can implement a new handler by inheriting (not a strict statement as there is no OO in golang) from the ProxyServer struct located in handlers/proxy.go and overriding its method named ServeHTTP, then you are allowed to write your own logic into it. 119 | 120 | ## 🙏🏻 Thanks 121 | 122 | - [httpproxy](https://github.com/sakeven/httpproxy) 123 | - [gcache](https://github.com/bluele/gcache) 124 | - [viper](https://github.com/spf13/viper) 125 | - [redigo](https://github.com/gomodule/redigo) -------------------------------------------------------------------------------- /README_ZH.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | [![Build Status](https://travis-ci.org/panjf2000/goproxy.svg?branch=master)](https://travis-ci.org/panjf2000/goproxy) 5 | [![Goproxy on Sourcegraph](https://sourcegraph.com/github.com/panjf2000/goproxy/-/badge.svg)](https://sourcegraph.com/github.com/panjf2000/goproxy?badge) 6 | [![GPL Licence](https://badges.frapsoft.com/os/gpl/gpl.svg?v=103)](https://opensource.org/licenses/GPL-3.0/) 7 | [![Open Source Love](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badges/) 8 | 9 | 🇨🇳中文|[English](README.md) 10 | 11 | ## goproxy 12 | 13 | goproxy 是使用 Go 实现的一个基本的负载均衡服务器,支持缓存(使用内存或者 Redis);负载均衡目前支持:随机挑选一个服务器、轮询法(加权轮询)、p2c 负载均衡算法、IP HASH 模式,根据 client ip 用 hash ring 择取服务器、边界一致性哈希算法 6 种模式。另外,对转发的请求有较大的控制度,可以控制代理特定的请求,屏蔽特定的请求,甚至可以重写特定的请求。 14 | 15 | 另外,有时候项目需要用到第三方的服务并对返回的数据进行自定义修改,调用第三方的 API,利用 goproxy 可以很容易的控制第三方 API 返回的数据并进行自定义修改。 16 | 17 | ![](https://raw.githubusercontent.com/panjf2000/illustrations/master/go/reverseproxy.png) 18 | 19 | ## 🚀 功能: 20 | 21 | - 反向代理、负载均衡,负载策略目前支持 7 种算法:随机选取、IP HASH两种模式、轮询(Round Robin)法、加权轮询(Weight Round Robin)法、Power of Two Choices (P2C)算法、边界一致性哈希算法(Consistent Hashing with Bounded Loads), 最小负载算法(Least Load) 22 | - 支持 GET/POST/PUT/DELETE 这些 HTTP Methods,还有 HTTPS 的 CONNECT 方法 23 | - 支持 HTTP authentication 24 | - 支持屏蔽/过滤第三方 API 25 | - 支持改写 responses 26 | - 支持内容缓存和重校验:把 response 缓存在内存或者 Redis,定期刷新,加快请求响应速度 27 | - 灵活的 configurations 配置,支持热加载 28 | 29 | ## 🎉 使用 30 | 31 | ### 1.获取源码 32 | 33 | ```powershell 34 | go get github.com/panjf2000/goproxy 35 | ``` 36 | **如果开启 Redis 配置,则需要额外安装 Redis。** 37 | 38 | ### 2.编译源码 39 | ```powershell 40 | cd $GOPATH/src/github.com/panjf2000/goproxy 41 | 42 | go build 43 | ``` 44 | 45 | ### 3.运行 46 | 先配置 cfg.toml 配置文件,cfg.toml 配置文件默认存放路径为 `/etc/proxy/cfg.toml`,需要在该目录预先放置一个 cfg.toml 配置文件,一个典型的例子如下: 47 | ```toml 48 | # toml file for goproxy 49 | 50 | title = "TOML config for goproxy" 51 | 52 | [server] 53 | port = ":8080" 54 | reverse = true 55 | proxy_pass = ["127.0.0.1:6000"] 56 | # 0 - random, 1 - loop, 2 - power of two choices(p2c), 3 - hash, 4 - consistent hashing, 5 - least load 57 | inverse_mode = 2 58 | auth = false 59 | cache = true 60 | cache_timeout = 60 61 | cache_type = "redis" 62 | log = 1 63 | log_path = "./logs" 64 | user = { agent = "proxy" } 65 | http_read_timeout = 10 66 | http_write_timeout = 10 67 | 68 | [redis] 69 | redis_host = "localhost:6379" 70 | redis_pass = "" 71 | max_idle = 5 72 | idle_timeout = 10 73 | max_active = 10 74 | 75 | [mem] 76 | capacity = 1000 77 | cache_replacement_policy = "LRU" 78 | ``` 79 | 80 | ### 配置项: 81 | #### [server] 82 | - **port**:代理服务器的监听端口 83 | - **reverse**:设置反向代理,值为 true 或者 false 84 | - **proxy_pass**:反向代理目标服务器地址列表,如["127.0.0.1:80^10","127.0.0.1:88^5","127.0.0.1:8088^2","127.0.0.1:8888"],目前支持设置服务器权重,依权重优先转发请求 85 | - **inverse_mode**:设置负载策略,即选择转发的服务器,目前支持模式:0-随机挑选一个服务器; 1-轮询法(加权轮询); 2-p2c负载均衡算法; 3-IP HASH 模式,根据 client ip 用 hash ring 择取服务器; 4-边界一致性哈希算法 86 | - **auth**:开启代理认证,值为 true 或者 false 87 | - **cache**:是否开启缓存(缓存response),值为 true 或者 false 88 | - **cache_timeout**:redis 缓存 response 的刷新时间,以秒为单位 89 | - **cache_type**: redis 或者 memory 90 | - **log**:设置 log 的 level,值为 1 表示 Debug,值为 0 表示 info 91 | - **log_path**:设置存放 log 的路径 92 | - **user**:代理服务器的 http authentication 用户 93 | - **http_read_timeout**:代理服务器读取 http request 的超时时间,一旦超过该时长,就会抛出异常 94 | - **http_write_timeout**:代理服务器转发后端真实服务器时写入 http response 的超时时间,一旦超过该时长,就会抛出异常 95 | 96 | #### [redis] 97 | - **redis_host**:缓存模块的 redis host 98 | - **redis_pass**:redis 密码 99 | - **max_idle**:redis 连接池最大空闲连接数 100 | - **idle_timeout**:空闲连接超时关闭设置 101 | - **max_active**:连接池容量 102 | 103 | #### [mem] 104 | 105 | - **capacity**:缓存容量 106 | - **cache_replacement_policy**:LRU 或者 LFU 算法 107 | 108 | 运行完go build后会生成一个执行文件,名字与项目名相同,可以直接运行:./goproxy 启动反向代理服务器。 109 | 110 | goproxy 运行之后会监听配置文件中设置的 port 端口,然后直接访问该端口即可实现反向代理,将请求转发至proxy_pass参数中的服务器。 111 | 112 | ## 🎱 二次开发 113 | 114 | 目前该项目已实现反向代理负载均衡,支持缓存,也可以支持开发者精确控制请求,如屏蔽某些请求或者重写某些请求,甚至于对 response 进行自定义修改(定制 response 的内容),要实现精确控制 request,只需继承(不严谨的说法,因为实际上 golang 没有面向对象的概念)handlers/proxy.go 中的 ProxyServer struct,重写它的 ServeHTTP 方法,进行自定义的处理即可。 115 | 116 | ## 🙏🏻 致谢 117 | 118 | - [httpproxy](https://github.com/sakeven/httpproxy) 119 | - [gcache](https://github.com/bluele/gcache) 120 | - [viper](https://github.com/spf13/viper) 121 | - [redigo](https://github.com/gomodule/redigo) 122 | -------------------------------------------------------------------------------- /cache/cache.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | // "io" 5 | "io/ioutil" 6 | "log" 7 | "net/http" 8 | "strings" 9 | "time" 10 | 11 | "github.com/panjf2000/goproxy/config" 12 | ) 13 | 14 | type HttpCache struct { 15 | Header http.Header `json:"header"` 16 | Body []byte `json:"body"` 17 | StatusCode int `json:"status_code"` 18 | URI string `json:"url"` 19 | LastModified string `json:"last_modified"` //eg:"Fri, 27 Jun 2014 07:19:49 GMT" 20 | ETag string `json:"etag"` 21 | MustVerified bool `json:"must_verified"` 22 | //Validity is a time when to verify the cache again. 23 | Validity time.Time `json:"validity"` 24 | maxAge int64 `json:"-"` 25 | } 26 | 27 | func NewCacheResp(resp *http.Response) *HttpCache { 28 | c := new(HttpCache) 29 | c.Header = make(http.Header) 30 | CopyHeaders(c.Header, resp.Header) 31 | c.StatusCode = resp.StatusCode 32 | 33 | var err error 34 | c.Body, err = ioutil.ReadAll(resp.Body) 35 | 36 | if c.Header == nil { 37 | return nil 38 | } 39 | 40 | c.ETag = c.Header.Get("ETag") 41 | c.LastModified = c.Header.Get("Last-Modified") 42 | 43 | cacheControl := c.Header.Get("Cache-Control") 44 | 45 | // no-cache means you should verify data before use cache. 46 | // only use cache when remote server returns 302 status. 47 | if strings.Index(cacheControl, "no-cache") != -1 || 48 | strings.Index(cacheControl, "must-revalidate") != -1 || 49 | strings.Index(cacheControl, "proxy-revalidate") != -1 { 50 | c.MustVerified = false 51 | return nil 52 | } 53 | c.MustVerified = true 54 | 55 | if Expires := c.Header.Get("Expires"); Expires != "" { 56 | c.Validity, err = time.Parse(http.TimeFormat, Expires) 57 | if err != nil { 58 | return nil 59 | } 60 | log.Println("expire:", c.Validity) 61 | } 62 | 63 | maxAge := getAge(cacheControl) 64 | if maxAge != -1 { 65 | var Time time.Time 66 | date := c.Header.Get("Date") 67 | if date == "" { 68 | Time = time.Now().UTC() 69 | } else { 70 | Time, err = time.Parse(time.RFC1123, date) 71 | if err != nil { 72 | return nil 73 | } 74 | } 75 | c.Validity = Time.Add(time.Duration(maxAge) * time.Second) 76 | c.maxAge = maxAge 77 | } else { 78 | //c.maxAge, max_age = 0.1 * 60 * 60, 0.1 * 60 * 60 79 | cacheTimeout := config.RuntimeViper.GetInt64("server.cache_timeout") 80 | c.maxAge, maxAge = cacheTimeout, cacheTimeout 81 | Time := time.Now().UTC() 82 | c.Validity = Time.Add(time.Duration(maxAge) * time.Second) 83 | } 84 | log.Println("all:", c.Validity) 85 | 86 | return c 87 | } 88 | 89 | // Verify verifies whether cache is out of date. 90 | func (c *HttpCache) Verify() bool { 91 | if c.MustVerified == true && c.Validity.After(time.Now().UTC()) { 92 | return true 93 | } 94 | 95 | newReq, err := http.NewRequest("GET", c.URI, nil) 96 | if err != nil { 97 | return false 98 | } 99 | 100 | if c.LastModified != "" { 101 | newReq.Header.Add("If-Modified-Since", c.LastModified) 102 | } 103 | if c.ETag != "" { 104 | newReq.Header.Add("If-None-Match", c.ETag) 105 | } 106 | Tr := &http.Transport{Proxy: http.ProxyFromEnvironment} 107 | resp, err := Tr.RoundTrip(newReq) 108 | if err != nil { 109 | return false 110 | } 111 | 112 | if resp.StatusCode != http.StatusNotModified { 113 | return false 114 | } 115 | return false 116 | } 117 | 118 | // CacheHandler handles "Get" request 119 | func (c *HttpCache) WriteTo(rw http.ResponseWriter) (int, error) { 120 | 121 | CopyHeaders(rw.Header(), c.Header) 122 | rw.WriteHeader(c.StatusCode) 123 | 124 | return rw.Write(c.Body) 125 | 126 | } 127 | 128 | // CopyHeaders copies headers from source to destination. 129 | // Nothing would be returned. 130 | func CopyHeaders(dst, src http.Header) { 131 | for key, values := range src { 132 | for _, value := range values { 133 | dst.Add(key, value) 134 | } 135 | } 136 | } 137 | 138 | //getAge from Cache Control get cache's lifetime. 139 | func getAge(cacheControl string) (age int64) { 140 | f := func(sage string) int64 { 141 | var tmpAge int64 142 | idx := strings.Index(cacheControl, sage) 143 | if idx != -1 { 144 | for i := idx + len(sage) + 1; i < len(cacheControl); i++ { 145 | if cacheControl[i] >= '0' && cacheControl[i] <= '9' { 146 | tmpAge = tmpAge*10 + int64(cacheControl[i]) 147 | } else { 148 | break 149 | } 150 | } 151 | return tmpAge 152 | } 153 | return -1 154 | } 155 | if sMaxAge := f("s-maxage"); sMaxAge != -1 { 156 | return sMaxAge 157 | } 158 | return f("max-age") 159 | } 160 | -------------------------------------------------------------------------------- /cache/cache_pool.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "github.com/panjf2000/goproxy/config" 5 | api "github.com/panjf2000/goproxy/interface" 6 | ) 7 | 8 | type CachePoolType int 9 | 10 | const ( 11 | Mem = iota 12 | Redis 13 | ) 14 | 15 | func NewCachePool(cachePoolType CachePoolType) api.CachePool { 16 | switch cachePoolType { 17 | case Redis: 18 | return NewRedisCachePool(config.RuntimeViper.GetString("redis.redis_host"), 19 | config.RuntimeViper.GetString("redis.redis_pass"), config.RuntimeViper.GetInt("redis.idle_timeout"), 20 | config.RuntimeViper.GetInt("redis.max_active"), config.RuntimeViper.GetInt("redis.max_idle")) 21 | default: 22 | var crp CacheReplacementPolicy 23 | if config.RuntimeViper.GetString("mem.cache_replacement_policy") == "LFU" { 24 | crp = LFU 25 | } 26 | return NewMemCachePool(config.RuntimeViper.GetInt("mem.capacity"), crp) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /cache/mem_cache_pool.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | "time" 7 | 8 | "github.com/bluele/gcache" 9 | api "github.com/panjf2000/goproxy/interface" 10 | "github.com/panjf2000/goproxy/tool" 11 | ) 12 | 13 | type CacheReplacementPolicy int 14 | 15 | const ( 16 | LRU = iota 17 | LFU 18 | ) 19 | 20 | type MemConnCachePool struct { 21 | cache gcache.Cache 22 | } 23 | 24 | func NewMemCachePool(cap int, crp CacheReplacementPolicy) *MemConnCachePool { 25 | var gc gcache.Cache 26 | switch crp { 27 | case LFU: 28 | gc = gcache.New(cap).LFU().Build() 29 | default: 30 | gc = gcache.New(cap).LRU().Build() 31 | 32 | } 33 | return &MemConnCachePool{cache: gc} 34 | 35 | } 36 | 37 | func (c *MemConnCachePool) Get(uri string) api.Cache { 38 | if respCache := c.get(tool.MD5Uri(uri)); respCache != nil { 39 | return respCache 40 | } 41 | return nil 42 | } 43 | 44 | func (c *MemConnCachePool) get(md5Uri string) *HttpCache { 45 | value, err := c.cache.Get(md5Uri) 46 | if err != nil { 47 | return nil 48 | } 49 | b := value.([]byte) 50 | if len(b) == 0 { 51 | return nil 52 | } 53 | respCache := new(HttpCache) 54 | _ = json.Unmarshal(b, respCache) 55 | 56 | return respCache 57 | } 58 | 59 | func (c *MemConnCachePool) Delete(uri string) { 60 | c.delete(tool.MD5Uri(uri)) 61 | } 62 | 63 | func (c *MemConnCachePool) delete(md5Uri string) { 64 | c.cache.Remove(md5Uri) 65 | return 66 | } 67 | 68 | func (c *MemConnCachePool) CheckAndStore(uri string, req *http.Request, resp *http.Response) { 69 | if !IsReqCache(req) || !IsRespCache(resp) { 70 | return 71 | } 72 | respCache := NewCacheResp(resp) 73 | 74 | if respCache == nil { 75 | return 76 | } 77 | 78 | md5Uri := tool.MD5Uri(uri) 79 | b, err := json.Marshal(respCache) 80 | if err != nil { 81 | return 82 | } 83 | 84 | if err := c.cache.SetWithExpire(md5Uri, b, time.Duration(respCache.maxAge)*time.Second); err != nil { 85 | return 86 | } 87 | 88 | } 89 | 90 | //func (c *MemConnCachePool) Clear(d time.Duration) { 91 | // 92 | //} 93 | -------------------------------------------------------------------------------- /cache/redis_cache_pool.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | "time" 7 | 8 | "github.com/gomodule/redigo/redis" 9 | "github.com/panjf2000/goproxy/interface" 10 | "github.com/panjf2000/goproxy/tool" 11 | ) 12 | 13 | type RedisConnCachePool struct { 14 | pool *redis.Pool 15 | } 16 | 17 | func NewRedisCachePool(address, password string, idleTimeout, cap, maxIdle int) *RedisConnCachePool { 18 | redisPool := &redis.Pool{ 19 | MaxActive: cap, 20 | MaxIdle: maxIdle, 21 | IdleTimeout: time.Duration(idleTimeout) * time.Second, 22 | Wait: true, 23 | Dial: func() (redis.Conn, error) { 24 | conn, err := redis.Dial("tcp", address) 25 | if err != nil { 26 | return nil, err 27 | } 28 | if password != "" { 29 | if _, err := conn.Do("AUTH", password); err != nil { 30 | _ = conn.Close() 31 | return nil, err 32 | } 33 | } 34 | return conn, err 35 | }, 36 | TestOnBorrow: func(c redis.Conn, t time.Time) error { 37 | _, err := c.Do("PING") 38 | if err != nil { 39 | panic(err) 40 | } 41 | return err 42 | 43 | }, 44 | } 45 | return &RedisConnCachePool{pool: redisPool} 46 | 47 | } 48 | 49 | func (c *RedisConnCachePool) Get(uri string) api.Cache { 50 | if respCache := c.get(tool.MD5Uri(uri)); respCache != nil { 51 | return respCache 52 | } 53 | return nil 54 | } 55 | 56 | func (c *RedisConnCachePool) get(md5Uri string) *HttpCache { 57 | conn := c.pool.Get() 58 | defer conn.Close() 59 | 60 | b, err := redis.Bytes(conn.Do("GET", md5Uri)) 61 | if err != nil || len(b) == 0 { 62 | return nil 63 | } 64 | respCache := new(HttpCache) 65 | _ = json.Unmarshal(b, respCache) 66 | return respCache 67 | } 68 | 69 | func (c *RedisConnCachePool) Delete(uri string) { 70 | c.delete(tool.MD5Uri(uri)) 71 | } 72 | 73 | func (c *RedisConnCachePool) delete(md5Uri string) { 74 | conn := c.pool.Get() 75 | defer conn.Close() 76 | 77 | if _, err := conn.Do("DEL", md5Uri); err != nil { 78 | return 79 | } 80 | return 81 | } 82 | 83 | func (c *RedisConnCachePool) CheckAndStore(uri string, req *http.Request, resp *http.Response) { 84 | if !IsReqCache(req) || !IsRespCache(resp) { 85 | return 86 | } 87 | respCache := NewCacheResp(resp) 88 | 89 | if respCache == nil { 90 | return 91 | } 92 | 93 | md5Uri := tool.MD5Uri(uri) 94 | b, err := json.Marshal(respCache) 95 | if err != nil { 96 | return 97 | } 98 | 99 | conn := c.pool.Get() 100 | defer conn.Close() 101 | 102 | _, err = conn.Do("MULTI") 103 | _, _ = conn.Do("SET", md5Uri, b) 104 | _, _ = conn.Do("EXPIRE", md5Uri, respCache.maxAge) 105 | _, err = conn.Do("EXEC") 106 | if err != nil { 107 | return 108 | } 109 | 110 | } 111 | 112 | //func (c *RedisConnCachePool) Clear(d time.Duration) { 113 | // 114 | //} 115 | -------------------------------------------------------------------------------- /cache/util.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | // IsReqCache checks whether request ask to be stored as cache 10 | func IsReqCache(req *http.Request) bool { 11 | log.Printf("http request header:%v", req.Header) 12 | cacheControl := req.Header.Get("Cache-Control") 13 | contentType := req.Header.Get("Content-Type") 14 | if cacheControl == "" && contentType == "" { 15 | return true 16 | } else if len(cacheControl) > 0 { 17 | if strings.Index(cacheControl, "private") != -1 || 18 | strings.Index(cacheControl, "no-cache") != -1 || 19 | strings.Index(cacheControl, "no-store") != -1 || 20 | strings.Index(cacheControl, "must-revalidate") != -1 || 21 | (strings.Index(cacheControl, "max-age") == -1 && 22 | strings.Index(cacheControl, "s-maxage") == -1 && 23 | req.Header.Get("Etag") == "" && 24 | req.Header.Get("Last-Modified") == "" && 25 | (req.Header.Get("Expires") == "" || req.Header.Get("Expires") == "0")) { 26 | return false 27 | } 28 | 29 | } else if len(contentType) > 0 { 30 | if strings.Index(contentType, "video") != -1 || 31 | strings.Index(contentType, "image") != -1 || 32 | strings.Index(contentType, "audio") != -1 { 33 | return false 34 | } 35 | 36 | } 37 | return true 38 | } 39 | 40 | // IsRespCache checks whether response can be stored as cache 41 | func IsRespCache(resp *http.Response) bool { 42 | log.Printf("http response header:%v", resp.Header) 43 | cacheControl := resp.Header.Get("Cache-Control") 44 | contentType := resp.Header.Get("Content-Type") 45 | if cacheControl == "" && contentType == "" { 46 | return true 47 | } else if len(cacheControl) > 0 { 48 | if strings.Index(cacheControl, "private") != -1 || 49 | strings.Index(cacheControl, "no-cache") != -1 || 50 | strings.Index(cacheControl, "no-store") != -1 || 51 | strings.Index(cacheControl, "must-revalidate") != -1 || 52 | (strings.Index(cacheControl, "max-age") == -1 && 53 | strings.Index(cacheControl, "s-maxage") == -1 && 54 | resp.Header.Get("Etag") == "" && 55 | resp.Header.Get("Last-Modified") == "" && 56 | (resp.Header.Get("Expires") == "" || resp.Header.Get("Expires") == "0")) { 57 | return false 58 | } 59 | 60 | } else if len(contentType) > 0 { 61 | if strings.Index(contentType, "video") != -1 || 62 | strings.Index(contentType, "image") != -1 || 63 | strings.Index(contentType, "audio") != -1 { 64 | return false 65 | } 66 | 67 | } 68 | return true 69 | } 70 | -------------------------------------------------------------------------------- /config/cfg.toml: -------------------------------------------------------------------------------- 1 | # toml file for goproxy 2 | 3 | title = "TOML config for goproxy" 4 | 5 | [server] 6 | port = ":80" 7 | reverse = true 8 | proxy_pass = ["127.0.0.1:6000", "127.0.0.1:7000", "127.0.0.1:8000", "127.0.0.1:9000"] 9 | inverse_mode = 2 # 0 - round-robin, 1 - power of two choices(p2c), 2 - consistent hashing, 3 - consistent hashing with bounded loads 10 | auth = false 11 | cache = true 12 | cache_timeout = 60 13 | cache_type = "redis" 14 | log = 1 15 | log_path = "./logs" 16 | user = { agent = "proxy" } 17 | http_read_timeout = 10 18 | http_write_timeout = 10 19 | 20 | [redis] 21 | redis_host = "localhost:6379" 22 | redis_pass = "" 23 | max_idle = 5 24 | idle_timeout = 10 25 | max_active = 10 26 | 27 | [mem] 28 | capacity = 1000 29 | cache_replacement_policy = "LRU" 30 | 31 | 32 | -------------------------------------------------------------------------------- /config/init.go: -------------------------------------------------------------------------------- 1 | /* 2 | @version: 1.0 3 | @author: allanpan 4 | @license: Apache Licence 5 | @contact: panjf2000@gmail.com 6 | @site: 7 | @file: init.go 8 | @time: 2018/2/11 16:40 9 | @tag: 1,2,3 10 | @todo: ... 11 | */ 12 | package config 13 | 14 | import ( 15 | "fmt" 16 | "log" 17 | 18 | "github.com/fsnotify/fsnotify" 19 | "github.com/spf13/viper" 20 | ) 21 | 22 | //RuntimeViper runtime config 23 | var RuntimeViper *viper.Viper 24 | 25 | func init() { 26 | RuntimeViper = viper.New() 27 | RuntimeViper.SetConfigType("toml") 28 | RuntimeViper.SetConfigName("cfg") // name of config file (without extension) 29 | RuntimeViper.AddConfigPath("/etc/proxy/") // path to look for the config file in 30 | RuntimeViper.AddConfigPath("./config/") // optionally look for config in the working directory 31 | if err := RuntimeViper.ReadInConfig(); err != nil { 32 | panic(fmt.Errorf("fatal error config file: %s", err)) 33 | } 34 | RuntimeViper.WatchConfig() 35 | RuntimeViper.OnConfigChange(func(e fsnotify.Event) { 36 | log.Printf("config file changed:%s", e.Name) 37 | }) 38 | } 39 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/panjf2000/goproxy 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/BurntSushi/toml v0.3.1 // indirect 7 | github.com/Sirupsen/logrus v1.0.5 8 | github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833 9 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484 // indirect 10 | github.com/fsnotify/fsnotify v1.4.9 11 | github.com/gomodule/redigo v2.0.0+incompatible 12 | github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce // indirect 13 | github.com/lafikl/liblb v0.0.0-20170702133218-2321f9d41430 14 | github.com/magiconair/properties v0.0.0-20180217134545-2c9e95027885 // indirect 15 | github.com/mitchellh/mapstructure v0.0.0-20180220230111-00c29f56e238 // indirect 16 | github.com/parnurzeal/gorequest v0.2.16 17 | github.com/pelletier/go-toml v0.0.0-20180323185243-66540cf1fcd2 // indirect 18 | github.com/pkg/errors v0.8.1 // indirect 19 | github.com/sirupsen/logrus v1.4.2 // indirect 20 | github.com/smartystreets/goconvey v1.6.4 // indirect 21 | github.com/spf13/afero v1.1.0 // indirect 22 | github.com/spf13/cast v1.2.0 // indirect 23 | github.com/spf13/jwalterweatherman v0.0.0-20180109140146-7c0cea34c8ec // indirect 24 | github.com/spf13/pflag v1.0.1 // indirect 25 | github.com/spf13/viper v1.0.2 26 | github.com/zehuamama/balancer v0.2.0 27 | gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect 28 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect 29 | moul.io/http2curl v1.0.0 // indirect 30 | ) 31 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/Sirupsen/logrus v1.0.5 h1:447dy9LxSj+Iaa2uN3yoFHOzU9yJcJYiQPtNz8OXtv0= 4 | github.com/Sirupsen/logrus v1.0.5/go.mod h1:rmk17hk6i8ZSAJkSDa7nOxamrG+SP4P0mm+DAvExv4U= 5 | github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833 h1:yCfXxYaelOyqnia8F/Yng47qhmfC9nKTRIbYRrRueq4= 6 | github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833/go.mod h1:8c4/i2VlovMO2gBnHGQPN5EJw+H0lx1u/5p+cgsXtCk= 7 | github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= 8 | github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= 9 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= 10 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 13 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484 h1:pEtiCjIXx3RvGjlUJuCNxNOw0MNblyR9Wi+vJGBFh+8= 14 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= 15 | github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 h1:dWB6v3RcOy03t/bUadywsbyrQwCqZeNIEX6M1OtSZOM= 16 | github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= 17 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 18 | github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= 19 | github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= 20 | github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= 21 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 22 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 23 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 24 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 25 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 26 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 27 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 28 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 29 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 30 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 31 | github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= 32 | github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= 33 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 34 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 35 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 36 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 37 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 38 | github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= 39 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= 40 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 41 | github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= 42 | github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce h1:xdsDDbiBDQTKASoGEZ+pEmF1OnWuu8AQ9I8iNbHNeno= 43 | github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= 44 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 45 | github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= 46 | github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= 47 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= 48 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 49 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 50 | github.com/lafikl/consistent v0.0.0-20220512074542-bdd3606bfc3e h1:DuhzIzxOx3aJ0j4enY7SQ9bvulrT/XjkGAqiychfavc= 51 | github.com/lafikl/consistent v0.0.0-20220512074542-bdd3606bfc3e/go.mod h1:JmowInJuqa6EpSut8NSMAZtlvK9uL+8Q1P7tyew5rQY= 52 | github.com/lafikl/liblb v0.0.0-20170702133218-2321f9d41430 h1:9bf1p3tctiWc45sNBBrhAzczaSgWDFFXne+gKrVhrHM= 53 | github.com/lafikl/liblb v0.0.0-20170702133218-2321f9d41430/go.mod h1:K2tTs/mGTGApM8cP9GhuQYn3L7k8xPdnMPXXGrWOS4E= 54 | github.com/magiconair/properties v0.0.0-20180217134545-2c9e95027885 h1:HWxJJvF+QceKcql4r9PC93NtMEgEBfBxlQrZPvbcQvs= 55 | github.com/magiconair/properties v0.0.0-20180217134545-2c9e95027885/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= 56 | github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 h1:lYpkrQH5ajf0OXOcUbGjvZxxijuBwbbmlSxLiuofa+g= 57 | github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= 58 | github.com/mitchellh/mapstructure v0.0.0-20180220230111-00c29f56e238 h1:+MZW2uvHgN8kYvksEN3f7eFL2wpzk0GxmlFsMybWc7E= 59 | github.com/mitchellh/mapstructure v0.0.0-20180220230111-00c29f56e238/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= 60 | github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= 61 | github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= 62 | github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= 63 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 64 | github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= 65 | github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= 66 | github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= 67 | github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= 68 | github.com/onsi/ginkgo/v2 v2.1.3 h1:e/3Cwtogj0HA+25nMP1jCMDIf8RtRYbGwGGuBIFztkc= 69 | github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= 70 | github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= 71 | github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= 72 | github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= 73 | github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= 74 | github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= 75 | github.com/parnurzeal/gorequest v0.2.16 h1:T/5x+/4BT+nj+3eSknXmCTnEVGSzFzPGdpqmUVVZXHQ= 76 | github.com/parnurzeal/gorequest v0.2.16/go.mod h1:3Kh2QUMJoqw3icWAecsyzkpY7UzRfDhbRdTjtNwNiUE= 77 | github.com/pelletier/go-toml v0.0.0-20180323185243-66540cf1fcd2 h1:BR4UJUSGxC9crpVRG7k28Mq2HRB7lO2A3/ghfWl0R+M= 78 | github.com/pelletier/go-toml v0.0.0-20180323185243-66540cf1fcd2/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= 79 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 80 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 81 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 82 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 83 | github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc= 84 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= 85 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 86 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= 87 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= 88 | github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= 89 | github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= 90 | github.com/spf13/afero v1.1.0 h1:bopulORc2JeYaxfHLvJa5NzxviA9PoWhpiiJkru7Ji4= 91 | github.com/spf13/afero v1.1.0/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= 92 | github.com/spf13/cast v1.2.0 h1:HHl1DSRbEQN2i8tJmtS6ViPyHx35+p51amrdsiTCrkg= 93 | github.com/spf13/cast v1.2.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg= 94 | github.com/spf13/jwalterweatherman v0.0.0-20180109140146-7c0cea34c8ec h1:2ZXvIUGghLpdTVHR1UfvfrzoVlZaE/yOWC5LueIHZig= 95 | github.com/spf13/jwalterweatherman v0.0.0-20180109140146-7c0cea34c8ec/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= 96 | github.com/spf13/pflag v1.0.1 h1:aCvUg6QPl3ibpQUxyLkrEkCHtPqYJL4x9AuhqVqFis4= 97 | github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 98 | github.com/spf13/viper v1.0.2 h1:Ncr3ZIuJn322w2k1qmzXDnkLAdQMlJqBa9kfAH+irso= 99 | github.com/spf13/viper v1.0.2/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM= 100 | github.com/starwander/GoFibonacciHeap v0.0.0-20190508061137-ba2e4f01000a h1:HxQEVn2dC2DyalPmsBVsTRsB05UpBmbgZV2a939iEwE= 101 | github.com/starwander/GoFibonacciHeap v0.0.0-20190508061137-ba2e4f01000a/go.mod h1:0UZshEHv45sVxpYdRE55cbIVuvbXD3+liaXyrgm1Mr4= 102 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 103 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 104 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 105 | github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= 106 | github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= 107 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 108 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 109 | github.com/zehuamama/balancer v0.2.0 h1:X2Wz2tqitXBwnLevZotjwNmDCqLz4AkKvdr1KCWoj68= 110 | github.com/zehuamama/balancer v0.2.0/go.mod h1:wINeqszXXc4aKQiM63I2fLmecEz0xUB2rqAQL9uaSoM= 111 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 112 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 113 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= 114 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 115 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 116 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 117 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 118 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 119 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 120 | golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 121 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 122 | golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= 123 | golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc= 124 | golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= 125 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 126 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 127 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 128 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 129 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 130 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 131 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 132 | golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 133 | golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 134 | golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 135 | golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 136 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 137 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 138 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 139 | golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 140 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 141 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 142 | golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= 143 | golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 144 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 145 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 146 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 147 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 148 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 149 | golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= 150 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 151 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 152 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 153 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 154 | golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= 155 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 156 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 157 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 158 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 159 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 160 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 161 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 162 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 163 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 164 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 165 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 166 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 167 | google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk= 168 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 169 | gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo= 170 | gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= 171 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 172 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 173 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 174 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0= 175 | gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= 176 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 177 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 178 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 179 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 180 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 181 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 182 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 183 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 184 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 185 | moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8= 186 | moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE= 187 | -------------------------------------------------------------------------------- /handler/auth.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "encoding/base64" 5 | "errors" 6 | "log" 7 | "net/http" 8 | "strings" 9 | 10 | "github.com/panjf2000/goproxy/config" 11 | ) 12 | 13 | //Auth provides basic authorization for proxy server. 14 | func (ps *ProxyServer) Auth(rw http.ResponseWriter, req *http.Request) bool { 15 | var err error 16 | if config.RuntimeViper.GetBool("server.auth") { 17 | // authentication for the proxy server 18 | if ps.Browser, err = ps.auth(rw, req); err != nil { 19 | //ps.Browser = "Anonymous" 20 | return false 21 | } 22 | return true 23 | } 24 | ps.Browser = "Anonymous" 25 | return true 26 | 27 | } 28 | 29 | //Auth provides basic authorization for proxy server. 30 | func (ps *ProxyServer) auth(rw http.ResponseWriter, req *http.Request) (string, error) { 31 | 32 | auth := req.Header.Get("Proxy-Authorization") 33 | auth = strings.Replace(auth, "Basic ", "", 1) 34 | 35 | if auth == "" { 36 | NeedAuth(rw) 37 | return "", errors.New("need proxy authorization") 38 | } 39 | data, err := base64.StdEncoding.DecodeString(auth) 40 | if err != nil { 41 | return "", errors.New("fail to decoding Proxy-Authorization") 42 | } 43 | 44 | var user, password string 45 | 46 | userPasswordPair := strings.Split(string(data), ":") 47 | if len(userPasswordPair) != 2 { 48 | NeedAuth(rw) 49 | return "", errors.New("fail to log in") 50 | } 51 | user = userPasswordPair[0] 52 | password = userPasswordPair[1] 53 | if Verify(user, password) == false { 54 | NeedAuth(rw) 55 | return "", errors.New("fail to log in") 56 | } 57 | return user, nil 58 | } 59 | 60 | func NeedAuth(rw http.ResponseWriter) { 61 | hj, _ := rw.(http.Hijacker) 62 | Client, _, err := hj.Hijack() 63 | defer Client.Close() 64 | if err != nil { 65 | log.Printf("fail to get TCP connection of client in auth, %v", err) 66 | } 67 | _, _ = Client.Write(HTTP407) 68 | } 69 | 70 | // Verify verifies username and password 71 | func Verify(user, password string) bool { 72 | if user != "" && password != "" { 73 | if pass, ok := config.RuntimeViper.GetStringMapString("server.user")[user]; ok && pass == password { 74 | return true 75 | } 76 | } 77 | return false 78 | } 79 | -------------------------------------------------------------------------------- /handler/cache.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "net/http" 8 | 9 | "github.com/panjf2000/goproxy/interface" 10 | ) 11 | 12 | var cachePool api.CachePool 13 | 14 | func RegisterCachePool(c api.CachePool) { 15 | cachePool = c 16 | } 17 | 18 | //CacheHandler handles "Get" request 19 | func (ps *ProxyServer) CacheHandler(rw http.ResponseWriter, req *http.Request) { 20 | 21 | uri := req.RequestURI 22 | 23 | c := cachePool.Get(uri) 24 | 25 | if c != nil { 26 | if c.Verify() { 27 | _, _ = c.WriteTo(rw) 28 | return 29 | } 30 | cachePool.Delete(uri) 31 | } 32 | 33 | RmProxyHeaders(req) 34 | resp, err := ps.Travel.RoundTrip(req) 35 | if err != nil { 36 | http.Error(rw, err.Error(), 500) 37 | return 38 | } 39 | defer resp.Body.Close() 40 | 41 | httpResp := new(http.Response) 42 | *httpResp = *resp 43 | CopyResponse(httpResp, resp) 44 | 45 | go cachePool.CheckAndStore(uri, req, httpResp) 46 | 47 | ClearHeaders(rw.Header()) 48 | CopyHeaders(rw.Header(), resp.Header) 49 | 50 | rw.WriteHeader(resp.StatusCode) // writes the response status. 51 | 52 | _, err = io.Copy(rw, resp.Body) 53 | if err != nil && err != io.EOF { 54 | return 55 | } 56 | } 57 | 58 | func CopyResponse(dest *http.Response, src *http.Response) { 59 | *dest = *src 60 | var bodyBytes []byte 61 | 62 | if src.Body != nil { 63 | bodyBytes, _ = ioutil.ReadAll(src.Body) 64 | } 65 | 66 | // Restores the io.ReadCloser to its original state 67 | src.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) 68 | dest.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) 69 | } 70 | -------------------------------------------------------------------------------- /handler/headers.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | // CopyHeaders copies headers from source to destination. 8 | // Nothing would be returned. 9 | func CopyHeaders(dst, src http.Header) { 10 | for key, values := range src { 11 | for _, value := range values { 12 | dst.Add(key, value) 13 | } 14 | } 15 | } 16 | 17 | // ClearHeaders clears headers. 18 | func ClearHeaders(headers http.Header) { 19 | for key := range headers { 20 | headers.Del(key) 21 | } 22 | } 23 | 24 | // RmProxyHeaders removes Hop-by-hop headers. 25 | func RmProxyHeaders(req *http.Request) { 26 | req.RequestURI = "" 27 | req.Header.Del("Proxy-Connection") 28 | req.Header.Del("Connection") 29 | req.Header.Del("Keep-Alive") 30 | req.Header.Del("Proxy-Authenticate") 31 | req.Header.Del("Proxy-Authorization") 32 | req.Header.Del("TE") 33 | req.Header.Del("Trailers") 34 | req.Header.Del("Transfer-Encoding") 35 | req.Header.Del("Upgrade") 36 | } 37 | -------------------------------------------------------------------------------- /handler/proxy.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | _ "bufio" 5 | "io" 6 | "net" 7 | "net/http" 8 | "time" 9 | 10 | "github.com/panjf2000/goproxy/cache" 11 | "github.com/panjf2000/goproxy/config" 12 | ) 13 | 14 | type ProxyServer struct { 15 | // Browser records user's name 16 | Travel *http.Transport 17 | Browser string 18 | } 19 | 20 | // NewProxyServer returns a new proxy server. 21 | func NewProxyServer() *http.Server { 22 | if config.RuntimeViper.GetBool("server.cache") { 23 | var cachePoolType cache.CachePoolType 24 | if config.RuntimeViper.GetString("server.cache_type") == "redis" { 25 | cachePoolType = cache.Redis 26 | } 27 | RegisterCachePool(cache.NewCachePool(cachePoolType)) 28 | } 29 | 30 | return &http.Server{ 31 | Addr: config.RuntimeViper.GetString("server.port"), 32 | Handler: &ProxyServer{Travel: &http.Transport{Proxy: http.ProxyFromEnvironment, DisableKeepAlives: false}}, 33 | ReadTimeout: time.Duration(config.RuntimeViper.GetInt("server.http_read_timeout")) * time.Second, 34 | WriteTimeout: time.Duration(config.RuntimeViper.GetInt("server.http_write_timeout")) * time.Second, 35 | MaxHeaderBytes: 1 << 20, 36 | } 37 | } 38 | 39 | //ServeHTTP will be automatically called by system. 40 | //ProxyServer implements the Handler interface which need ServeHTTP. 41 | func (ps *ProxyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { 42 | defer func() { 43 | if err := recover(); err != nil { 44 | rw.WriteHeader(http.StatusInternalServerError) 45 | } 46 | }() 47 | if !ps.Auth(rw, req) { 48 | return 49 | } 50 | 51 | ps.LoadBalancing(req) 52 | defer ps.Done(req) 53 | 54 | if req.Method == "CONNECT" { 55 | ps.HttpsHandler(rw, req) 56 | } else if req.Method == "GET" && config.RuntimeViper.GetBool("server.cache") { 57 | ps.CacheHandler(rw, req) 58 | } else { 59 | ps.HttpHandler(rw, req) 60 | } 61 | } 62 | 63 | //HttpHandler handles http connections. 64 | func (ps *ProxyServer) HttpHandler(rw http.ResponseWriter, req *http.Request) { 65 | RmProxyHeaders(req) 66 | 67 | resp, err := ps.Travel.RoundTrip(req) 68 | if err != nil { 69 | http.Error(rw, err.Error(), 500) 70 | return 71 | } 72 | defer resp.Body.Close() 73 | 74 | ClearHeaders(rw.Header()) 75 | CopyHeaders(rw.Header(), resp.Header) 76 | 77 | rw.WriteHeader(resp.StatusCode) // writes the response status. 78 | 79 | _, err = io.Copy(rw, resp.Body) 80 | if err != nil && err != io.EOF { 81 | return 82 | } 83 | } 84 | 85 | 86 | // HttpsHandler handles any connection which needs "connect" method. 87 | func (ps *ProxyServer) HttpsHandler(rw http.ResponseWriter, req *http.Request) { 88 | hj, _ := rw.(http.Hijacker) 89 | Client, _, err := hj.Hijack() // gets the tcp connection between client and server. 90 | if err != nil { 91 | http.Error(rw, "Failed", http.StatusBadRequest) 92 | return 93 | } 94 | 95 | Remote, err := net.Dial("tcp", req.URL.Host) // establishes the tcp connection between the client and server. 96 | if err != nil { 97 | http.Error(rw, "Failed", http.StatusBadGateway) 98 | return 99 | } 100 | 101 | _, _ = Client.Write(HTTP200) 102 | 103 | go copyRemoteToClient(ps.Browser, Remote, Client) 104 | go copyRemoteToClient(ps.Browser, Client, Remote) 105 | } 106 | 107 | func copyRemoteToClient(User string, Remote, Client net.Conn) { 108 | defer func() { 109 | _ = Remote.Close() 110 | _ = Client.Close() 111 | }() 112 | 113 | _, err := io.Copy(Remote, Client) 114 | if err != nil && err != io.EOF { 115 | return 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /handler/rebalance.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "math/rand" 5 | "net" 6 | "net/http" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/lafikl/liblb/r2" 11 | "github.com/panjf2000/goproxy/config" 12 | "github.com/panjf2000/goproxy/tool" 13 | "github.com/zehuamama/balancer/balancer" 14 | ) 15 | 16 | var r2LB = r2.New() 17 | var p2cLB balancer.Balancer 18 | var boundedLB balancer.Balancer 19 | var leastLB balancer.Balancer 20 | var backendServers map[string]int 21 | var serverNodes []string 22 | 23 | func init() { 24 | backendServers = make(map[string]int) 25 | proxyPasses := config.RuntimeViper.GetStringSlice("server.proxy_pass") 26 | for _, addr := range proxyPasses { 27 | if tool.IsHost(addr) { 28 | backendServers[addr] = 1 29 | serverNodes = append(serverNodes, addr) 30 | } else if tool.IsWeightHost(addr) { 31 | hostPair := strings.Split(addr, "^") 32 | host := hostPair[0] 33 | weight, _ := strconv.Atoi(hostPair[1]) 34 | backendServers[host] = weight 35 | serverNodes = append(serverNodes, host) 36 | } 37 | } 38 | 39 | for host, weight := range backendServers { 40 | r2LB.AddWeight(host, weight) 41 | } 42 | p2cLB, _ = balancer.Build(balancer.P2CBalancer, serverNodes) 43 | boundedLB, _ = balancer.Build(balancer.BoundedBalancer, serverNodes) 44 | leastLB, _ = balancer.Build(balancer.LeastLoadBalancer, serverNodes) 45 | } 46 | 47 | func (ps *ProxyServer) Done(req *http.Request) { 48 | switch config.RuntimeViper.GetInt("server.reverse_mode") { 49 | case 2: 50 | p2cLB.Done(req.Host) 51 | case 4: 52 | boundedLB.Done(req.Host) 53 | case 5: 54 | leastLB.Done(req.Host) 55 | default: 56 | } 57 | } 58 | 59 | //LoadBalancing handles request for reverse proxy. 60 | func (ps *ProxyServer) LoadBalancing(req *http.Request) { 61 | if config.RuntimeViper.GetBool("server.reverse") { 62 | ps.loadBalancing(req) 63 | } 64 | } 65 | 66 | //loadBalancing handles request for reverse proxy. 67 | func (ps *ProxyServer) loadBalancing(req *http.Request) { 68 | var proxyHost string 69 | mode := config.RuntimeViper.GetInt("server.reverse_mode") 70 | switch mode { 71 | case 0: 72 | // Selects a back-end server base on randomized algorithm. 73 | index := tool.GenRandom(0, len(serverNodes), 1)[0] 74 | proxyHost = serverNodes[index] 75 | case 1: 76 | // Selects a back-end server base on polling algorithm which supports weight. 77 | proxyHost, _ = r2LB.Balance() 78 | case 2: 79 | // Selects a back-end server base on power of two choices (p2c) algorithm. 80 | proxyHost, _ = p2cLB.Balance(req.RemoteAddr) 81 | case 3: 82 | // Calculates a HashCode using the client ip and forwards this request to a back-end server base on HashCode with 83 | // weights in config file. 84 | ring := tool.NewWithWeights(backendServers) 85 | if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil { 86 | proxyHost, _ = ring.GetNode(clientIP) 87 | } else { 88 | proxyHost = serverNodes[rand.Intn(len(serverNodes))] 89 | } 90 | case 4: 91 | // Selects a back-end server base on Bound Consistent Hashing algorithm. 92 | proxyHost, _ = boundedLB.Balance(req.RemoteAddr) 93 | case 5: 94 | // Selects a back-end server base on Least Load algorithm. 95 | proxyHost, _ = leastLB.Balance("") 96 | default: 97 | // Selects a back-end server base on randomized algorithm. 98 | index := tool.GenRandom(0, len(serverNodes), 1)[0] 99 | proxyHost = serverNodes[index] 100 | 101 | } 102 | req.Host = proxyHost 103 | req.URL.Host = proxyHost 104 | req.URL.Scheme = "http" 105 | } 106 | -------------------------------------------------------------------------------- /handler/status.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | var ( 4 | HTTP200 = []byte("HTTP/1.1 200 Connection Established\r\n\r\n") 5 | HTTP407 = []byte("HTTP/1.1 407 Proxy Authorization Required\r\nProxy-Authenticate: Basic realm=\"Access to internal site\"\r\n\r\n") 6 | ) 7 | -------------------------------------------------------------------------------- /interface/cacher.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | type CachePool interface { 8 | Get(uri string) Cache 9 | Delete(uri string) 10 | CheckAndStore(uri string, req *http.Request, resp *http.Response) 11 | //Clear(d time.Duration) 12 | } 13 | 14 | type Cache interface { 15 | Verify() bool 16 | WriteTo(rw http.ResponseWriter) (int, error) 17 | } 18 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | log "github.com/Sirupsen/logrus" 5 | "github.com/panjf2000/goproxy/config" 6 | "github.com/panjf2000/goproxy/handler" 7 | _ "net/http" 8 | ) 9 | 10 | func main() { 11 | goproxy := handler.NewProxyServer() 12 | 13 | log.Infof("Start the proxy server in port:%s", config.RuntimeViper.GetString("server.port")) 14 | log.Fatal(goproxy.ListenAndServe()) 15 | } 16 | -------------------------------------------------------------------------------- /test/config/cfg.toml: -------------------------------------------------------------------------------- 1 | # toml file for goproxy 2 | 3 | title = "TOML config for goproxy" 4 | 5 | [server] 6 | port = ":8080" 7 | reverse = true 8 | proxy_pass = ["127.0.0.1:6000"] 9 | # 0 - random, 1 - loop, 2 - power of two choices(p2c), 3 - hash, 4 - consistent hashing 10 | inverse_mode = 2 11 | auth = false 12 | cache = true 13 | cache_timeout = 60 14 | cache_type = "redis" 15 | log = 1 16 | log_path = "./logs" 17 | user = { agent = "proxy" } 18 | http_read_timeout = 10 19 | http_write_timeout = 10 20 | 21 | [redis] 22 | redis_host = "localhost:6379" 23 | redis_pass = "" 24 | max_idle = 5 25 | idle_timeout = 10 26 | max_active = 10 27 | 28 | [mem] 29 | capacity = 1000 30 | cache_replacement_policy = "LRU" 31 | 32 | 33 | -------------------------------------------------------------------------------- /test/server_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | @version: 1.0 3 | @author: allanpan 4 | @license: Apache Licence 5 | @contact: panjf2000@gmail.com 6 | @site: 7 | @file: server_test.go 8 | @time: 2018/7/4 15:01 9 | @tag: 1,2,3 10 | @todo: ... 11 | */ 12 | package test 13 | 14 | import ( 15 | "encoding/json" 16 | "fmt" 17 | "io/ioutil" 18 | "log" 19 | "net/http" 20 | "testing" 21 | "time" 22 | 23 | "github.com/panjf2000/goproxy/config" 24 | "github.com/panjf2000/goproxy/handler" 25 | "github.com/parnurzeal/gorequest" 26 | ) 27 | 28 | func init() { 29 | http.HandleFunc("/test_proxy", revRequest) 30 | for _, addr := range config.RuntimeViper.GetStringSlice("server.proxy_pass") { 31 | go func() { 32 | log.Fatalln(http.ListenAndServe(addr, nil)) 33 | }() 34 | } 35 | 36 | server := handler.NewProxyServer() 37 | go func() { 38 | log.Fatalln(server.ListenAndServe()) 39 | }() 40 | time.Sleep(5 * time.Second) 41 | } 42 | 43 | func revRequest(w http.ResponseWriter, r *http.Request) { 44 | switch r.Method { 45 | case "GET": 46 | fmt.Fprint(w, "{GET} return: "+r.FormValue("get_req")) 47 | case "POST": 48 | b, _ := ioutil.ReadAll(r.Body) 49 | defer r.Body.Close() 50 | var m map[string]interface{} 51 | json.Unmarshal(b, &m) 52 | postParam, _ := m["post_req"].(string) 53 | fmt.Fprint(w, "{POST} return: "+postParam) 54 | default: 55 | fmt.Fprint(w, "defalut return: nil") 56 | } 57 | } 58 | 59 | func TestServer(t *testing.T) { 60 | for range []int{1, 2, 3, 4, 5} { 61 | resp, body, errs := gorequest.New().Get("http://127.0.0.1:8080/test_proxy").Param("get_req", "Hello World!").End() 62 | if errs != nil { 63 | t.Fatal(errs) 64 | } 65 | if resp.StatusCode != http.StatusOK { 66 | t.Fatalf("response status err, status code:%d\n", resp.StatusCode) 67 | } 68 | t.Logf("{GET} response: %s\n", body) 69 | } 70 | 71 | resp, body, errs := gorequest.New().Post("http://127.0.0.1:8080/test_proxy").Send(`{"post_req": "Hello World!"}`).End() 72 | 73 | if errs != nil { 74 | t.Fatal(errs) 75 | } 76 | if resp.StatusCode != http.StatusOK { 77 | t.Fatalf("response status err, status code:%d\n", resp.StatusCode) 78 | } 79 | t.Logf("{POST} response: %s\n", body) 80 | } 81 | -------------------------------------------------------------------------------- /tool/hashring.go: -------------------------------------------------------------------------------- 1 | package tool 2 | 3 | import ( 4 | "crypto/md5" 5 | "fmt" 6 | "math" 7 | "sort" 8 | ) 9 | 10 | type HashKey uint32 11 | type HashKeyOrder []HashKey 12 | 13 | func (h HashKeyOrder) Len() int { return len(h) } 14 | func (h HashKeyOrder) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 15 | func (h HashKeyOrder) Less(i, j int) bool { return h[i] < h[j] } 16 | 17 | type HashRing struct { 18 | ring map[HashKey]string 19 | sortedKeys []HashKey 20 | nodes []string 21 | weights map[string]int 22 | } 23 | 24 | func New(nodes []string) *HashRing { 25 | hashRing := &HashRing{ 26 | ring: make(map[HashKey]string), 27 | sortedKeys: make([]HashKey, 0), 28 | nodes: nodes, 29 | weights: make(map[string]int), 30 | } 31 | hashRing.generateCircle() 32 | return hashRing 33 | } 34 | 35 | func NewWithWeights(weights map[string]int) *HashRing { 36 | nodes := make([]string, 0, len(weights)) 37 | for node := range weights { 38 | nodes = append(nodes, node) 39 | } 40 | hashRing := &HashRing{ 41 | ring: make(map[HashKey]string), 42 | sortedKeys: make([]HashKey, 0), 43 | nodes: nodes, 44 | weights: weights, 45 | } 46 | hashRing.generateCircle() 47 | return hashRing 48 | } 49 | 50 | func (h *HashRing) UpdateWithWeights(weights map[string]int) { 51 | nodesChgFlg := false 52 | if len(weights) != len(h.weights) { 53 | nodesChgFlg = true 54 | } else { 55 | for node, newWeight := range weights { 56 | oldWeight, ok := h.weights[node] 57 | if !ok || oldWeight != newWeight { 58 | nodesChgFlg = true 59 | break 60 | } 61 | } 62 | } 63 | 64 | if nodesChgFlg { 65 | newhring := NewWithWeights(weights) 66 | h.weights = newhring.weights 67 | h.nodes = newhring.nodes 68 | h.ring = newhring.ring 69 | h.sortedKeys = newhring.sortedKeys 70 | } 71 | } 72 | 73 | func (h *HashRing) generateCircle() { 74 | totalWeight := 0 75 | for _, node := range h.nodes { 76 | if weight, ok := h.weights[node]; ok { 77 | totalWeight += weight 78 | } else { 79 | totalWeight += 1 80 | } 81 | } 82 | 83 | for _, node := range h.nodes { 84 | weight := 1 85 | 86 | if _, ok := h.weights[node]; ok { 87 | weight = h.weights[node] 88 | } 89 | 90 | factor := math.Floor(float64(40*len(h.nodes)*weight) / float64(totalWeight)) 91 | 92 | for j := 0; j < int(factor); j++ { 93 | nodeKey := fmt.Sprintf("%s-%d", node, j) 94 | bKey := hashDigest(nodeKey) 95 | 96 | for i := 0; i < 3; i++ { 97 | key := hashVal(bKey[i*4 : i*4+4]) 98 | h.ring[key] = node 99 | h.sortedKeys = append(h.sortedKeys, key) 100 | } 101 | } 102 | } 103 | 104 | sort.Sort(HashKeyOrder(h.sortedKeys)) 105 | } 106 | 107 | func (h *HashRing) GetNode(stringKey string) (node string, ok bool) { 108 | pos, ok := h.GetNodePos(stringKey) 109 | if !ok { 110 | return "", false 111 | } 112 | return h.ring[h.sortedKeys[pos]], true 113 | } 114 | 115 | func (h *HashRing) GetNodePos(stringKey string) (pos int, ok bool) { 116 | if len(h.ring) == 0 { 117 | return 0, false 118 | } 119 | 120 | key := h.GenKey(stringKey) 121 | 122 | nodes := h.sortedKeys 123 | pos = sort.Search(len(nodes), func(i int) bool { return nodes[i] > key }) 124 | 125 | if pos == len(nodes) { 126 | // Wrap the search, should return first node 127 | return 0, true 128 | } else { 129 | return pos, true 130 | } 131 | } 132 | 133 | func (h *HashRing) GenKey(key string) HashKey { 134 | bKey := hashDigest(key) 135 | return hashVal(bKey[0:4]) 136 | } 137 | 138 | func (h *HashRing) GetNodes(stringKey string, size int) (nodes []string, ok bool) { 139 | pos, ok := h.GetNodePos(stringKey) 140 | if !ok { 141 | return []string{}, false 142 | } 143 | 144 | if size > len(h.nodes) { 145 | return []string{}, false 146 | } 147 | 148 | returnedValues := make(map[string]bool, size) 149 | //mergedSortedKeys := append(h.sortedKeys[pos:], h.sortedKeys[:pos]...) 150 | resultSlice := make([]string, 0, size) 151 | 152 | for i := pos; i < pos+len(h.sortedKeys); i++ { 153 | key := h.sortedKeys[i%len(h.sortedKeys)] 154 | val := h.ring[key] 155 | if !returnedValues[val] { 156 | returnedValues[val] = true 157 | resultSlice = append(resultSlice, val) 158 | } 159 | if len(returnedValues) == size { 160 | break 161 | } 162 | } 163 | 164 | return resultSlice, len(resultSlice) == size 165 | } 166 | 167 | func (h *HashRing) AddNode(node string) *HashRing { 168 | return h.AddWeightedNode(node, 1) 169 | } 170 | 171 | func (h *HashRing) AddWeightedNode(node string, weight int) *HashRing { 172 | if weight <= 0 { 173 | return h 174 | } 175 | 176 | for _, eNode := range h.nodes { 177 | if eNode == node { 178 | return h 179 | } 180 | } 181 | 182 | nodes := make([]string, len(h.nodes), len(h.nodes)+1) 183 | copy(nodes, h.nodes) 184 | nodes = append(nodes, node) 185 | 186 | weights := make(map[string]int) 187 | for eNode, eWeight := range h.weights { 188 | weights[eNode] = eWeight 189 | } 190 | weights[node] = weight 191 | 192 | hashRing := &HashRing{ 193 | ring: make(map[HashKey]string), 194 | sortedKeys: make([]HashKey, 0), 195 | nodes: nodes, 196 | weights: weights, 197 | } 198 | hashRing.generateCircle() 199 | return hashRing 200 | } 201 | 202 | func (h *HashRing) UpdateWeightedNode(node string, weight int) *HashRing { 203 | if weight <= 0 { 204 | return h 205 | } 206 | 207 | /* node is not need to update for node is not existed or weight is not changed */ 208 | if oldWeight, ok := h.weights[node]; (!ok) || (ok && oldWeight == weight) { 209 | return h 210 | } 211 | 212 | nodes := make([]string, len(h.nodes), len(h.nodes)) 213 | copy(nodes, h.nodes) 214 | 215 | weights := make(map[string]int) 216 | for eNode, eWeight := range h.weights { 217 | weights[eNode] = eWeight 218 | } 219 | weights[node] = weight 220 | 221 | hashRing := &HashRing{ 222 | ring: make(map[HashKey]string), 223 | sortedKeys: make([]HashKey, 0), 224 | nodes: nodes, 225 | weights: weights, 226 | } 227 | hashRing.generateCircle() 228 | return hashRing 229 | } 230 | func (h *HashRing) RemoveNode(node string) *HashRing { 231 | nodes := make([]string, 0) 232 | for _, eNode := range h.nodes { 233 | if eNode != node { 234 | nodes = append(nodes, eNode) 235 | } 236 | } 237 | 238 | /* if node isn't exist in hashring, don't refresh hashring */ 239 | if len(nodes) == len(h.nodes) { 240 | return h 241 | } 242 | 243 | weights := make(map[string]int) 244 | for eNode, eWeight := range h.weights { 245 | if eNode != node { 246 | weights[eNode] = eWeight 247 | } 248 | } 249 | 250 | hashRing := &HashRing{ 251 | ring: make(map[HashKey]string), 252 | sortedKeys: make([]HashKey, 0), 253 | nodes: nodes, 254 | weights: weights, 255 | } 256 | hashRing.generateCircle() 257 | return hashRing 258 | } 259 | 260 | func hashVal(bKey []byte) HashKey { 261 | return ((HashKey(bKey[3]) << 24) | 262 | (HashKey(bKey[2]) << 16) | 263 | (HashKey(bKey[1]) << 8) | 264 | (HashKey(bKey[0]))) 265 | } 266 | 267 | func hashDigest(key string) []byte { 268 | m := md5.New() 269 | m.Write([]byte(key)) 270 | return m.Sum(nil) 271 | } 272 | -------------------------------------------------------------------------------- /tool/regexp.go: -------------------------------------------------------------------------------- 1 | package tool 2 | 3 | import ( 4 | "regexp" 5 | ) 6 | 7 | const ( 8 | // 匹配大陆电话 9 | cnPhonePattern = `((\d{3,4})-?)?` + // 区号 10 | `\d{7,8}` + // 号码 11 | `(-\d{1,4})?` // 分机号,分机号的连接符号不能省略。 12 | 13 | // 匹配大陆手机号码 14 | cnMobilePattern = `(0|\+?86)?` + // 匹配 0,86,+86 15 | `(13[0-9]|` + // 130-139 16 | `14[57]|` + // 145,147 17 | `15[0-35-9]|` + // 150-153,155-159 18 | `17[0678]|` + // 170,176,177,178 19 | `18[0-9])` + // 180-189 20 | `[0-9]{8}` 21 | 22 | // 匹配大陆手机号或是电话号码 23 | cnTelPattern = "(" + cnPhonePattern + ")|(" + cnMobilePattern + ")" 24 | 25 | // 匹配邮箱 26 | emailPattern = `[\w.-]+@[\w_-]+\w{1,}[\.\w-]+` 27 | 28 | // 匹配IP4 29 | ip4Pattern = `((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)` 30 | 31 | // 匹配IP6,参考以下网页内容: 32 | // http://blog.csdn.net/jiangfeng08/article/details/7642018 33 | ip6Pattern = `(([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|` + 34 | `(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|` + 35 | `(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|` + 36 | `(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|` + 37 | `(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|` + 38 | `(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|` + 39 | `(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|` + 40 | `(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))` 41 | 42 | // 同时匹配IP4和IP6 43 | ipPattern = "(" + ip4Pattern + ")|(" + ip6Pattern + ")" 44 | 45 | // 匹配域名 46 | domainPattern = `[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}(\.[a-zA-Z0-9][a-zA-Z0-9_-]{0,62})*(\.[a-zA-Z][a-zA-Z0-9]{0,10}){1}` 47 | 48 | hostPattern = "(" + ip4Pattern + "|(" + domainPattern + "))" + // IP或域名 49 | `(:\d{1,4})?` // 端口 50 | 51 | weightHostPattern = "(" + ip4Pattern + "|(" + domainPattern + "))" + // IP或域名 52 | `(:\d{1,4}\^\d+)?` // 端口 53 | 54 | // 匹配URL 55 | urlPattern = `((https|http|ftp|rtsp|mms)?://)?` + // 协议 56 | `(([0-9a-zA-Z]+:)?[0-9a-zA-Z_-]+@)?` + // pwd:user@ 57 | "(" + ipPattern + "|(" + domainPattern + "))" + // IP或域名 58 | `(:\d{1,4})?` + // 端口 59 | `(/+[a-zA-Z0-9][a-zA-Z0-9_.-]*/*)*` + // path 60 | `(\?([a-zA-Z0-9_-]+(=[a-zA-Z0-9_-]*)*)*)*` // query 61 | 62 | ) 63 | 64 | var ( 65 | Email = regexpCompile(emailPattern) 66 | Ip4 = regexpCompile(ip4Pattern) 67 | Ip6 = regexpCompile(ip6Pattern) 68 | Ip = regexpCompile(ipPattern) 69 | Url = regexpCompile(urlPattern) 70 | CnPhone = regexpCompile(cnPhonePattern) 71 | CnMobile = regexpCompile(cnMobilePattern) 72 | CnTel = regexpCompile(cnTelPattern) 73 | Host = regexpCompile(hostPattern) 74 | WeightHost = regexpCompile(weightHostPattern) 75 | ) 76 | 77 | func regexpCompile(str string) *regexp.Regexp { 78 | return regexp.MustCompile("^" + str + "$") 79 | } 80 | 81 | // 判断val是否能正确匹配exp中的正则表达式。 82 | // val可以是[]byte, []rune, string类型。 83 | func isMatch(exp *regexp.Regexp, val interface{}) bool { 84 | switch v := val.(type) { 85 | case []rune: 86 | return exp.MatchString(string(v)) 87 | case []byte: 88 | return exp.Match(v) 89 | case string: 90 | return exp.MatchString(v) 91 | default: 92 | return false 93 | } 94 | } 95 | 96 | // 验证中国大陆的电话号码。支持如下格式: 97 | // 0578-12345678-1234 98 | // 057812345678-1234 99 | // 若存在分机号,则分机号的连接符不能省略。 100 | func IsCNPhone(val interface{}) bool { 101 | return isMatch(CnPhone, val) 102 | } 103 | 104 | // 验证中国大陆的手机号码 105 | func IsCNMobile(val interface{}) bool { 106 | return isMatch(CnMobile, val) 107 | } 108 | 109 | func IsCNTel(val interface{}) bool { 110 | return isMatch(CnTel, val) 111 | } 112 | 113 | // 验证一个值是否标准的URL格式。支持IP和域名等格式 114 | func IsURL(val interface{}) bool { 115 | return isMatch(Url, val) 116 | } 117 | 118 | // 验证一个值是否为IP,可验证IP4和IP6 119 | func IsIP(val interface{}) bool { 120 | return isMatch(Ip, val) 121 | } 122 | 123 | // 验证一个值是否为IP6 124 | func IsIP6(val interface{}) bool { 125 | return isMatch(Ip6, val) 126 | } 127 | 128 | // 验证一个值是滞为IP4 129 | func IsIP4(val interface{}) bool { 130 | return isMatch(Ip4, val) 131 | } 132 | 133 | // 验证一个值是否匹配一个邮箱。 134 | func IsEmail(val interface{}) bool { 135 | return isMatch(Email, val) 136 | } 137 | 138 | func IsHost(val interface{}) bool { 139 | return isMatch(Host, val) 140 | } 141 | 142 | func IsWeightHost(val interface{}) bool { 143 | return isMatch(WeightHost, val) 144 | } 145 | -------------------------------------------------------------------------------- /tool/util.go: -------------------------------------------------------------------------------- 1 | /* 2 | @version: 1.0 3 | @author: allanpan 4 | @license: Apache Licence 5 | @contact: panjf2000@gmail.com 6 | @site: 7 | @file: fileutil.go 8 | @time: 2017/3/22 19:18 9 | @tag: 1,2,3 10 | @todo: ... 11 | */ 12 | package tool 13 | 14 | import ( 15 | "crypto/md5" 16 | "encoding/hex" 17 | "math/rand" 18 | "os" 19 | "time" 20 | ) 21 | 22 | // 判断给定文件名是否是一个目录 23 | // 如果文件名存在并且为目录则返回 true。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。 24 | func IsDir(filename string) bool { 25 | return isFileOrDir(filename, true) 26 | } 27 | 28 | // 判断是文件还是目录,根据decideDir为true表示判断是否为目录;否则判断是否为文件 29 | func isFileOrDir(filename string, decideDir bool) bool { 30 | fileInfo, err := os.Stat(filename) 31 | if err != nil { 32 | return false 33 | } 34 | isDir := fileInfo.IsDir() 35 | if decideDir { 36 | return isDir 37 | } 38 | return !isDir 39 | } 40 | 41 | func CheckFileIsExist(filepath string) bool { 42 | exist := true 43 | if _, err := os.Stat(filepath); os.IsNotExist(err) { 44 | exist = false 45 | } 46 | return exist 47 | } 48 | 49 | //GenRandom 获取随机数 50 | func GenRandom(start int, end int, count int) []int { 51 | //范围检查 52 | if end < start || (end-start) < count { 53 | return nil 54 | } 55 | 56 | //存放结果的slice 57 | nums := make([]int, 0) 58 | //随机数生成器,加入时间戳保证每次生成的随机数不一样 59 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 60 | for len(nums) < count { 61 | //生成随机数 62 | num := r.Intn(end-start) + start 63 | 64 | //查重 65 | exist := false 66 | for _, v := range nums { 67 | if v == num { 68 | exist = true 69 | break 70 | } 71 | } 72 | 73 | if !exist { 74 | nums = append(nums, num) 75 | } 76 | } 77 | return nums 78 | } 79 | 80 | func MD5Uri(uri string) string { 81 | ctx := md5.New() 82 | ctx.Write([]byte(uri)) 83 | return hex.EncodeToString(ctx.Sum(nil)) 84 | } 85 | --------------------------------------------------------------------------------