forked from the-gigi/delinkcious
/
client.go
69 lines (60 loc) · 1.65 KB
/
client.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
package user_client
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
httptransport "github.com/go-kit/kit/transport/http"
om "github.com/rotk2022/delinkcious/pkg/object_model"
)
func NewClient(baseURL string) (om.UserManager, error) {
// Quickly sanitize the instance string.
if !strings.HasPrefix(baseURL, "http") {
baseURL = "http://" + baseURL
}
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
registerEndpoint := httptransport.NewClient(
"POST",
copyURL(u, "/register"),
encodeHTTPGenericRequest,
decodeSimpleResponse).Endpoint()
loginEndpoint := httptransport.NewClient(
"POST",
copyURL(u, "/login"),
encodeHTTPGenericRequest,
decodeLoginResponse).Endpoint()
logoutEndpoint := httptransport.NewClient(
"POST",
copyURL(u, "/logout"),
encodeHTTPGenericRequest,
decodeSimpleResponse).Endpoint()
// Returning the EndpointSet as an interface relies on the
// EndpointSet implementing the Service methods. That's just a simple bit
// of glue code.
return EndpointSet{
RegisterEndpoint: registerEndpoint,
LoginEndpoint: loginEndpoint,
LogoutEndpoint: logoutEndpoint,
}, nil
}
func copyURL(base *url.URL, path string) *url.URL {
next := *base
next.Path = path
return &next
}
// encodeHTTPGenericRequest is a transport/http.EncodeRequestFunc that
// JSON-encodes any request to the request body. Primarily useful in a client.
func encodeHTTPGenericRequest(_ context.Context, r *http.Request, request interface{}) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(request); err != nil {
return err
}
r.Body = ioutil.NopCloser(&buf)
return nil
}