-
Notifications
You must be signed in to change notification settings - Fork 36
/
memconn_example_http_test.go
66 lines (57 loc) · 1.57 KB
/
memconn_example_http_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
56
57
58
59
60
61
62
63
64
65
66
package memconn_test
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"github.com/akutz/memconn"
)
// ExampleHTTP illustrates an HTTP server and client that communicate
// over an unbuffered, in-memory connection.
func Example_hTTP() {
// Create a new, named listener using the in-memory, unbuffered
// network "memu" and address "MyNamedNetwork".
lis, err := memconn.Listen("memu", "MyNamedNetwork")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Create a new HTTP mux and register a handler with it that responds
// to requests with the text "Hello, world.".
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, world.")
}))
// Start an HTTP server using the HTTP mux.
go func() {
if err := http.Serve(lis, mux); err != http.ErrServerClosed {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}()
// Create a new HTTP client that delegates its dialing to memconn.
client := &http.Client{
Transport: &http.Transport{
DialContext: func(
ctx context.Context, _, _ string) (net.Conn, error) {
return memconn.DialContext(ctx, "memu", "MyNamedNetwork")
},
},
}
// Get the root resource and copy its response to os.Stdout. Please
// note that the URL must contain a host name, even if it's ignored.
rep, err := client.Get("http://host/")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer rep.Body.Close()
if _, err := io.Copy(os.Stdout, rep.Body); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Output: Hello, world.
}