-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
66 lines (52 loc) · 1.22 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//go:generate ffjson -noencoder $GOFILE
package auth
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/pquerna/ffjson/ffjson"
)
// Request is a request
type Request struct {
Token string `json:"token"`
Refresh string `json:"refresh_token"`
Username string `json:"username"`
Password string `json:"password"`
}
func reader(r *http.Request) (io.Reader, error) {
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
rdr1 := bytes.NewReader(buf)
rdr2 := bytes.NewReader(buf)
r.Body = ioutil.NopCloser(rdr2)
return rdr1, nil
}
// ParseRequest parses a request from a http.Request
func ParseRequest(r *http.Request) (*Request, error) {
request := &Request{
Token: r.FormValue("token"),
Username: r.FormValue("username"),
Password: r.FormValue("password"),
Refresh: r.FormValue("refresh_token"),
}
contentType := r.Header.Get("Content-Type")
if tok := r.Header.Get("Bearer"); tok != "" {
request.Token = tok
}
if strings.Contains(contentType, "json") {
decoder := ffjson.NewDecoder()
reader, err := reader(r)
if err != nil {
return nil, err
}
err = decoder.DecodeReader(reader, request)
if err != nil {
return nil, err
}
}
return request, nil
}