github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/pkg/trace/inject/http-server/http_server_test.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package traceinject
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  	"net/http"
    21  	"os"
    22  	"runtime"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/stretchr/testify/assert"
    27  
    28  	"github.com/erda-project/erda-infra/pkg/trace/inject/hook"
    29  )
    30  
    31  func init() {
    32  	os.Setenv(hook.EnvTraceHookEnable, "true")
    33  	hook.Hook(serveHTTP, wrappedHTTPHandler, originalServeHTTP)
    34  }
    35  
    36  func TestHookHttpServer(t *testing.T) {
    37  	// start a http server listen on 8083
    38  	http.HandleFunc("/test",
    39  		func(w http.ResponseWriter, r *http.Request) {
    40  			fmt.Println(runtime.GOARCH)
    41  			if runtime.GOARCH == "amd64" {
    42  				h := getServerHandler(r.Context()) // injected by hook
    43  				assert.NotNil(t, h)
    44  			}
    45  			w.Write([]byte("hello world"))
    46  		},
    47  	)
    48  	s := &http.Server{Addr: ":8083"}
    49  	go func() {
    50  		if err := s.ListenAndServe(); err != nil {
    51  			t.Fatal(err)
    52  		}
    53  	}()
    54  	time.Sleep(time.Second)
    55  	// call api
    56  	resp, err := http.Get("http://localhost:8083/test")
    57  	if err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	if resp.StatusCode != http.StatusOK {
    61  		t.Fatal("http status code not match")
    62  	}
    63  	// print body
    64  	b, _ := io.ReadAll(resp.Body)
    65  	t.Log(string(b))
    66  	assert.Equal(t, "hello world", string(b)) // check original response
    67  }