-
Notifications
You must be signed in to change notification settings - Fork 69
/
util.go
110 lines (88 loc) · 2.05 KB
/
util.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/streadway/amqp"
)
func LogOnError(err error) {
if err != nil {
fmt.Printf("ERROR - %s\n", err)
}
}
func PanicOnError(err error) {
if err != nil {
panic(err)
}
}
func setupChannel() (*amqp.Connection, *amqp.Channel, error) {
url := os.Getenv("AMQP_URL")
conn, err := amqp.Dial(url)
if err != nil {
LogOnError(err)
return nil, nil, err
}
channel, err := conn.Channel()
if err != nil {
LogOnError(err)
return nil, nil, err
}
err = channel.Qos(1, 0, false)
if err != nil {
LogOnError(err)
return nil, nil, err
}
log.Printf("setup channel success!")
return conn, channel, nil
}
func cloneToPublishMsg(msg *amqp.Delivery) *amqp.Publishing {
newMsg := amqp.Publishing{
Headers: msg.Headers,
ContentType: msg.ContentType,
ContentEncoding: msg.ContentEncoding,
DeliveryMode: msg.DeliveryMode,
Priority: msg.Priority,
CorrelationId: msg.CorrelationId,
ReplyTo: msg.ReplyTo,
Expiration: msg.Expiration,
MessageId: msg.MessageId,
Timestamp: msg.Timestamp,
Type: msg.Type,
UserId: msg.UserId,
AppId: msg.AppId,
Body: msg.Body,
}
return &newMsg
}
func newHttpClient(maxIdleConns, maxIdleConnsPerHost, idleConnTimeout int) *http.Client {
tr := &http.Transport{
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
IdleConnTimeout: time.Duration(idleConnTimeout) * time.Second,
}
client := &http.Client{
Transport: tr,
}
return client
}
func notifyUrl(client *http.Client, url string, body []byte) int {
req, err := http.NewRequest("POST", url, bytes.NewReader(body))
if err != nil {
log.Printf("notify url create req fail: %s", err)
return 0
}
req.Header.Set("Content-Type", "application/json")
response, err := client.Do(req)
if err != nil {
log.Printf("notify url %s fail: %s", url, err)
return 0
}
defer response.Body.Close()
io.Copy(ioutil.Discard, response.Body)
return response.StatusCode
}