trpc.group/trpc-go/trpc-go@v1.0.3/http/client_test.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package http_test
    15  
    16  import (
    17  	"bytes"
    18  	"io"
    19  	"net/http"
    20  	"net/http/httptest"
    21  	"testing"
    22  
    23  	"github.com/stretchr/testify/require"
    24  
    25  	thttp "trpc.group/trpc-go/trpc-go/http"
    26  )
    27  
    28  func TestStdHTTPClient(t *testing.T) {
    29  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    30  		if r.Method == "PUT" {
    31  			w.WriteHeader(http.StatusInternalServerError)
    32  			w.Write([]byte("unsupported method"))
    33  			return
    34  		}
    35  		if _, err := io.Copy(w, r.Body); err != nil {
    36  			w.Write([]byte(err.Error()))
    37  		}
    38  	}))
    39  	defer ts.Close()
    40  
    41  	body := []byte(`{"name": "xyz"}`)
    42  	cli := thttp.NewStdHTTPClient("trpc.http.stdclient.test")
    43  
    44  	rsp1, err1 := cli.Get(ts.URL)
    45  	require.Nil(t, err1)
    46  	require.Equal(t, http.StatusOK, rsp1.StatusCode)
    47  	require.Equal(t, int64(0), rsp1.ContentLength)
    48  
    49  	rsp2, err2 := cli.Post(ts.URL, "application/json", bytes.NewBuffer(body))
    50  	require.Nil(t, err2)
    51  	require.Equal(t, http.StatusOK, rsp2.StatusCode)
    52  
    53  	rspBody2, err := io.ReadAll(rsp2.Body)
    54  	defer rsp2.Body.Close()
    55  	require.Nil(t, err)
    56  	require.Equal(t, body, rspBody2)
    57  
    58  	req, _ := http.NewRequest("PUT", ts.URL, bytes.NewBuffer(body))
    59  	rsp3, err3 := cli.Do(req)
    60  	require.Nil(t, err3)
    61  	require.Equal(t, http.StatusInternalServerError, rsp3.StatusCode)
    62  
    63  	rspBody3, err := io.ReadAll(rsp3.Body)
    64  	defer rsp3.Body.Close()
    65  	require.Nil(t, err)
    66  	require.Equal(t, "unsupported method", string(rspBody3))
    67  }