summaryrefslogtreecommitdiffstats
path: root/http/http_test.go
blob: 603dce33a94760a7bb888a48437bbffdd80e7f2d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package http_test

import (
	"context"
	httpServer "go.sudomsg.com/kit/http"
	"io"
	"net/http"
	"strings"
	"testing"
	"time"
)

func TestRunHTTPServers(t *testing.T) {
	t.Parallel()
	t.Run("basic serve and shutdown", func(t *testing.T) {
		t.Parallel()
		ctx := t.Context()
		handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			io.WriteString(w, "hello")
		})

		ln := newListener(t)
		addr := ln.Addr().String()

		ctx, cancel := context.WithCancel(ctx)
		defer cancel()

		go func() {
			// Wait for server to be ready
			time.Sleep(200 * time.Millisecond)

			r, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+addr, nil)
			resp, err := http.DefaultClient.Do(r)
			if err != nil {
				t.Errorf("http.Do error: %v", err)
				return
			}
			defer resp.Body.Close()

			body, _ := io.ReadAll(resp.Body)
			if got := strings.TrimSpace(string(body)); got != "hello" {
				t.Errorf("unexpected response body: %q", got)
			}

			cancel() // shutdown the server
		}()

		err := httpServer.RunHTTPServers(ctx, httpServer.Listeners{ln}, handler)
		if err != nil {
			t.Fatalf("RunHTTPServers failed: %v", err)
		}
	})
}