github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/http/httptest/example_test.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package httptest_test
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"log"
    11  	"net/http"
    12  	"net/http/httptest"
    13  )
    14  
    15  func ExampleResponseRecorder() {
    16  	handler := func(w http.ResponseWriter, r *http.Request) {
    17  		http.Error(w, "something failed", http.StatusInternalServerError)
    18  	}
    19  
    20  	req, err := http.NewRequest("GET", "http://example.com/foo", nil)
    21  	if err != nil {
    22  		log.Fatal(err)
    23  	}
    24  
    25  	w := httptest.NewRecorder()
    26  	handler(w, req)
    27  
    28  	fmt.Printf("%d - %s", w.Code, w.Body.String())
    29  	// Output: 500 - something failed
    30  }
    31  
    32  func ExampleServer() {
    33  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    34  		fmt.Fprintln(w, "Hello, client")
    35  	}))
    36  	defer ts.Close()
    37  
    38  	res, err := http.Get(ts.URL)
    39  	if err != nil {
    40  		log.Fatal(err)
    41  	}
    42  	greeting, err := ioutil.ReadAll(res.Body)
    43  	res.Body.Close()
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	fmt.Printf("%s", greeting)
    49  	// Output: Hello, client
    50  }