-
Notifications
You must be signed in to change notification settings - Fork 0
/
std_request.go
68 lines (56 loc) · 1.7 KB
/
std_request.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
package client
import (
"context"
"github.com/hopeio/cherry/utils/log"
"io"
"net/http"
urlpkg "net/url"
"strings"
)
type replaceHttpRequest http.Request
func NewReplaceHttpRequest(r *http.Request) *replaceHttpRequest {
return (*replaceHttpRequest)(r)
}
func ReplaceHttpRequest(r *http.Request, url, method string, body io.ReadCloser) *http.Request {
return NewReplaceHttpRequest(r).Replace(url, method, body).StdHttpRequest()
}
func (r *replaceHttpRequest) Replace(url, method string, body io.ReadCloser) *replaceHttpRequest {
r.SetURL(url).SetMethod(method).SetBody(body)
return r
}
func (r *replaceHttpRequest) SetURL(url string) *replaceHttpRequest {
u, err := urlpkg.Parse(url)
if err != nil {
log.Error(err)
}
u.Host = removeEmptyPort(u.Host)
r.URL = u
r.Host = u.Host
return r
}
// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
// return true if the string includes a port.
func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
// removeEmptyPort strips the empty port in ":port" to ""
// as mandated by RFC 3986 Section 6.2.3.
func removeEmptyPort(host string) string {
if hasPort(host) {
return strings.TrimSuffix(host, ":")
}
return host
}
func (r *replaceHttpRequest) SetMethod(method string) *replaceHttpRequest {
r.Method = strings.ToUpper(method)
return r
}
func (r *replaceHttpRequest) SetBody(body io.ReadCloser) *replaceHttpRequest {
r.Body = body
return r
}
func (r *replaceHttpRequest) SetContext(ctx context.Context) *replaceHttpRequest {
stdr := (*http.Request)(r).WithContext(ctx)
return (*replaceHttpRequest)(stdr)
}
func (r *replaceHttpRequest) StdHttpRequest() *http.Request {
return (*http.Request)(r)
}