github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/group_test.go (about)

     1  package don_test
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/abemedia/go-don"
     8  	_ "github.com/abemedia/go-don/encoding/text"
     9  	"github.com/abemedia/go-don/internal/test"
    10  	"github.com/abemedia/httprouter"
    11  	"github.com/valyala/fasthttp"
    12  )
    13  
    14  func TestGroup(t *testing.T) {
    15  	api := don.New(nil)
    16  	group := api.Group("/group")
    17  
    18  	test.Router(t, group, api.RequestHandler(), "/group")
    19  	test.Router(t, group.Group("/sub"), api.RequestHandler(), "/group/sub")
    20  	test.Router(t, group.Group("sub"), api.RequestHandler(), "/groupsub")
    21  }
    22  
    23  func TestGroup_Use(t *testing.T) {
    24  	mwCalled := false
    25  
    26  	api := don.New(nil)
    27  	api.Get("/", func(*fasthttp.RequestCtx, httprouter.Params) {})
    28  
    29  	group := api.Group("/group")
    30  	group.Get("/foo", func(*fasthttp.RequestCtx, httprouter.Params) {})
    31  	group.Use(func(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    32  		return func(ctx *fasthttp.RequestCtx) {
    33  			if strings.HasPrefix(string(ctx.Path()), "/group/") {
    34  				mwCalled = true
    35  			} else {
    36  				t.Error("middleware called outside of group")
    37  			}
    38  		}
    39  	})
    40  
    41  	h := api.RequestHandler()
    42  
    43  	urls := []string{"/", "/group/foo"}
    44  	for _, url := range urls {
    45  		ctx := &fasthttp.RequestCtx{}
    46  		ctx.Request.Header.SetMethod(fasthttp.MethodGet)
    47  		ctx.Request.SetRequestURI(url)
    48  
    49  		h(ctx)
    50  
    51  		if ctx.Response.StatusCode() >= 300 {
    52  			t.Errorf("expected success status got %d", ctx.Response.Header.StatusCode())
    53  		}
    54  	}
    55  
    56  	if !mwCalled {
    57  		t.Error("group middleware wasn't called")
    58  	}
    59  }