github.com/blend/go-sdk@v1.20220411.3/webutil/middleware_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"fmt"
    12  	"io"
    13  	"net/http"
    14  	"net/http/httptest"
    15  	"testing"
    16  
    17  	"github.com/blend/go-sdk/assert"
    18  )
    19  
    20  func TestMiddelware(t *testing.T) {
    21  	assert := assert.New(t)
    22  
    23  	innerDone := make(chan struct{})
    24  	inner := func(rw http.ResponseWriter, req *http.Request) {
    25  		close(innerDone)
    26  		rw.WriteHeader(http.StatusOK)
    27  		fmt.Fprint(rw, "OK!\n")
    28  	}
    29  
    30  	oneDone := make(chan struct{})
    31  	one := func(action http.HandlerFunc) http.HandlerFunc {
    32  		return func(rw http.ResponseWriter, req *http.Request) {
    33  			close(oneDone)
    34  			action(rw, req)
    35  			fmt.Fprint(rw, "One\n")
    36  		}
    37  	}
    38  
    39  	twoDone := make(chan struct{})
    40  	two := func(action http.HandlerFunc) http.HandlerFunc {
    41  		return func(rw http.ResponseWriter, req *http.Request) {
    42  			close(twoDone)
    43  			action(rw, req)
    44  			fmt.Fprint(rw, "Two\n")
    45  		}
    46  	}
    47  
    48  	server := httptest.NewServer(http.HandlerFunc(NestMiddleware(inner, two, one)))
    49  	defer server.Close()
    50  
    51  	res, err := http.Get(server.URL)
    52  	assert.Nil(err)
    53  
    54  	<-oneDone
    55  	<-twoDone
    56  	<-innerDone
    57  
    58  	contents, err := io.ReadAll(res.Body)
    59  	assert.Nil(err)
    60  	assert.Equal("OK!\nTwo\nOne\n", string(contents))
    61  }