-
Notifications
You must be signed in to change notification settings - Fork 0
/
petition.go
executable file
·97 lines (89 loc) · 2.53 KB
/
petition.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
96
97
package minigrush
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"code.google.com/p/go-uuid/uuid"
)
//Constants names of the header fields used by Rush
const (
RelayerHost = "X-Relayer-Host"
RelayerProtocol = "X-Relayer-Protocol"
)
//Petition is a representation from the request received. Header fields are cooked to represent
//the final request meant to be sent to the target host. The relayer's own fields are removed
type Petition struct {
Id string
TargetHost string
TargetScheme string
Method string // GET, POST, PUT, etc.
URL *url.URL
URLString string
Proto string // "HTTP/1.0"
Header http.Header
Trailer http.Header
Body []byte
RemoteAddr string
RequestURI string
Host string
Created time.Time
}
//newPetition creates a petition from an http.Request. It checks header fields and make necessary transformations.
//The body is read and saved as a slice of byte.
func newPetition(original *http.Request) (*Petition, error) {
targetHost := original.Header.Get(RelayerHost)
if targetHost == "" {
return nil, fmt.Errorf("minigrush: Missing mandatory header %s", RelayerHost)
}
original.Header.Del(RelayerHost)
scheme := strings.ToLower(original.Header.Get(RelayerProtocol))
switch scheme {
case "http", "https":
case "":
scheme = "http"
default:
return nil, fmt.Errorf("minigrush: Unsupported protocol %s", scheme)
}
original.Header.Del(RelayerProtocol)
//save body content
body, err := ioutil.ReadAll(original.Body)
if err != nil {
return nil, err
}
id := uuid.New()
relayedRequest := &Petition{
Id: id,
Body: body,
Method: original.Method,
URL: original.URL,
Proto: original.Proto, // "HTTP/1.0"
Header: original.Header,
Trailer: original.Trailer,
RemoteAddr: original.RemoteAddr,
RequestURI: original.RequestURI,
TargetHost: targetHost,
TargetScheme: scheme,
Created: time.Now()}
return relayedRequest, nil
}
//Request returns the original http.Request with the body restored as a CloserReader
//so it can be used to do a request to the original target host
func (p *Petition) Request() (*http.Request, error) {
p.URL.Host = p.TargetHost
p.URL.Scheme = p.TargetScheme
p.URLString = p.URL.String()
req, err := http.NewRequest(
p.Method,
p.URLString,
ioutil.NopCloser(bytes.NewReader(p.Body))) //Restore body as ReadCloser
if err != nil {
return nil, err
}
req.Header = p.Header
req.Trailer = p.Trailer
return req, nil
}