當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO ResponseRecorder用法及代碼示例

GO語言"net/http/httptest"包中"ResponseRecorder"類型的用法及代碼示例。

ResponseRecorder 是 http ResponseWriter 的一個實現,它記錄其突變以供以後在測試中檢查。

用法:

type ResponseRecorder struct {
    // Code is the HTTP response code set by WriteHeader.
    //
    // Note that if a Handler never calls WriteHeader or Write,
    // this might end up being 0, rather than the implicit
    // http.StatusOK.To get the implicit value, use the Result
    // method.
    Code int

    // HeaderMap contains the headers explicitly set by the Handler.
    // It is an internal detail.
    //
    // Deprecated: HeaderMap exists for historical compatibility
    // and should not be used.To access the headers returned by a handler,
    // use the Response.Header map as returned by the Result method.
    HeaderMap http.Header

    // Body is the buffer to which the Handler's Write calls are sent.
    // If nil, the Writes are silently discarded.
    Body *bytes.Buffer

    // Flushed is whether the Handler called Flush.
    Flushed bool
    // contains filtered or unexported fields
}

例子:

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
)

func main() {
    handler := func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "<html><body>Hello World!</body></html>")
    }

    req := httptest.NewRequest("GET", "http://example.com/foo", nil)
    w := httptest.NewRecorder()
    handler(w, req)

    resp := w.Result()
    body, _ := io.ReadAll(resp.Body)

    fmt.Println(resp.StatusCode)
    fmt.Println(resp.Header.Get("Content-Type"))
    fmt.Println(string(body))

}

輸出:

200
text/html; charset=utf-8
<html><body>Hello World!</body></html>

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 ResponseRecorder。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。