Skip to content

Commit

Permalink
make cache reusable
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmood committed Mar 7, 2022
1 parent 8c482c9 commit bcebf07
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
9 changes: 5 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,21 +209,21 @@ func (ut Utils) ToJSONString(obj interface{}) string {
// If obj is not []byte, string, or io.Reader, it will be encoded as JSON.
func (ut Utils) Write(obj interface{}) (writer func(io.Writer)) {
lock := sync.Mutex{}
var cache io.ReadWriter
var cache []byte
return func(w io.Writer) {
lock.Lock()
defer lock.Unlock()

ut.Helper()

if cache != nil {
_, err := io.Copy(w, cache)
_, err := w.Write(cache)
ut.err(err)
return
}

cache = bytes.NewBuffer(nil)
w = io.MultiWriter(cache, w)
buf := bytes.NewBuffer(nil)
w = io.MultiWriter(buf, w)

var err error
switch v := obj.(type) {
Expand All @@ -237,6 +237,7 @@ func (ut Utils) Write(obj interface{}) (writer func(io.Writer)) {
err = json.NewEncoder(w).Encode(v)
}
ut.err(err)
cache = buf.Bytes()
}
}

Expand Down
33 changes: 33 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package got_test

import (
"bytes"
"io"
"net/http"
"os"
"sync"
"testing"

"github.com/ysmood/got"
Expand Down Expand Up @@ -116,3 +118,34 @@ func TestHelper(t *testing.T) {
mut.Skipf("test skip")
ut.Eq(m.msg, "test skip")
}

func TestServe(t *testing.T) {
ut := got.New(t)

key := ut.Srand(8)
s := ut.Serve().Route("/", "", key)
count := 30

wg := sync.WaitGroup{}
wg.Add(count)

request := func() {
req, err := http.NewRequest(http.MethodGet, s.URL(), nil)
ut.E(err)

res, err := http.DefaultClient.Do(req)
ut.E(err)

b, err := io.ReadAll(res.Body)
ut.E(err)

ut.Eq(string(b), key)
wg.Done()
}

for i := 0; i < count; i++ {
go request()
}

wg.Wait()
}

0 comments on commit bcebf07

Please sign in to comment.