github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/mock/mock_response_writer.go (about)

     1  package mock
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/http/httputil"
     8  )
     9  
    10  func NewMockResponseWriter() *ResponseWriter {
    11  	return &ResponseWriter{
    12  		header: http.Header{},
    13  	}
    14  }
    15  
    16  type ResponseWriter struct {
    17  	header     http.Header
    18  	StatusCode int
    19  	bytes.Buffer
    20  }
    21  
    22  var _ http.ResponseWriter = (*ResponseWriter)(nil)
    23  
    24  func (w *ResponseWriter) Header() http.Header {
    25  	if w.StatusCode == 0 {
    26  		return w.header
    27  	}
    28  
    29  	header := http.Header{}
    30  
    31  	for k, v := range w.header {
    32  		header[k] = v
    33  	}
    34  
    35  	return header
    36  }
    37  
    38  func (w *ResponseWriter) WriteHeader(statusCode int) {
    39  	w.StatusCode = statusCode
    40  }
    41  
    42  func (w *ResponseWriter) Response() *http.Response {
    43  	resp := &http.Response{}
    44  	resp.Header = w.header
    45  	resp.StatusCode = w.StatusCode
    46  	resp.Body = ioutil.NopCloser(&w.Buffer)
    47  	return resp
    48  }
    49  
    50  func (w *ResponseWriter) MustDumpResponse() []byte {
    51  	data, err := httputil.DumpResponse(w.Response(), true)
    52  	if err != nil {
    53  		panic(err)
    54  	}
    55  	return bytes.Replace(data, []byte("\r\n"), []byte("\n"), -1)
    56  }