-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgomopost.go
71 lines (59 loc) · 1.36 KB
/
gomopost.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
package gomopost
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// GomoPoster is an interface to post message to chatserver
type GomoPoster interface {
Post(name, msg string) error
}
type gomopost struct {
address string
}
// NewClient returns an instance of GomoPoster
func NewClient(address string) GomoPoster {
return &gomopost{
address: address,
}
}
type payload struct {
Name string `json:"name"`
Body string `json:"body"`
}
func (g *gomopost) Post(name, msg string) error {
p := payload{
Name: name,
Body: msg,
}
pb, err := json.Marshal(p)
if err != nil {
return fmt.Errorf("failed to marshal parameters: %s", err.Error())
}
buf := bytes.NewBuffer(pb)
req, err := http.NewRequest("POST", g.address+"/messages", buf)
if err != nil {
return fmt.Errorf("failed to create post request: %s", err.Error())
}
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
req = req.WithContext(ctx)
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("post request failed: %s", err.Error())
}
defer func() {
if e := resp.Body.Close(); e != nil {
fmt.Printf("failed to close response body: %s", e.Error())
}
}()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %s", err.Error())
}
return nil
}