Last active
April 12, 2021 02:45
-
-
Save linxGnu/1a5a99891d66ae913d7177bbd247fa8f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
const ( | |
numWorker = 20 | |
) | |
type handlingType byte | |
const ( | |
drainAndClosing handlingType = iota | |
closingOnly | |
) | |
func main() { | |
go startServer() | |
time.Sleep(time.Second) | |
requesting(closingOnly) // change it to `drainAndClosing` to see the difference | |
} | |
func requesting(hType handlingType) { | |
var ( | |
totalError int32 | |
) | |
start := time.Now() | |
var wg sync.WaitGroup | |
wg.Add(numWorker) | |
for i := 0; i < numWorker; i++ { | |
go func() { | |
defer wg.Done() | |
for j := 0; j < 1000; j++ { | |
req, _ := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/", nil) | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
atomic.AddInt32(&totalError, 1) | |
continue | |
} | |
switch hType { | |
case drainAndClosing: | |
_, _ = io.Copy(ioutil.Discard, resp.Body) | |
_ = resp.Body.Close() | |
case closingOnly: | |
_ = resp.Body.Close() | |
} | |
} | |
}() | |
} | |
wg.Wait() | |
switch hType { | |
case drainAndClosing: | |
fmt.Println("Type: draining and closing.") | |
case closingOnly: | |
fmt.Println("Type: only closing") | |
} | |
fmt.Printf("Duration: %0.2f sec(s).\nNumber errors: %d\n\n", time.Since(start).Seconds(), totalError) | |
} | |
func startServer() { | |
http.HandleFunc("/", HelloServer) | |
_ = http.ListenAndServe(":8080", nil) | |
} | |
func HelloServer(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello world") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment