Documentation
¶
Overview ¶
パッケージhttptestは、HTTPテストのためのユーティリティを提供します。
Index ¶
- Constants
- func NewRequest(method, target string, body io.Reader) *http.Request
- type ResponseRecorder
- func (rw *ResponseRecorder) Flush()
- func (rw *ResponseRecorder) Header() http.Header
- func (rw *ResponseRecorder) Result() *http.Response
- func (rw *ResponseRecorder) Write(buf []byte) (int, error)
- func (rw *ResponseRecorder) WriteHeader(code int)
- func (rw *ResponseRecorder) WriteString(str string) (int, error)
- type Server
Examples ¶
Constants ¶
const DefaultRemoteAddr = "1.2.3.4"
DefaultRemoteAddrは、ResponseRecorder に明示的なDefaultRemoteAddrが設定されていない場合に、 RemoteAddrで返すデフォルトのリモートアドレスです。
Variables ¶
This section is empty.
Functions ¶
func NewRequest ¶ added in v1.7.0
NewRequestはテスト用に、http.Handler に渡すことができる新しい受信サーバーリクエストを返します。
targetはRFC 7230の「要求ターゲット」です。パスまたは絶対URLのいずれかを使用できます。targetが絶対URLの場合、URLからホスト名が使用されます。それ以外の場合は、"example.com"が使用されます。
targetのスキームが「https」の場合、TLSフィールドは非nilのダミー値に設定されます。
Request.Protoは常にHTTP/1.1です。
空のメソッドは「GET」を意味します。
指定されたbodyはnilである場合があります。bodyが*bytes.Reader、*strings.Reader、または*bytes.Bufferの型の場合、Request.ContentLengthが設定されます。
NewRequestはエラー時にパニックを発生させます。テストではパニックが許容されるため、使用の便宜上です。
サーバーリクエストではなく、クライアントのHTTPリクエストを生成するには、net/httpパッケージのNewRequest関数を参照してください。
Types ¶
type ResponseRecorder ¶
type ResponseRecorder struct { // CodeはWriteHeaderが設定したHTTPレスポンスコードです。 // // HandlerがWriteHeaderやWriteを呼び出さない場合、これは暗黙のhttp.StatusOKではなく、0になることに注意してください。暗黙の値を取得するには、Resultメソッドを使用してください。 Code int // HeaderMapはHandlerによって明示的に設定されたヘッダーを含んでいます。 // これは内部の詳細です。 // // Deprecated: HeaderMapは歴史的な互換性のために存在しており、使用すべきではありません。 // ハンドラによって返されるヘッダーにアクセスするためには、Resultメソッドによって返される // Response.Headerマップを使用してください。 HeaderMap http.Header // BodyはHandlerのWrite呼び出しで送信されるバッファです。 // nilの場合、書き込みは黙って破棄されます。 Body *bytes.Buffer // Flushed はHandlerがFlushを呼び出したかどうかを示します。 Flushed bool // contains filtered or unexported fields }
ResponseRecorderは http.ResponseWriter の実装であり、テストで後で検査するためにその変更を記録します。
Example ¶
package main import ( "github.com/shogo82148/std/fmt" "github.com/shogo82148/std/io" "github.com/shogo82148/std/net/http" "github.com/shogo82148/std/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)) }
Output: 200 text/html; charset=utf-8 <html><body>Hello World!</body></html>
func (*ResponseRecorder) Flush ¶
func (rw *ResponseRecorder) Flush()
Flushは http.Flusher を実装します。Flushが呼び出されたかどうかをテストするには、rw.Flushedを参照してください。
func (*ResponseRecorder) Header ¶
func (rw *ResponseRecorder) Header() http.Header
Headerは http.ResponseWriter を実装します。ハンドラ内で変更するためにレスポンスヘッダーを返します。ハンドラが完了した後に書き込まれたヘッダーをテストするには、ResponseRecorder.Result メソッドを使用し、返されたResponse値のHeaderを確認してください。
func (*ResponseRecorder) Result ¶ added in v1.7.0
func (rw *ResponseRecorder) Result() *http.Response
Resultはハンドラによって生成されたレスポンスを返します。
返されるレスポンスには、少なくともStatusCode、Header、Body、およびオプションでTrailerが含まれます。 将来的にはさらなるフィールドが追加される可能性があるため、テストでは結果をDeepEqualで比較しないよう注意してください。
Response.Headerは、最初の書き込み呼び出し時またはこの呼び出し時のヘッダのスナップショットですが、ハンドラが書き込みを行っていない場合は呼び出し時のものになります。
Response.Bodyは非nilであり、Body.Read呼び出しは io.EOF 以外のエラーを返さないことが保証されています。
Resultは、ハンドラの実行が完了した後にのみ呼び出す必要があります。
func (*ResponseRecorder) Write ¶
func (rw *ResponseRecorder) Write(buf []byte) (int, error)
Writeはhttp.ResponseWriterを実装します。buf内のデータは、rw.Bodyがnilでない場合にrw.Bodyに書き込まれます。
func (*ResponseRecorder) WriteHeader ¶
func (rw *ResponseRecorder) WriteHeader(code int)
WriteHeaderは http.ResponseWriter を実装します。
func (*ResponseRecorder) WriteString ¶ added in v1.6.0
func (rw *ResponseRecorder) WriteString(str string) (int, error)
WriteStringは io.StringWriter を実装します。strのデータは、nilでない場合はrw.Bodyに書き込まれます。
type Server ¶
type Server struct { URL string Listener net.Listener // EnableHTTP2は、サーバー上でHTTP/2が有効かどうかを制御します。 // NewUnstartedServerを呼び出すときとServer.StartTLSを呼び出すときの間に設定する必要があります。 EnableHTTP2 bool // TLSはオプションのTLS構成であり、新しい構成でポピュレートされます // TLSが開始された後に。 StartTLSが呼び出される前に開始されていないサーバーに設定されている場合、既存のフィールドは新しい構成にコピーされます。 TLS *tls.Config // NewUnstartedServer を呼び出した後、Start または StartTLS を実行する前に、Config を変更することができます。 Config *http.Server // contains filtered or unexported fields }
Serverは、エンドツーエンドのHTTPテストで使用するために、 ローカルループバックインターフェース上のシステムが選んだポートでリッスンするHTTPサーバーです。
Example ¶
package main import ( "github.com/shogo82148/std/fmt" "github.com/shogo82148/std/io" "github.com/shogo82148/std/log" "github.com/shogo82148/std/net/http" "github.com/shogo82148/std/net/http/httptest" ) func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) }
Output: Hello, client
Example (HTTP2) ¶
package main import ( "github.com/shogo82148/std/fmt" "github.com/shogo82148/std/io" "github.com/shogo82148/std/log" "github.com/shogo82148/std/net/http" "github.com/shogo82148/std/net/http/httptest" ) func main() { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s", r.Proto) })) ts.EnableHTTP2 = true ts.StartTLS() defer ts.Close() res, err := ts.Client().Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) }
Output: Hello, HTTP/2.0
func NewTLSServer ¶
NewTLSServerはTLSを使用して新しい Server を起動し、それを返します。 終了時には、呼び出し元はシャットダウンするためにCloseを呼び出す必要があります。
Example ¶
package main import ( "github.com/shogo82148/std/fmt" "github.com/shogo82148/std/io" "github.com/shogo82148/std/log" "github.com/shogo82148/std/net/http" "github.com/shogo82148/std/net/http/httptest" ) func main() { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() client := ts.Client() res, err := client.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", greeting) }
Output: Hello, client
func NewUnstartedServer ¶
NewUnstartedServerは新しい Server を返しますが、開始はしません。
設定を変更した後、呼び出し元はStartまたはStartTLSを呼び出す必要があります。
使用し終えたらCloseを呼び出してシャットダウンする必要があります。
func (*Server) Certificate ¶ added in v1.9.0
func (s *Server) Certificate() *x509.Certificate
Certificateは、サーバーがTLSを使用していない場合はnil、それ以外の場合はサーバーが使用する証明書を返します。
func (*Server) Client ¶ added in v1.9.0
Clientは、サーバーへのリクエストを行うために設定されたHTTPクライアントを返します。 サーバーのTLSテスト証明書を信頼するように設定されており、Server.Close 時にアイドル接続をクローズします。
func (*Server) Close ¶
func (s *Server) Close()
Close はサーバーをシャットダウンし、このサーバーに対して保留中のすべてのリクエストが完了するまでブロックします。
func (*Server) CloseClientConnections ¶
func (s *Server) CloseClientConnections()
CloseClientConnectionsはテストサーバーへのすべてのオープン中のHTTP接続を閉じます。