├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── LICENSE ├── README.md ├── _example ├── echo │ ├── README.md │ └── main.go ├── grpc │ ├── README.md │ └── main.go └── http │ └── main.go ├── assets ├── diagram.jpg └── forker.png ├── error.go ├── fork.go ├── forker.go ├── forker_test.go ├── go.mod ├── go.sum ├── interface.go ├── network.go ├── network_string.go └── options.go /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # forker 2 | [![Go Reference](https://pkg.go.dev/badge/github.com/Ja7ad/forker.svg)](https://pkg.go.dev/github.com/Ja7ad/forker) 3 | 4 | Get high performance http requests with fork process (forker inspired prefork feature in web servers) 5 | 6 | prefork is a solution which is also used by other webservers 7 | 8 | A server instance is opened for each processor core and incoming requests are shared between these instances 9 | 10 | In order to distribute the load more evenly and handle more requests per second, there is a master that starts by the user, which then starts child processes on the other processor cores based on configuration 11 | 12 | memory between the different processes is not shared, beacuse goroutines are independent processes 13 | 14 | ![alt text](assets/diagram.jpg "diagram") 15 | 16 | # how to install 17 | 18 | ```shell 19 | go get -u github.com/Ja7ad/forker 20 | ``` 21 | 22 | ## forker benchmark 23 | 24 | forker tested 500 concurrent with 200k http requests 25 | 26 | ![alt text](assets/forker.png "forker") 27 | 28 | ```shell 29 | oha -c 500 -n 200000 --latency-correction --disable-keepalive http://localhost:8080 30 | ``` 31 | 32 | ```shell 33 | Summary: 34 | Success rate: 1.0000 35 | Total: 24.4907 secs 36 | Slowest: 0.5000 secs 37 | Fastest: 0.0004 secs 38 | Average: 0.0610 secs 39 | Requests/sec: 8166.3762 40 | 41 | Total data: 2.10 MiB 42 | Size/request: 11 B 43 | Size/sec: 87.72 KiB 44 | 45 | Response time histogram: 46 | 0.000 [1] | 47 | 0.050 [82408] |■■■■■■■■■■■■■■■■■■■■■■■■■■ 48 | 0.100 [98705] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 49 | 0.150 [16180] |■■■■■ 50 | 0.200 [2245] | 51 | 0.250 [361] | 52 | 0.300 [59] | 53 | 0.350 [33] | 54 | 0.400 [3] | 55 | 0.450 [1] | 56 | 0.500 [4] | 57 | 58 | Latency distribution: 59 | 10% in 0.0291 secs 60 | 25% in 0.0404 secs 61 | 50% in 0.0557 secs 62 | 75% in 0.0754 secs 63 | 90% in 0.0989 secs 64 | 95% in 0.1170 secs 65 | 99% in 0.1581 secs 66 | 67 | Details (average, fastest, slowest): 68 | DNS+dialup: 0.0259 secs, 0.0001 secs, 0.3010 secs 69 | DNS-lookup: 0.0000 secs, 0.0000 secs, 0.0239 secs 70 | 71 | ``` 72 | 73 | ## Example 74 | 75 | ### http server 76 | 77 | ```go 78 | package main 79 | 80 | import ( 81 | "github.com/Ja7ad/forker" 82 | "log" 83 | "net/http" 84 | ) 85 | 86 | func main() { 87 | srv := &http.Server{ 88 | Handler: GreetingHandler(), 89 | } 90 | 91 | f := forker.New(srv) 92 | 93 | log.Fatalln(f.ListenAndServe(":8080")) 94 | 95 | } 96 | 97 | func GreetingHandler() http.HandlerFunc { 98 | return func(w http.ResponseWriter, r *http.Request) { 99 | w.Write([]byte("greeting!!!")) 100 | } 101 | } 102 | ``` 103 | 104 | ### grpc server 105 | 106 | [benchmark](_example/grpc) 107 | 108 | ```go 109 | package main 110 | 111 | import ( 112 | "github.com/Ja7ad/forker" 113 | "google.golang.org/grpc/health" 114 | "google.golang.org/grpc/health/grpc_health_v1" 115 | "google.golang.org/grpc/reflection" 116 | "log" 117 | ) 118 | 119 | func main() { 120 | f := forker.NewGrpcForker(nil) 121 | srv := f.GetGrpcServer() 122 | 123 | grpc_health_v1.RegisterHealthServer(srv, health.NewServer()) 124 | 125 | reflection.Register(srv) 126 | 127 | log.Fatalln(f.ServeGrpc(":9090")) 128 | } 129 | 130 | ``` 131 | 132 | ### echo framework 133 | 134 | [benchmark](_example/echo) 135 | 136 | ```go 137 | package main 138 | 139 | import ( 140 | "github.com/Ja7ad/forker" 141 | "github.com/labstack/echo/v4" 142 | ) 143 | 144 | func main() { 145 | f := forker.NewEchoForker() 146 | e := f.GetEcho() 147 | 148 | e.GET("/", Greeting) 149 | 150 | e.Logger.Fatal(f.Start(":8080")) 151 | } 152 | 153 | func Greeting(c echo.Context) error { 154 | return c.String(200, "greeting") 155 | } 156 | 157 | ``` -------------------------------------------------------------------------------- /_example/echo/README.md: -------------------------------------------------------------------------------- 1 | # Benchmark echo forker 2 | 3 | ```shell 4 | ab -n 200000 -c 500 http://localhost:8080/ 5 | ``` 6 | 7 | ### with forker 8 | 9 | ```shell 10 | Server Software: 11 | Server Hostname: localhost 12 | Server Port: 8080 13 | 14 | Document Path: / 15 | Document Length: 8 bytes 16 | 17 | Concurrency Level: 500 18 | Time taken for tests: 31.660 seconds 19 | Complete requests: 200000 20 | Failed requests: 0 21 | Total transferred: 24800000 bytes 22 | HTML transferred: 1600000 bytes 23 | Requests per second: 6317.10 [#/sec] (mean) 24 | Time per request: 79.150 [ms] (mean) 25 | Time per request: 0.158 [ms] (mean, across all concurrent requests) 26 | Transfer rate: 764.96 [Kbytes/sec] received 27 | 28 | Connection Times (ms) 29 | min mean[+/-sd] median max 30 | Connect: 0 39 5.5 39 60 31 | Processing: 8 40 6.1 40 82 32 | Waiting: 0 29 6.3 29 64 33 | Total: 44 79 3.0 79 136 34 | 35 | Percentage of the requests served within a certain time (ms) 36 | 50% 79 37 | 66% 79 38 | 75% 79 39 | 80% 80 40 | 90% 81 41 | 95% 83 42 | 98% 88 43 | 99% 92 44 | 100% 136 (longest request) 45 | ``` 46 | 47 | ### without forker 48 | 49 | ```shell 50 | Server Software: 51 | Server Hostname: localhost 52 | Server Port: 8080 53 | 54 | Document Path: / 55 | Document Length: 8 bytes 56 | 57 | Concurrency Level: 500 58 | Time taken for tests: 34.230 seconds 59 | Complete requests: 200000 60 | Failed requests: 0 61 | Total transferred: 24800000 bytes 62 | HTML transferred: 1600000 bytes 63 | Requests per second: 5842.85 [#/sec] (mean) 64 | Time per request: 85.575 [ms] (mean) 65 | Time per request: 0.171 [ms] (mean, across all concurrent requests) 66 | Transfer rate: 707.53 [Kbytes/sec] received 67 | 68 | Connection Times (ms) 69 | min mean[+/-sd] median max 70 | Connect: 0 39 5.8 39 64 71 | Processing: 9 46 8.4 45 98 72 | Waiting: 0 33 8.9 31 81 73 | Total: 46 85 6.9 84 153 74 | 75 | Percentage of the requests served within a certain time (ms) 76 | 50% 84 77 | 66% 86 78 | 75% 88 79 | 80% 90 80 | 90% 95 81 | 95% 99 82 | 98% 104 83 | 99% 108 84 | 100% 153 (longest request) 85 | 86 | ``` -------------------------------------------------------------------------------- /_example/echo/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Ja7ad/forker" 5 | "github.com/labstack/echo/v4" 6 | ) 7 | 8 | func main() { 9 | f := forker.NewEchoForker() 10 | e := f.GetEcho() 11 | 12 | e.GET("/", Greeting) 13 | 14 | e.Logger.Fatal(f.StartEcho(":8080")) 15 | } 16 | 17 | func Greeting(c echo.Context) error { 18 | return c.String(200, "greeting") 19 | } 20 | -------------------------------------------------------------------------------- /_example/grpc/README.md: -------------------------------------------------------------------------------- 1 | # Benchmark grpc forker 2 | 3 | ```shell 4 | ghz -c 500 -n 200000 --insecure --call grpc.health.v1.Health.Check 0.0.0.0:9090 5 | ``` 6 | 7 | ### with forker 8 | 9 | ```shell 10 | Summary: 11 | Count: 200000 12 | Total: 14.38 s 13 | Slowest: 142.50 ms 14 | Fastest: 0.14 ms 15 | Average: 21.14 ms 16 | Requests/sec: 13910.00 17 | 18 | Response time histogram: 19 | 0.136 [1] | 20 | 14.372 [61253] |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 21 | 28.609 [92588] |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 22 | 42.845 [36131] |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 23 | 57.081 [7548] |∎∎∎ 24 | 71.318 [1670] |∎ 25 | 85.554 [599] | 26 | 99.790 [100] | 27 | 114.026 [39] | 28 | 128.263 [12] | 29 | 142.499 [59] | 30 | 31 | Latency distribution: 32 | 10 % in 6.91 ms 33 | 25 % in 12.65 ms 34 | 50 % in 19.31 ms 35 | 75 % in 27.64 ms 36 | 90 % in 36.87 ms 37 | 95 % in 42.87 ms 38 | 99 % in 59.01 ms 39 | ``` -------------------------------------------------------------------------------- /_example/grpc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Ja7ad/forker" 5 | "google.golang.org/grpc/health" 6 | "google.golang.org/grpc/health/grpc_health_v1" 7 | "google.golang.org/grpc/reflection" 8 | "log" 9 | ) 10 | 11 | func main() { 12 | f := forker.NewGrpcForker(nil) 13 | srv := f.GetGrpcServer() 14 | 15 | grpc_health_v1.RegisterHealthServer(srv, health.NewServer()) 16 | 17 | reflection.Register(srv) 18 | 19 | log.Fatalln(f.ServeGrpc(":9090")) 20 | } 21 | -------------------------------------------------------------------------------- /_example/http/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/Ja7ad/forker" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func main() { 10 | srv := &http.Server{ 11 | Handler: GreetingHandler(), 12 | } 13 | 14 | f := forker.New(srv) 15 | 16 | log.Fatalln(f.ListenAndServe(":8080")) 17 | 18 | } 19 | 20 | func GreetingHandler() http.HandlerFunc { 21 | return func(w http.ResponseWriter, r *http.Request) { 22 | w.Write([]byte("greeting!!!")) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /assets/diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoFarsi/forker/ac986841d3abe8dcda8d9d7a11ed9b5845cbcca3/assets/diagram.jpg -------------------------------------------------------------------------------- /assets/forker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoFarsi/forker/ac986841d3abe8dcda8d9d7a11ed9b5845cbcca3/assets/forker.png -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrReuseportOnWindows = errors.New("please enable reuseport for windows") 7 | ErrOverRecovery = errors.New("exceeding recovery child of forker") 8 | ) 9 | -------------------------------------------------------------------------------- /fork.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | import ( 4 | "flag" 5 | "github.com/valyala/fasthttp/reuseport" 6 | "net" 7 | "os" 8 | "os/exec" 9 | "runtime" 10 | ) 11 | 12 | const ( 13 | childFlag = "-child" 14 | _defaultNetwork = TCP4 15 | ) 16 | 17 | type processSignal struct { 18 | pid int 19 | err error 20 | } 21 | 22 | func init() { 23 | flag.Bool(childFlag[1:], false, "is forker child process") 24 | } 25 | 26 | func (f *Fork) forker(address string) (err error) { 27 | if !f.ReusePort { 28 | if runtime.GOOS == "windows" { 29 | return ErrReuseportOnWindows 30 | } 31 | 32 | if err = f.setTCPListenerFiles(address); err != nil { 33 | return 34 | } 35 | 36 | defer func() { 37 | if e := f.ln.Close(); e != nil { 38 | err = e 39 | } 40 | }() 41 | } 42 | 43 | goMaxProcess := runtime.GOMAXPROCS(0) 44 | sigCh := make(chan processSignal, goMaxProcess) 45 | childProcess := make(map[int]*exec.Cmd) 46 | 47 | defer func() { 48 | for _, proc := range childProcess { 49 | _ = proc.Process.Kill() 50 | } 51 | }() 52 | 53 | for i := 0; i < goMaxProcess; i++ { 54 | var cmd *exec.Cmd 55 | cmd, err = f.doCmd() 56 | if err != nil { 57 | return err 58 | } 59 | 60 | pid := cmd.Process.Pid 61 | childProcess[pid] = cmd 62 | f.childsPid = append(f.childsPid, pid) 63 | 64 | go func() { 65 | sigCh <- processSignal{cmd.Process.Pid, cmd.Wait()} 66 | }() 67 | } 68 | 69 | var exitedProcess int 70 | for sig := range sigCh { 71 | delete(childProcess, sig.pid) 72 | 73 | if exitedProcess++; exitedProcess > f.recoverChild { 74 | err = ErrOverRecovery 75 | break 76 | } 77 | 78 | var cmd *exec.Cmd 79 | if cmd, err = f.doCmd(); err != nil { 80 | break 81 | } 82 | 83 | childProcess[cmd.Process.Pid] = cmd 84 | go func() { 85 | sigCh <- processSignal{cmd.Process.Pid, cmd.Wait()} 86 | }() 87 | } 88 | 89 | return nil 90 | } 91 | 92 | func (f *Fork) listen(address string) (net.Listener, error) { 93 | runtime.GOMAXPROCS(1) 94 | 95 | if f.ReusePort { 96 | return reuseport.Listen(f.Network.String(), address) 97 | } 98 | 99 | return net.FileListener(os.NewFile(3, "")) 100 | } 101 | 102 | func (f *Fork) setTCPListenerFiles(address string) error { 103 | 104 | tcpAddr, err := net.ResolveTCPAddr(f.Network.String(), address) 105 | if err != nil { 106 | return err 107 | } 108 | 109 | tcpListener, err := net.ListenTCP(f.Network.String(), tcpAddr) 110 | if err != nil { 111 | return err 112 | } 113 | 114 | f.ln = tcpListener 115 | 116 | file, err := tcpListener.File() 117 | if err != nil { 118 | return err 119 | } 120 | 121 | f.files = []*os.File{file} 122 | 123 | return nil 124 | } 125 | 126 | func (f *Fork) doCmd() (*exec.Cmd, error) { 127 | cmd := exec.Command(os.Args[0], append(os.Args[1:], childFlag)...) 128 | cmd.Stdout = os.Stdout 129 | cmd.Stderr = os.Stderr 130 | cmd.ExtraFiles = f.files 131 | return cmd, cmd.Start() 132 | } 133 | 134 | func isChild() bool { 135 | for _, arg := range os.Args[1:] { 136 | if arg == childFlag { 137 | return true 138 | } 139 | } 140 | return false 141 | } 142 | -------------------------------------------------------------------------------- /forker.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | import ( 4 | "github.com/labstack/echo/v4" 5 | "google.golang.org/grpc" 6 | "net" 7 | "net/http" 8 | "os" 9 | "runtime" 10 | ) 11 | 12 | var _ Forker = (*Fork)(nil) 13 | 14 | type Fork struct { 15 | echo *echo.Echo 16 | grpc *grpc.Server 17 | 18 | serveFunc func(ln net.Listener) error 19 | serveTLSFunc func(ln net.Listener, certFile, keyFile string) error 20 | 21 | recoverChild int 22 | ln net.Listener 23 | files []*os.File 24 | 25 | childsPid []int 26 | 27 | Network Network // Network is net type tcp4, tcp, tcp6, udp, udp4, udp6 28 | ReusePort bool // ReusePort use for windows support child process base on system call 29 | } 30 | 31 | // New create forker for listen and serve http server 32 | func New(httpServer *http.Server, opts ...Option) Forker { 33 | forker := &Fork{ 34 | serveFunc: httpServer.Serve, 35 | serveTLSFunc: httpServer.ServeTLS, 36 | recoverChild: runtime.GOMAXPROCS(0) / 2, 37 | } 38 | 39 | for _, opt := range opts { 40 | opt(forker) 41 | } 42 | 43 | if forker.Network == 0 { 44 | forker.Network = _defaultNetwork 45 | } 46 | 47 | return forker 48 | } 49 | 50 | // NewEchoForker create for listen and serve echo 51 | func NewEchoForker(opts ...Option) EchoForker { 52 | forker := &Fork{ 53 | echo: echo.New(), 54 | recoverChild: runtime.GOMAXPROCS(0) / 2, 55 | } 56 | 57 | for _, opt := range opts { 58 | opt(forker) 59 | } 60 | 61 | if forker.Network == 0 { 62 | forker.Network = _defaultNetwork 63 | } 64 | 65 | return forker 66 | } 67 | 68 | // NewGrpcForker create for listen and serve grpc server 69 | func NewGrpcForker(grpcServerOpts []grpc.ServerOption, opts ...Option) GrpcForker { 70 | forker := &Fork{ 71 | recoverChild: runtime.GOMAXPROCS(0) / 2, 72 | } 73 | 74 | for _, opt := range opts { 75 | opt(forker) 76 | } 77 | 78 | grpcOpts := make([]grpc.ServerOption, 0) 79 | 80 | if len(grpcServerOpts) != 0 { 81 | grpcOpts = append(grpcOpts, grpcServerOpts...) 82 | } 83 | 84 | forker.grpc = grpc.NewServer(grpcOpts...) 85 | 86 | if forker.Network == 0 { 87 | forker.Network = _defaultNetwork 88 | } 89 | 90 | return forker 91 | } 92 | 93 | // ServeGrpc serve grpc server 94 | func (f *Fork) ServeGrpc(address string) error { 95 | if isChild() { 96 | ln, err := f.listen(address) 97 | if err != nil { 98 | return err 99 | } 100 | f.ln = ln 101 | return f.grpc.Serve(ln) 102 | } 103 | return f.forker(address) 104 | } 105 | 106 | // GetGrpcServer return grpc server object 107 | func (f *Fork) GetGrpcServer() *grpc.Server { 108 | return f.grpc 109 | } 110 | 111 | // StartEcho listener echo 112 | func (f *Fork) StartEcho(address string) error { 113 | if isChild() { 114 | ln, err := f.listen(address) 115 | if err != nil { 116 | return err 117 | } 118 | f.echo.Listener = ln 119 | f.ln = ln 120 | return f.echo.Start(address) 121 | } 122 | return f.forker(address) 123 | } 124 | 125 | // GetEcho return echo object 126 | func (f *Fork) GetEcho() *echo.Echo { 127 | return f.echo 128 | } 129 | 130 | // ListenAndServe listen and serve http server 131 | func (f *Fork) ListenAndServe(address string) error { 132 | if isChild() { 133 | ln, err := f.listen(address) 134 | if err != nil { 135 | return err 136 | } 137 | f.ln = ln 138 | return f.serveFunc(ln) 139 | } 140 | return f.forker(address) 141 | } 142 | 143 | // ListenAndServeTLS listen and serve http server with tls support 144 | func (f *Fork) ListenAndServeTLS(address, certFile, keyFile string) error { 145 | if isChild() { 146 | ln, err := f.listen(address) 147 | if err != nil { 148 | return err 149 | } 150 | 151 | f.ln = ln 152 | 153 | return f.serveTLSFunc(ln, certFile, keyFile) 154 | } 155 | 156 | return f.forker(address) 157 | } 158 | 159 | // NumOfChild number of child process 160 | func (f *Fork) NumOfChild() int { 161 | return len(f.childsPid) 162 | } 163 | 164 | // ChildPids list child process PID 165 | func (f *Fork) ChildPids() []int { 166 | return f.childsPid 167 | } 168 | -------------------------------------------------------------------------------- /forker_test.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "net/http" 7 | "os" 8 | "testing" 9 | ) 10 | 11 | func Test_Forker(t *testing.T) { 12 | t.Parallel() 13 | setup() 14 | defer tearDown() 15 | 16 | srv := &http.Server{} 17 | f := New(srv, WithReusePort(true)) 18 | 19 | addr := fmt.Sprintf("0.0.0.0:%d", rand.Intn(9000-3000)+3000) 20 | 21 | err := f.ListenAndServe(addr) 22 | if err != nil { 23 | t.Error(err) 24 | } 25 | 26 | f.(*Fork).ln.Close() 27 | 28 | lnAddr := f.(*Fork).ln.Addr().String() 29 | if lnAddr != addr { 30 | t.Errorf("want forker address %s, but listener address is %s", addr, lnAddr) 31 | } 32 | 33 | if f.(*Fork).ln == nil { 34 | t.Error("listener is null") 35 | } 36 | } 37 | 38 | func setup() { 39 | os.Args = append(os.Args, childFlag) 40 | } 41 | 42 | func tearDown() { 43 | os.Args = os.Args[:len(os.Args)-1] 44 | } 45 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Ja7ad/forker 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/labstack/echo/v4 v4.9.0 7 | github.com/valyala/fasthttp v1.40.0 8 | ) 9 | 10 | require ( 11 | github.com/golang/protobuf v1.5.2 // indirect 12 | github.com/labstack/gommon v0.3.1 // indirect 13 | github.com/mattn/go-colorable v0.1.11 // indirect 14 | github.com/mattn/go-isatty v0.0.14 // indirect 15 | github.com/valyala/bytebufferpool v1.0.0 // indirect 16 | github.com/valyala/fasttemplate v1.2.1 // indirect 17 | github.com/valyala/tcplisten v1.0.0 // indirect 18 | golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect 19 | golang.org/x/net v0.0.0-20221004154528-8021a29435af // indirect 20 | golang.org/x/sys v0.0.0-20221010170243-090e33056c14 // indirect 21 | golang.org/x/text v0.3.8 // indirect 22 | google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e // indirect 23 | google.golang.org/grpc v1.50.0 // indirect 24 | google.golang.org/protobuf v1.28.1 // indirect 25 | ) 26 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY= 2 | github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 7 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 8 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 9 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 10 | github.com/klauspost/compress v1.15.0 h1:xqfchp4whNFxn5A4XFyyYtitiWI8Hy5EW59jEwcyL6U= 11 | github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= 12 | github.com/labstack/echo/v4 v4.9.0 h1:wPOF1CE6gvt/kmbMR4dGzWvHMPT+sAEUJOwOTtvITVY= 13 | github.com/labstack/echo/v4 v4.9.0/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks= 14 | github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o= 15 | github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= 16 | github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs= 17 | github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= 18 | github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= 19 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= 20 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 21 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 22 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 23 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 24 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 25 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 26 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 27 | github.com/valyala/fasthttp v1.40.0 h1:CRq/00MfruPGFLTQKY8b+8SfdK60TxNztjRMnH0t1Yc= 28 | github.com/valyala/fasthttp v1.40.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I= 29 | github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4= 30 | github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= 31 | github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= 32 | github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= 33 | golang.org/x/crypto v0.0.0-20220214200702-86341886e292 h1:f+lwQ+GtmgoY+A2YaQxlSOnDjXcQ7ZRLWOHbC6HtRqE= 34 | golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 35 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 36 | golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc= 37 | golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= 38 | golang.org/x/net v0.0.0-20221004154528-8021a29435af h1:wv66FM3rLZGPdxpYL+ApnDe2HzHcTFta3z5nsc13wI4= 39 | golang.org/x/net v0.0.0-20221004154528-8021a29435af/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= 40 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 41 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 42 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 43 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 44 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 45 | golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 46 | golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 47 | golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 48 | golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875 h1:AzgQNqF+FKwyQ5LbVrVqOcuuFB67N47F9+htZYH0wFM= 49 | golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 50 | golang.org/x/sys v0.0.0-20221010170243-090e33056c14 h1:k5II8e6QD8mITdi+okbbmR/cIyEbeXLBhy5Ha4nevyc= 51 | golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 52 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 53 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 54 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 55 | golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= 56 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 57 | golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= 58 | golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= 59 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 60 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 61 | google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e h1:halCgTFuLWDRD61piiNSxPsARANGD3Xl16hPrLgLiIg= 62 | google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqwhZAwq4wsRUaVG555sVgsNmIjRtO7t/JH29U= 63 | google.golang.org/grpc v1.50.0 h1:fPVVDxY9w++VjTZsYvXWqEf9Rqar/e+9zYfxKK+W+YU= 64 | google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= 65 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 66 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 67 | google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= 68 | google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 69 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 70 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 71 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= 72 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 73 | -------------------------------------------------------------------------------- /interface.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | import ( 4 | "github.com/labstack/echo/v4" 5 | "google.golang.org/grpc" 6 | ) 7 | 8 | type Forker interface { 9 | child 10 | ListenAndServe(address string) error 11 | ListenAndServeTLS(address, certFile, keyFile string) error 12 | } 13 | 14 | type GrpcForker interface { 15 | child 16 | ServeGrpc(address string) error 17 | GetGrpcServer() *grpc.Server 18 | } 19 | 20 | type EchoForker interface { 21 | child 22 | StartEcho(address string) error 23 | GetEcho() *echo.Echo 24 | } 25 | 26 | type child interface { 27 | NumOfChild() int 28 | ChildPids() []int 29 | } 30 | -------------------------------------------------------------------------------- /network.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | //go:generate stringer -type=Network 4 | 5 | type Network int 6 | 7 | const ( 8 | TCP4 Network = iota + 1 9 | TCP6 10 | UDP 11 | UDP4 12 | UDP6 13 | ) 14 | -------------------------------------------------------------------------------- /network_string.go: -------------------------------------------------------------------------------- 1 | // Code generated by "stringer -type=Network"; DO NOT EDIT. 2 | 3 | package forker 4 | 5 | import "strconv" 6 | 7 | func _() { 8 | // An "invalid array index" compiler error signifies that the constant values have changed. 9 | // Re-run the stringer command to generate them again. 10 | var x [1]struct{} 11 | _ = x[TCP4-1] 12 | _ = x[TCP6-2] 13 | _ = x[UDP-3] 14 | _ = x[UDP4-4] 15 | _ = x[UDP6-5] 16 | } 17 | 18 | const _Network_name = "tcp4tcp6udpudp4udp6" 19 | 20 | var _Network_index = [...]uint8{0, 4, 8, 11, 15, 19} 21 | 22 | func (i Network) String() string { 23 | i -= 1 24 | if i < 0 || i >= Network(len(_Network_index)-1) { 25 | return "Network(" + strconv.FormatInt(int64(i+1), 10) + ")" 26 | } 27 | return _Network_name[_Network_index[i]:_Network_index[i+1]] 28 | } 29 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | package forker 2 | 3 | type Option func(f *Fork) 4 | 5 | // WithReusePort enable reuse port option for windows 6 | func WithReusePort(reusePort bool) Option { 7 | return func(f *Fork) { 8 | f.ReusePort = reusePort 9 | } 10 | } 11 | 12 | // WithCustomNetwork set network type listing type 13 | func WithCustomNetwork(network Network) Option { 14 | return func(f *Fork) { 15 | f.Network = network 16 | } 17 | } 18 | --------------------------------------------------------------------------------