-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
example_test.go
95 lines (78 loc) · 2.29 KB
/
example_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package vulcain_test
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"github.com/dunglas/vulcain"
)
func Example() {
handler := http.NewServeMux()
handler.Handle("/books.json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{
"title": "1984",
"genre": "dystopia",
"author": "/authors/orwell.json"
}`)
}))
handler.Handle("/authors/orwell.json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{
"name": "George Orwell",
"birthDate": "1903-06-25"
}`)
}))
backendServer := httptest.NewServer(handler)
defer backendServer.Close()
rpURL, err := url.Parse(backendServer.URL)
if err != nil {
log.Fatal(err)
}
vulcain := vulcain.New()
rpHandler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
r := req.WithContext(vulcain.CreateRequestContext(rw, req))
var wait bool
defer func() { vulcain.Finish(r, wait) }()
rp := httputil.NewSingleHostReverseProxy(rpURL)
rp.ModifyResponse = func(resp *http.Response) error {
if !vulcain.IsValidRequest(r) || !vulcain.IsValidResponse(r, resp.StatusCode, resp.Header) {
return nil
}
newBody, err := vulcain.Apply(r, rw, resp.Body, resp.Header)
if newBody == nil {
return err
}
wait = true
newBodyBuffer := bytes.NewBuffer(newBody)
resp.Body = io.NopCloser(newBodyBuffer)
return nil
}
rp.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
wait = false
}
rp.ServeHTTP(rw, req)
})
frontendProxy := httptest.NewServer(rpHandler)
defer frontendProxy.Close()
resp, err := http.Get(frontendProxy.URL + `/books.json?preload="/author"&fields="/title","/author"`)
if err != nil {
log.Fatal(err)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Go's HTTP client doesn't support HTTP/2 Server Push yet, so a Link rel=preload is added as fallback
// Browsers and other clients supporting Server Push will receive a push instead
fmt.Printf("%v\n\n", resp.Header.Values("Link"))
fmt.Printf("%s", b)
// Output:
// [</authors/orwell.json>; rel=preload; as=fetch]
//
// {"author":"/authors/orwell.json","title":"1984"}
}