1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
package main
import (
"archive/tar"
"bytes"
"flag"
"fmt"
"io"
"net/http"
"sync"
"time"
)
func makeInit() []byte {
writer := bytes.NewBuffer(nil)
archive := tar.NewWriter(writer)
archive.WriteHeader(&tar.Header{
Typeflag: tar.TypeReg,
Name: "index.html",
})
archive.Write([]byte{})
archive.Flush()
return writer.Bytes()
}
func initSite() {
req, err := http.NewRequest(http.MethodPut, "http://localhost:3000",
bytes.NewReader(makeInit()))
if err != nil {
panic(err)
}
req.Header.Add("Content-Type", "application/x-tar")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
}
func makePatch(n int) []byte {
writer := bytes.NewBuffer(nil)
archive := tar.NewWriter(writer)
archive.WriteHeader(&tar.Header{
Typeflag: tar.TypeReg,
Name: fmt.Sprintf("%d.txt", n),
})
archive.Write([]byte{})
archive.Flush()
return writer.Bytes()
}
func patchRequest(n int) int {
req, err := http.NewRequest(http.MethodPatch, "http://localhost:3000",
bytes.NewReader(makePatch(n)))
if err != nil {
panic(err)
}
req.Header.Add("Atomic", "no")
req.Header.Add("Content-Type", "application/x-tar")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("%d: %s %q\n", n, resp.Status, string(data))
return resp.StatusCode
}
func concurrentWriter(wg *sync.WaitGroup, n int) {
for {
if patchRequest(n) == 200 {
break
}
}
wg.Done()
}
var count = flag.Int("count", 10, "request count")
func main() {
flag.Parse()
initSite()
time.Sleep(time.Second)
wg := &sync.WaitGroup{}
for n := range *count {
wg.Add(1)
go concurrentWriter(wg, n)
}
wg.Wait()
success := 0
for n := range *count {
resp, err := http.Get(fmt.Sprintf("http://localhost:3000/%d.txt", n))
if err != nil {
panic(err)
}
if resp.StatusCode == 200 {
success++
}
}
fmt.Printf("written: %d of %d\n", success, *count)
}
|