github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_status_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/gogf/gf.
     6  
     7  // static service testing.
     8  
     9  package ghttp_test
    10  
    11  import (
    12  	"fmt"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/gogf/gf/frame/g"
    17  	"github.com/gogf/gf/net/ghttp"
    18  	"github.com/gogf/gf/test/gtest"
    19  )
    20  
    21  func Test_StatusHandler(t *testing.T) {
    22  	gtest.C(t, func(t *gtest.T) {
    23  		p, _ := ports.PopRand()
    24  		s := g.Server(p)
    25  		s.BindStatusHandlerByMap(map[int]ghttp.HandlerFunc{
    26  			404: func(r *ghttp.Request) { r.Response.WriteOver("404") },
    27  			502: func(r *ghttp.Request) { r.Response.WriteOver("502") },
    28  		})
    29  		s.BindHandler("/502", func(r *ghttp.Request) {
    30  			r.Response.WriteStatusExit(502)
    31  		})
    32  		s.SetDumpRouterMap(false)
    33  		s.SetPort(p)
    34  		s.Start()
    35  		defer s.Shutdown()
    36  		time.Sleep(100 * time.Millisecond)
    37  		client := g.Client()
    38  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    39  
    40  		t.Assert(client.GetContent("/404"), "404")
    41  		t.Assert(client.GetContent("/502"), "502")
    42  	})
    43  }
    44  
    45  func Test_StatusHandler_Multi(t *testing.T) {
    46  	gtest.C(t, func(t *gtest.T) {
    47  		p, _ := ports.PopRand()
    48  		s := g.Server(p)
    49  		s.BindStatusHandler(502, func(r *ghttp.Request) {
    50  			r.Response.WriteOver("1")
    51  		})
    52  		s.BindStatusHandler(502, func(r *ghttp.Request) {
    53  			r.Response.Write("2")
    54  		})
    55  		s.BindHandler("/502", func(r *ghttp.Request) {
    56  			r.Response.WriteStatusExit(502)
    57  		})
    58  		s.SetDumpRouterMap(false)
    59  		s.SetPort(p)
    60  		s.Start()
    61  		defer s.Shutdown()
    62  		time.Sleep(100 * time.Millisecond)
    63  		client := g.Client()
    64  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    65  
    66  		t.Assert(client.GetContent("/502"), "12")
    67  	})
    68  }