-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
54 lines (45 loc) · 1011 Bytes
/
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
package rest
import (
"encoding/json"
"errors"
"io"
"net/http"
"reflect"
"strings"
)
var ErrEmptyRequest = errors.New("empty request")
var ErrNotPointer = errors.New("not pointer provided")
// ReadBody - read body from request and trying to unmarshal to provided struct
func ReadBody(r *http.Request, str interface{}) error {
if r == nil {
return ErrEmptyRequest
}
if reflect.ValueOf(str).Kind() != reflect.Ptr {
return ErrNotPointer
}
body, err := io.ReadAll(r.Body)
if err != nil && err != io.EOF {
return err
}
defer func() { _ = r.Body.Close() }()
if err = json.Unmarshal(body, str); err != nil {
return err
}
return nil
}
func GetAddr(r *http.Request) string {
addr := r.RemoteAddr
if CFAddr := r.Header.Get("CF-Connecting-IP"); CFAddr != "" {
addr = CFAddr
}
if addr == "" {
addr = r.Header.Get("X-Forwarded-For")
}
if addr == "" {
addr = r.Header.Get("X-Real-Ip")
}
if strings.Count(addr, ":") == 1 {
addr = strings.Split(addr, ":")[0]
}
return addr
}