Skip to content

Commit

Permalink
Merge branch 'main' into use-copy
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW authored Jun 14, 2024
2 parents 7b79e3e + 74dcb46 commit 31afcc8
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions rc.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"syscall"
Expand Down Expand Up @@ -244,14 +243,51 @@ func New(cacher Cacher, opts ...Option) func(next http.Handler) http.Handler {
// HandlerToRequester converts http.Handler to func(*http.Request) (*http.Response, error).
func HandlerToRequester(h http.Handler) func(*http.Request) (*http.Response, error) {
return func(req *http.Request) (*http.Response, error) {
rec := httptest.NewRecorder()
rec := newRecorder()
h.ServeHTTP(rec, req)
res := rec.Result()
res.Header = rec.Header()
return res, nil
}
}

type recorder struct {
statusCode int
header http.Header
buf *bytes.Buffer
}

var _ http.ResponseWriter = (*recorder)(nil)

func newRecorder() *recorder {
return &recorder{
buf: new(bytes.Buffer),
header: make(http.Header),
}
}

func (r *recorder) Header() http.Header {
return r.header
}

func (r *recorder) Write(b []byte) (int, error) {
return r.buf.Write(b)
}

func (r *recorder) WriteHeader(statusCode int) {
r.statusCode = statusCode
}

func (r *recorder) Result() *http.Response {
return &http.Response{
Status: http.StatusText(r.statusCode),
StatusCode: r.statusCode,
Header: r.header.Clone(),
Body: io.NopCloser(r.buf),
ContentLength: int64(r.buf.Len()),
}
}

func contains(s []string, e string) bool {
for _, v := range s {
if e == v {
Expand Down

0 comments on commit 31afcc8

Please sign in to comment.