-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
55 lines (46 loc) · 1.11 KB
/
server_test.go
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
package natshttp
import (
"context"
"io"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
"golang.org/x/sync/errgroup"
)
func ExampleServer_basic() {
// connect to NATS
conn, err := nats.Connect(nats.DefaultURL)
if err != nil {
panic(err)
}
// create a router
router := chi.NewRouter()
router.Head("/hello", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "world")
})
// create a server
srv := Server{
Conn: conn,
Subject: "foo.bar", // it will listen for requests on the 'foo.bar.>' subject hierarchy
Group: "my-server", // name of the queue group when subscribing, used for load balancing
Handler: router,
}
// create a context and an error group for running processes
ctx, cancel := context.WithCancel(context.Background())
eg := errgroup.Group{}
// start listening
eg.Go(func() error {
return srv.Listen(ctx)
})
// wait 10 seconds then cancel the context
eg.Go(func() error {
<-time.After(10 * time.Second)
cancel()
return nil
})
// wait for the listener to complete
if err = eg.Wait(); err != nil {
panic(err)
}
}