-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
83 lines (73 loc) · 2.09 KB
/
examples_test.go
File metadata and controls
83 lines (73 loc) · 2.09 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package httpsrv_test
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"testing"
"time"
"github.com/ainvaltin/httpsrv"
)
// example of a simple service which only has a http server (ie no need to use errgroup)
func ExampleRun() {
// any mux which implements http.Handler can be used, ie gin, echo, gorilla...
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello, world")
})
// context to manage server's lifetime - when interrupt signal is sent the
// ctx will be cancelled and server stops
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
go func() {
<-ctx.Done()
stop()
}()
err := httpsrv.Run(ctx, &http.Server{Addr: "127.0.0.1:8080", Handler: mux})
fmt.Println("server exited:", err)
}
// Listener parameter is useful for tests where server is running on a random port
// which the test needs to know in order to make request to it.
func ExampleListener() {
// this would be a parameter of a Test func ie "func TestXXX(t *testing.T)"
var t testing.T
// open listener on random free port
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to create listener: %v", err)
}
defer ln.Close()
// start the http server on the port
ctx, cancel := context.WithCancel(context.Background())
srvErr := make(chan error, 1)
go func() {
srvErr <- httpsrv.Run(ctx,
&http.Server{Handler: http.NotFoundHandler()},
httpsrv.Listener(ln),
)
}()
// make a request to the server
c := &http.Client{Timeout: time.Second}
rsp, err := c.Get(fmt.Sprintf("http://%s", ln.Addr().String()))
if err != nil {
t.Errorf("GET request returned unexpected error: %v", err)
}
if rsp == nil {
t.Error("unexpectedly GET request returned nil response")
}
// stop the server
cancel()
select {
case <-time.After(time.Second):
t.Fatal("server didn't stop within timeout")
case err := <-srvErr:
if err == nil {
t.Fatal("unexpectedly Run returned nil error")
}
if !errors.Is(err, context.Canceled) {
t.Errorf("expected %q, got %q", context.Canceled, err)
}
}
}