-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
69 lines (61 loc) · 1.57 KB
/
Copy pathmain.go
File metadata and controls
69 lines (61 loc) · 1.57 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
package pier
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"github.com/brandonbloom/httpie-go"
)
func Main(handler http.Handler) {
peer := &Peer{
Handler: handler,
}
peer.Main()
}
// Peer configures Pier's in-process HTTP exchange.
type Peer struct {
// Handler receives the constructed HTTP request directly, without opening
// a network socket. Handler must be non-nil.
Handler http.Handler
// BaseContext, if non-nil, supplies the base context for each request.
BaseContext func(*http.Request) context.Context
// Stdin is used for request body input. If nil, os.Stdin is used.
Stdin io.Reader
// Stdout receives response output. If nil, os.Stdout is used.
Stdout io.Writer
// Stderr receives usage and informational output. If nil, os.Stderr is used.
Stderr io.Writer
}
func (p *Peer) RoundTrip(req *http.Request) (*http.Response, error) {
recorder := httptest.NewRecorder()
if p.BaseContext != nil {
req = req.WithContext(p.BaseContext(req))
}
p.Handler.ServeHTTP(recorder, req)
res := recorder.Result()
return res, nil
}
func (p *Peer) Main() {
if err := httpie.Main(p.options()); err != nil {
stderr := p.Stderr
if stderr == nil {
stderr = os.Stderr
}
fmt.Fprintf(stderr, "ERROR: %v\n", err)
os.Exit(1)
}
}
// Run executes Pier with explicit command-line arguments, including argv[0].
func (p *Peer) Run(argv []string) error {
return httpie.Run(argv, p.options())
}
func (p *Peer) options() *httpie.Options {
return &httpie.Options{
Transport: p,
Stdin: p.Stdin,
Stdout: p.Stdout,
Stderr: p.Stderr,
}
}