This repository has been archived by the owner on May 24, 2020. It is now read-only.
forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
74 lines (65 loc) · 1.61 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
67
68
69
70
71
72
73
74
package rest
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
)
// Inherit from http.Request, and provide additional methods.
type Request struct {
*http.Request
// map of parameters that have been matched in the URL Path.
PathParams map[string]string
}
// Provide a convenient access to the PathParams map
func (self *Request) PathParam(name string) string {
return self.PathParams[name]
}
// Read the request body and decode the JSON using json.Unmarshal
func (self *Request) DecodeJsonPayload(v interface{}) error {
content, err := ioutil.ReadAll(self.Body)
self.Body.Close()
if err != nil {
return err
}
err = json.Unmarshal(content, v)
if err != nil {
return err
}
return nil
}
// Returns a URL structure for the base (scheme + host) of the application,
// without the trailing slash in the host
func (self *Request) UriBase() url.URL {
scheme := self.URL.Scheme
if scheme == "" {
scheme = "http"
}
host := self.Host
if len(host) > 0 && host[len(host)-1] == '/' {
host = host[:len(host)-1]
}
url := url.URL{
Scheme: scheme,
Host: host,
}
return url
}
// Returns an URL structure from the base and an additional path.
func (self *Request) UriFor(path string) url.URL {
baseUrl := self.UriBase()
baseUrl.Path = path
return baseUrl
}
// Returns an URL structure from the base, the path and the parameters.
func (self *Request) UriForWithParams(path string, parameters map[string][]string) url.URL {
query := url.Values{}
for k, v := range parameters {
for _, vv := range v {
query.Add(k, vv)
}
}
baseUrl := self.UriFor(path)
baseUrl.RawQuery = query.Encode()
return baseUrl
}