-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.go
103 lines (91 loc) · 2.35 KB
/
utils.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
98
99
100
101
102
103
/******************************************************************************
*
* Copyright 2020 SAP SE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package keppel
import (
"net/http"
"net/url"
"strings"
"time"
)
// OriginalRequestURL returns the URL that the original requester used when
// sending an HTTP request. This inspects the X-Forwarded-* set of headers to
// identify reverse proxying.
func OriginalRequestURL(r *http.Request) url.URL {
u := url.URL{
Path: r.URL.Path,
RawQuery: r.URL.RawQuery,
}
// case 1: we are behind a reverse proxy
u.Host = r.Header.Get("X-Forwarded-Host")
if u.Host != "" {
u.Scheme = r.Header.Get("X-Forwarded-Proto")
if u.Scheme == "" {
u.Scheme = "http"
}
return u
}
// case 2: we are not behind a reverse proxy, but the Host header indicates how the user reached us
if r.Host != "" {
u.Host = r.Host
u.Scheme = "http"
return u
}
// case 3: no idea how the user got here - don't include any guesses in the URL
return u
}
// AppendQuery adds additional query parameters to an existing unparsed URL.
func AppendQuery(urlStr string, query url.Values) string {
if strings.Contains(urlStr, "?") {
return urlStr + "&" + query.Encode()
}
return urlStr + "?" + query.Encode()
}
// MaybeTimeToUnix casts a time.Time instance into its UNIX timestamp while preserving nil-ness.
func MaybeTimeToUnix(t *time.Time) *int64 {
if t == nil {
return nil
}
val := t.Unix()
return &val
}
func MinMaybeTime(t1, t2 *time.Time) *time.Time {
if t1 == nil {
return t2
}
if t2 == nil {
return t1
}
if t1.Before(*t2) {
return t1
} else {
return t2
}
}
func MaxMaybeTime(t1, t2 *time.Time) *time.Time {
if t1 == nil {
return t2
}
if t2 == nil {
return t1
}
if t1.After(*t2) {
return t1
} else {
return t2
}
}