-
Notifications
You must be signed in to change notification settings - Fork 0
/
hijack.go
45 lines (40 loc) · 1.02 KB
/
hijack.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
package hijack
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/honestbank/hijack/v2/internal/transport"
"github.com/honestbank/hijack/v2/request"
)
func GetVariableAs[T any](r *request.GraphqlRequest, name string) (T, error) {
var output T
variable, ok := r.Variables[name]
if !ok {
return output, fmt.Errorf("variable %s not found", name)
}
err := json.Unmarshal(variable, &output)
if err != nil {
return output, err
}
return output, nil
}
type Hijacker func(o *request.GraphqlRequest) (string, error)
// Start a hijacking session where all requests going to `host` will be mocked.
func Start(hijacker Hijacker, host string) func() {
return transport.Hijack(func(r *http.Request) (*http.Response, error) {
parsedRequest, err := request.Parse(r)
if err != nil {
return nil, err
}
response, err := hijacker(parsedRequest)
if err != nil {
return nil, err
}
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(response)),
}, nil
}, host)
}