github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_z_unit_feature_router_group_hook_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package ghttp_test
     8  
     9  import (
    10  	"fmt"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/wangyougui/gf/v2/frame/g"
    15  	"github.com/wangyougui/gf/v2/net/ghttp"
    16  	"github.com/wangyougui/gf/v2/test/gtest"
    17  	"github.com/wangyougui/gf/v2/util/guid"
    18  )
    19  
    20  func Test_Router_Group_Hook1(t *testing.T) {
    21  	s := g.Server(guid.S())
    22  	group := s.Group("/api")
    23  	group.GET("/handler", func(r *ghttp.Request) {
    24  		r.Response.Write("1")
    25  	})
    26  	group.ALL("/handler", func(r *ghttp.Request) {
    27  		r.Response.Write("0")
    28  	}, ghttp.HookBeforeServe)
    29  	group.ALL("/handler", func(r *ghttp.Request) {
    30  		r.Response.Write("2")
    31  	}, ghttp.HookAfterServe)
    32  
    33  	s.SetDumpRouterMap(false)
    34  	s.Start()
    35  	defer s.Shutdown()
    36  
    37  	time.Sleep(100 * time.Millisecond)
    38  	gtest.C(t, func(t *gtest.T) {
    39  		client := g.Client()
    40  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
    41  		t.Assert(client.GetContent(ctx, "/api/handler"), "012")
    42  		t.Assert(client.PostContent(ctx, "/api/handler"), "02")
    43  		t.Assert(client.GetContent(ctx, "/api/ThisDoesNotExist"), "Not Found")
    44  	})
    45  }
    46  
    47  func Test_Router_Group_Hook2(t *testing.T) {
    48  	s := g.Server(guid.S())
    49  	group := s.Group("/api")
    50  	group.GET("/handler", func(r *ghttp.Request) {
    51  		r.Response.Write("1")
    52  	})
    53  	group.GET("/*", func(r *ghttp.Request) {
    54  		r.Response.Write("0")
    55  	}, ghttp.HookBeforeServe)
    56  	group.GET("/*", func(r *ghttp.Request) {
    57  		r.Response.Write("2")
    58  	}, ghttp.HookAfterServe)
    59  
    60  	s.SetDumpRouterMap(false)
    61  	s.Start()
    62  	defer s.Shutdown()
    63  
    64  	time.Sleep(100 * time.Millisecond)
    65  	gtest.C(t, func(t *gtest.T) {
    66  		client := g.Client()
    67  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
    68  		t.Assert(client.GetContent(ctx, "/api/handler"), "012")
    69  		t.Assert(client.PostContent(ctx, "/api/handler"), "Not Found")
    70  		t.Assert(client.GetContent(ctx, "/api/ThisDoesNotExist"), "02")
    71  		t.Assert(client.PostContent(ctx, "/api/ThisDoesNotExist"), "Not Found")
    72  	})
    73  }