github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/http/server_test.go (about)

     1  package http_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"net/http"
     8  	"net/http/httputil"
     9  	"os"
    10  	"strconv"
    11  	"testing"
    12  	"time"
    13  
    14  	. "github.com/onsi/gomega"
    15  
    16  	"github.com/machinefi/w3bstream/pkg/depends/base/types"
    17  	confhttp "github.com/machinefi/w3bstream/pkg/depends/conf/http"
    18  	"github.com/machinefi/w3bstream/pkg/depends/conf/logger"
    19  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport"
    20  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
    21  	"github.com/machinefi/w3bstream/pkg/depends/kit/kit"
    22  )
    23  
    24  type GetSome struct {
    25  	httpx.MethodGet
    26  }
    27  
    28  func (GetSome) Path() string {
    29  	return "/some"
    30  }
    31  
    32  func (GetSome) Output(ctx context.Context) (interface{}, error) {
    33  	html := httpx.NewHTML()
    34  
    35  	return httpx.WrapMeta(
    36  		httpx.Metadata("Cache-Control", "no-cache"),
    37  	)(html), nil
    38  }
    39  
    40  type GetOther struct {
    41  	httpx.MethodGet
    42  }
    43  
    44  func (GetOther) Path() string { return "/other" }
    45  
    46  func (GetOther) Output(ctx context.Context) (interface{}, error) {
    47  	client := confhttp.ClientEndpoint{
    48  		Endpoint: types.Endpoint{
    49  			Scheme:   "http",
    50  			Hostname: "0.0.0.0",
    51  			Port:     1234,
    52  		},
    53  	}
    54  
    55  	client.SetDefault()
    56  	client.Init()
    57  
    58  	_, _ = client.Do(ctx, confhttp.NewRequest(http.MethodGet, "/some")).Into(nil)
    59  
    60  	return nil, nil
    61  }
    62  
    63  func TestHttp(t *testing.T) {
    64  	ctx, l := logger.NewSpanContext(context.Background(), "TestHttp")
    65  	defer l.End()
    66  
    67  	servers := []*confhttp.Server{
    68  		{Protocol: "http", Port: 1234},
    69  		{Protocol: "http", Port: 3456},
    70  		{Protocol: "http+unix", Addr: "/tmp/server3.sock"},
    71  	}
    72  	clients := make([]*confhttp.ClientEndpoint, 0, len(servers))
    73  
    74  	router := kit.NewRouter(httptransport.Group("/"))
    75  	router.Register(kit.NewRouter(&GetSome{}))
    76  	router.Register(kit.NewRouter(&GetOther{}))
    77  
    78  	for i, srv := range servers {
    79  		srv.SetDefault()
    80  		go func(i int, srv *confhttp.Server) {
    81  			err := srv.Serve(router)
    82  			fmt.Printf("server#%d: %v", i, err)
    83  			time.Sleep(5 * time.Second)
    84  			p, _ := os.FindProcess(os.Getpid())
    85  			_ = p.Signal(os.Interrupt)
    86  		}(i, srv)
    87  
    88  		cli := &confhttp.ClientEndpoint{
    89  			Endpoint: types.Endpoint{
    90  				Scheme:   srv.Protocol,
    91  				Hostname: srv.Addr,
    92  				Port:     uint16(srv.Port),
    93  			},
    94  		}
    95  		cli.SetDefault()
    96  		cli.Init()
    97  
    98  		clients = append(clients, cli)
    99  	}
   100  
   101  	time.Sleep(time.Second)
   102  
   103  	printer := func(rsp *http.Response) {
   104  		data, _ := httputil.DumpResponse(rsp, true)
   105  		fmt.Println(string(data))
   106  	}
   107  
   108  	for i := 0; i < len(servers); i++ {
   109  		idx := strconv.Itoa(i + 1)
   110  		cli := clients[i]
   111  		srv := servers[i]
   112  
   113  		baseURL := srv.Protocol + "://" + srv.Addr
   114  		if srv.Port != 0 {
   115  			baseURL += ":" + strconv.Itoa(srv.Port)
   116  		}
   117  		if srv.Protocol == "http+unix" {
   118  			baseURL = "http://localhost"
   119  		}
   120  
   121  		// use confhttp.ClientEndpoint
   122  		t.Run("GetSome#"+idx, func(t *testing.T) {
   123  			meta, err := cli.Do(ctx, confhttp.NewRequest(http.MethodGet, "/some")).Into(nil)
   124  			NewWithT(t).Expect(err).To(BeNil())
   125  			NewWithT(t).Expect(http.Header(meta).Get("b3")).NotTo(BeEmpty())
   126  		})
   127  		t.Run("GetOther#"+idx, func(t *testing.T) {
   128  			meta, err := cli.Do(ctx, confhttp.NewRequest(http.MethodGet, "/other")).Into(nil)
   129  			NewWithT(t).Expect(err).To(BeNil())
   130  			NewWithT(t).Expect(http.Header(meta).Get("b3")).NotTo(BeEmpty())
   131  		})
   132  
   133  		// use http.DefaultClient
   134  		if srv.Protocol == "http+unix" {
   135  			http.DefaultClient.Transport = &http.Transport{
   136  				DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
   137  					return net.Dial("unix", srv.Addr)
   138  				},
   139  			}
   140  		} else {
   141  			http.DefaultClient.Transport = http.DefaultTransport
   142  		}
   143  
   144  		t.Run("Head#"+idx, func(t *testing.T) {
   145  			resp, err := http.Head(baseURL)
   146  			NewWithT(t).Expect(err).To(BeNil())
   147  			printer(resp)
   148  		})
   149  		t.Run("Options#"+idx, func(t *testing.T) {
   150  			req, _ := http.NewRequest(http.MethodOptions, fmt.Sprintf(baseURL+"/some"), nil)
   151  			req.Header.Add("Origin", "http://localhost:3000")
   152  			req.Header.Add("Access-Control-Request-Method", http.MethodPost)
   153  			req.Header.Set("Access-Control-Request-Headers", "authorization,content-type")
   154  			req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36")
   155  			resp, err := http.DefaultClient.Do(req)
   156  			NewWithT(t).Expect(err).To(BeNil())
   157  			printer(resp)
   158  		})
   159  	}
   160  	time.Sleep(1 * time.Second)
   161  }