-
Notifications
You must be signed in to change notification settings - Fork 6
/
request.go
45 lines (41 loc) · 1 KB
/
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
// Copyright (c) 2016, Janoš Guljaš <[email protected]>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"net"
"net/http"
"strings"
)
// GetRequestIPs returns all possible IPs found in HTTP request.
func GetRequestIPs(r *http.Request, realIPHeaders ...string) string {
if realIPHeaders == nil {
realIPHeaders = []string{"X-Forwarded-For", "X-Real-Ip"}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
ips := []string{ip}
for _, key := range realIPHeaders {
v := r.Header.Get(key)
if v != "" {
ips = append(ips, v)
}
}
return strings.Join(ips, ", ")
}
// GetRequestEndpoint returns request's host perpended with protocol:
// protocol://host.
func GetRequestEndpoint(r *http.Request) string {
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
if r.TLS == nil {
proto = "http"
} else {
proto = "https"
}
}
return proto + "://" + r.Host
}