本文整理汇总了Golang中github.com/valyala/fasthttp.Response.Body方法的典型用法代码示例。如果您正苦于以下问题:Golang Response.Body方法的具体用法?Golang Response.Body怎么用?Golang Response.Body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/valyala/fasthttp.Response
的用法示例。
在下文中一共展示了Response.Body方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: convertResponse
func convertResponse(stdreq *http.Request, fastresp *fasthttp.Response) *http.Response {
status := fastresp.Header.StatusCode()
body := fastresp.Body()
stdresp := &http.Response{
Request: stdreq,
StatusCode: status,
Status: http.StatusText(status),
}
fastresp.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)
if stdresp.Header == nil {
stdresp.Header = make(http.Header)
}
stdresp.Header.Add(sk, sv)
})
if fastresp.Header.ContentLength() == -1 {
stdresp.TransferEncoding = []string{"chunked"}
}
if body != nil {
stdresp.Body = ioutil.NopCloser(bytes.NewReader(body))
} else {
stdresp.Body = ioutil.NopCloser(bytes.NewReader(nil))
}
return stdresp
}
示例2: ExampleLBClient
func ExampleLBClient() {
// Requests will be spread among these servers.
servers := []string{
"google.com:80",
"foobar.com:8080",
"127.0.0.1:123",
}
// Prepare clients for each server
var lbc fasthttp.LBClient
for _, addr := range servers {
c := &fasthttp.HostClient{
Addr: addr,
}
lbc.Clients = append(lbc.Clients, c)
}
// Send requests to load-balanced servers
var req fasthttp.Request
var resp fasthttp.Response
for i := 0; i < 10; i++ {
url := fmt.Sprintf("http://abcedfg/foo/bar/%d", i)
req.SetRequestURI(url)
if err := lbc.Do(&req, &resp); err != nil {
log.Fatalf("Error when sending request: %s", err)
}
if resp.StatusCode() != fasthttp.StatusOK {
log.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), fasthttp.StatusOK)
}
useResponseBody(resp.Body())
}
}
示例3: fetchFromUpstream
func fetchFromUpstream(h *fasthttp.RequestHeader, key []byte) *ybc.Item {
upstreamUrl := fmt.Sprintf("%s://%s%s", *upstreamProtocol, *upstreamHost, h.RequestURI())
var req fasthttp.Request
req.SetRequestURI(upstreamUrl)
var resp fasthttp.Response
err := upstreamClient.Do(&req, &resp)
if err != nil {
logRequestError(h, "Cannot make request for [%s]: [%s]", key, err)
return nil
}
if resp.StatusCode() != fasthttp.StatusOK {
logRequestError(h, "Unexpected status code=%d for the response [%s]", resp.StatusCode(), key)
return nil
}
contentType := string(resp.Header.ContentType())
if contentType == "" {
contentType = "application/octet-stream"
}
body := resp.Body()
contentLength := len(body)
itemSize := contentLength + len(contentType) + 1
txn, err := cache.NewSetTxn(key, itemSize, ybc.MaxTtl)
if err != nil {
logRequestError(h, "Cannot start set txn for response [%s], itemSize=%d: [%s]", key, itemSize, err)
return nil
}
if err = storeContentType(h, txn, contentType); err != nil {
txn.Rollback()
return nil
}
n, err := txn.Write(body)
if err != nil {
logRequestError(h, "Cannot read response [%s] body with size=%d to cache: [%s]", key, contentLength, err)
txn.Rollback()
return nil
}
if n != contentLength {
logRequestError(h, "Unexpected number of bytes copied=%d from response [%s] to cache. Expected %d", n, key, contentLength)
txn.Rollback()
return nil
}
item, err := txn.CommitItem()
if err != nil {
logRequestError(h, "Cannot commit set txn for response [%s], size=%d: [%s]", key, contentLength, err)
return nil
}
atomic.AddInt64(&stats.BytesReadFromUpstream, int64(n))
return item
}
示例4: TestRouterServeFiles
func TestRouterServeFiles(t *testing.T) {
router := New()
recv := catchPanic(func() {
router.ServeFiles("/noFilepath", os.TempDir())
})
if recv == nil {
t.Fatal("registering path not ending with '*filepath' did not panic")
}
body := []byte("fake ico")
ioutil.WriteFile(os.TempDir()+"/favicon.ico", body, 0644)
router.ServeFiles("/*filepath", os.TempDir())
s := &fasthttp.Server{
Handler: router.Handler,
}
rw := &readWriter{}
ch := make(chan error)
rw.r.WriteString(string("GET /favicon.ico HTTP/1.1\r\n\r\n"))
go func() {
ch <- s.ServeConn(rw)
}()
select {
case err := <-ch:
if err != nil {
t.Fatalf("return error %s", err)
}
case <-time.After(500 * time.Millisecond):
t.Fatalf("timeout")
}
br := bufio.NewReader(&rw.w)
var resp fasthttp.Response
if err := resp.Read(br); err != nil {
t.Fatalf("Unexpected error when reading response: %s", err)
}
if resp.Header.StatusCode() != 200 {
t.Fatalf("Unexpected status code %d. Expected %d", resp.Header.StatusCode(), 423)
}
if !bytes.Equal(resp.Body(), body) {
t.Fatalf("Unexpected body %q. Expected %q", resp.Body(), string(body))
}
}
示例5: TestRouterNotAllowed
func TestRouterNotAllowed(t *testing.T) {
handlerFunc := func(_ *fasthttp.RequestCtx, _ Params) {}
router := New()
router.POST("/path", handlerFunc)
// Test not allowed
s := &fasthttp.Server{
Handler: router.Handler,
}
rw := &readWriter{}
ch := make(chan error)
rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n")
go func() {
ch <- s.ServeConn(rw)
}()
select {
case err := <-ch:
if err != nil {
t.Fatalf("return error %s", err)
}
case <-time.After(100 * time.Millisecond):
t.Fatalf("timeout")
}
br := bufio.NewReader(&rw.w)
var resp fasthttp.Response
if err := resp.Read(br); err != nil {
t.Fatalf("Unexpected error when reading response: %s", err)
}
if !(resp.Header.StatusCode() == fasthttp.StatusMethodNotAllowed) {
t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", resp.Header.StatusCode(), resp.Header)
} else if allow := string(resp.Header.Peek("Allow")); allow != "POST, OPTIONS" {
t.Error("unexpected Allow header value: " + allow)
}
// add another method
router.DELETE("/path", handlerFunc)
router.OPTIONS("/path", handlerFunc) // must be ignored
// test again
rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n")
go func() {
ch <- s.ServeConn(rw)
}()
select {
case err := <-ch:
if err != nil {
t.Fatalf("return error %s", err)
}
case <-time.After(100 * time.Millisecond):
t.Fatalf("timeout")
}
if err := resp.Read(br); err != nil {
t.Fatalf("Unexpected error when reading response: %s", err)
}
if !(resp.Header.StatusCode() == fasthttp.StatusMethodNotAllowed) {
t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", resp.Header.StatusCode(), resp.Header)
} else if allow := string(resp.Header.Peek("Allow")); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" {
t.Error("unexpected Allow header value: " + allow)
}
responseText := "custom method"
router.MethodNotAllowed = fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(fasthttp.StatusTeapot)
ctx.Write([]byte(responseText))
})
rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n")
go func() {
ch <- s.ServeConn(rw)
}()
select {
case err := <-ch:
if err != nil {
t.Fatalf("return error %s", err)
}
case <-time.After(100 * time.Millisecond):
t.Fatalf("timeout")
}
if err := resp.Read(br); err != nil {
t.Fatalf("Unexpected error when reading response: %s", err)
}
if !bytes.Equal(resp.Body(), []byte(responseText)) {
t.Errorf("unexpected response got %q want %q", string(resp.Body()), responseText)
}
if resp.Header.StatusCode() != fasthttp.StatusTeapot {
t.Errorf("unexpected response code %d want %d", resp.Header.StatusCode(), fasthttp.StatusTeapot)
}
if allow := string(resp.Header.Peek("Allow")); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" {
t.Error("unexpected Allow header value: " + allow)
}
}