github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/webutil/response_test.go (about)

     1  package webutil
     2  
     3  import (
     4  	"bytes"
     5  	"compress/gzip"
     6  	"fmt"
     7  	"io"
     8  	"io/ioutil"
     9  	"log"
    10  	"net/http"
    11  	"net/http/httptest"
    12  	"net/http/httputil"
    13  	"testing"
    14  )
    15  
    16  func TestResponse(t *testing.T) {
    17  
    18  	hl := NewDefaultHandlerList(
    19  		NewCtxSetHandler("webutil.TestResponse", "test_value"),
    20  		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    21  			if r.URL.Path == "/test1" {
    22  				fmt.Fprintf(w, "<html><body>testing! %q</body></html>", r.Context().Value("webutil.TestResponse"))
    23  			}
    24  		}),
    25  		http.NotFoundHandler(),
    26  	)
    27  
    28  	// var hl HandlerList
    29  	// hl = append(hl, NewContextCancelHandler())
    30  	// hl = append(hl, NewGzipHandler())
    31  	// hl = append(hl, NewCtxSetHandler("webutil.TestResponse", "test_value"))
    32  	// hl = append(hl, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    33  	// 	if r.URL.Path == "/test1" {
    34  	// 		fmt.Fprintf(w, "<html><body>testing! %q</body></html>", r.Context().Value("webutil.TestResponse"))
    35  	// 	}
    36  	// }))
    37  	// hl = append(hl, http.NotFoundHandler())
    38  
    39  	r := httptest.NewRequest("GET", "/test1", nil)
    40  	r.Header.Set("accept-encoding", "gzip")
    41  	tw := httptest.NewRecorder()
    42  	var w http.ResponseWriter = tw
    43  
    44  	w, r = hl.ServeHTTPChain(w, r)
    45  
    46  	result := tw.Result()
    47  	b, _ := httputil.DumpResponse(result, false)
    48  	log.Printf("RESULT:\n%s", b)
    49  
    50  	body, err := ioutil.ReadAll(result.Body)
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	// log.Printf("result body %v", body)
    55  
    56  	if result.Header.Get("content-encoding") == "gzip" {
    57  		gr, err := gzip.NewReader(bytes.NewReader(body))
    58  		if err != nil {
    59  			t.Fatal(err)
    60  		}
    61  		body, err = ioutil.ReadAll(gr)
    62  		if err != nil && err != io.ErrUnexpectedEOF { // ignore unexpected EOF, just verify the stream below got to the end
    63  			t.Fatal(err)
    64  		}
    65  	}
    66  
    67  	if !bytes.Contains(body, []byte("test_value")) {
    68  		t.Fatalf("result did not contain test_value")
    69  	}
    70  
    71  	if !bytes.Contains(body, []byte("</html>")) {
    72  		t.Fatalf("result did not contain </html>")
    73  	}
    74  
    75  	log.Printf("RESULT BODY:\n%s", body)
    76  
    77  }