github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbhttp/srv_test.go (about)

     1  // Copyright 2018 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package kbhttp
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"net/http"
    10  	"testing"
    11  
    12  	"github.com/keybase/client/go/logger"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestSrv(t *testing.T) {
    17  	test := func(s ListenerSource) {
    18  		log := logger.NewTestLogger(t)
    19  		srv := NewSrv(log, s)
    20  		require.NoError(t, srv.Start())
    21  		srv.HandleFunc("/test", func(resp http.ResponseWriter, req *http.Request) {
    22  			fmt.Fprintf(resp, "success")
    23  		})
    24  		addr, err := srv.Addr()
    25  		require.NoError(t, err)
    26  		url := fmt.Sprintf("http://%s/test", addr)
    27  		t.Logf("url: %s", url)
    28  		resp, err := http.Get(url)
    29  		require.NoError(t, err)
    30  		out, err := io.ReadAll(resp.Body)
    31  		require.NoError(t, err)
    32  		require.Equal(t, "success", string(out))
    33  		<-srv.Stop()
    34  	}
    35  	test(NewAutoPortListenerSource())
    36  	test(NewPortRangeListenerSource(7000, 8000))
    37  	test(NewRandomPortRangeListenerSource(7000, 8000))
    38  }