Created
September 23, 2021 14:48
-
-
Save kenota/8f1db9edf4ca147ed90a474abd5609e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"sync" | |
"time" | |
"github.com/valyala/fasthttp" | |
) | |
type counter struct { | |
success int | |
failed int | |
rps int | |
bytes int | |
mu sync.Mutex | |
} | |
func newCounter() *counter { | |
c := new(counter) | |
go func() { | |
for { | |
c.mu.Lock() | |
curr := c.success | |
c.mu.Unlock() | |
time.Sleep(time.Second) | |
c.mu.Lock() | |
c.rps = c.success - curr | |
c.mu.Unlock() | |
} | |
}() | |
return c | |
} | |
func (c *counter) Add(bytes int) { | |
c.mu.Lock() | |
c.success++ | |
c.bytes += bytes | |
c.mu.Unlock() | |
} | |
func (c *counter) AddFail() { | |
c.mu.Lock() | |
defer c.mu.Unlock() | |
c.failed++ | |
} | |
func (c *counter) Report() (int, int, int, int) { | |
c.mu.Lock() | |
defer c.mu.Unlock() | |
return c.success, c.failed, c.rps, c.bytes | |
} | |
func main() { | |
var ( | |
maxR = flag.Int("r", 100, "max goroutines to launch") | |
) | |
flag.Parse() | |
fmt.Printf("Starting %d goroutines", *maxR) | |
req := fasthttp.AcquireRequest() | |
req.SetRequestURI("http://localhost:9090") | |
req.Header.Add("X-Email-Id", "someone@example.com") | |
req.Header.Add("Connection", "keep-alive") | |
client := &fasthttp.Client{} | |
c := newCounter() | |
for i := 0; i < *maxR; i++ { | |
go func() { | |
for { | |
resp := fasthttp.AcquireResponse() | |
client.Do(req, resp) | |
// This actually reads response | |
b := resp.Body() | |
if resp.StatusCode() == http.StatusOK { | |
c.Add(len(b)) | |
} else { | |
c.AddFail() | |
log.Println("got resp code", resp.StatusCode) | |
} | |
fasthttp.ReleaseResponse(resp) | |
} | |
}() | |
} | |
var s, f, rps, bRead int | |
for { | |
time.Sleep(time.Second * 10) | |
s, f, rps, bRead = c.Report() | |
log.Printf("\ntotal successful requests: %v\ntotal failed requests: %v\nrps: %v bytes read: %v", s, f, rps, bRead) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment