File: queue.go

package info (click to toggle)
golang-github-denverdino-aliyungo 0.0~git20180921.13fa8aa-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,824 kB
  • sloc: xml: 1,359; makefile: 3
file content (115 lines) | stat: -rw-r--r-- 2,281 bytes parent folder | download | duplicates (3)
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
111
112
113
114
115
package mns

import (
	"encoding/xml"
	"io/ioutil"
	"net/http"
	"strconv"
)

//队列接口PATH
//POST /queues/$queueName/messages HTTP/1.1
//GET /queues/$queueName/messages?waitseconds=10 HTTP/1.1
//DELETE /queues/$queueName/messages?ReceiptHandle=<receiptHandle> HTTP/1.1
func getPath(queue string) string {
	return "/queues/" + queue + "/messages"
}

//发送队列消息
func (queue *Queue) Send(time int64, message []byte) (msg MsgSend, err error) {
	req := &request{
		endpoint:    queue.Endpoint,
		method:      http.MethodPost,
		path:        getPath(queue.QueueName),
		payload:     message,
		contentType: "text/xml",
		headers:     map[string]string{},
	}

	response, err := queue.doRequest(req)
	if err != nil {
		return
	}

	defer response.Body.Close()
	//err = xml.NewDecoder(response.Body).Decode(msg)

	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}
	//fmt.Printf("receive message: %s \n", data)
	err = xml.Unmarshal(data, &msg)

	if err != nil {
		return
	}

	return

}

//消费队列消息
func (queue *Queue) Receive(messageChan chan MsgReceive, errChan chan error) {
	req := &request{
		endpoint: queue.Endpoint,
		method:   http.MethodGet,
		path:     getPath(queue.QueueName),
		params: map[string]string{
			"waitseconds": strconv.Itoa(5),
		},
		payload:     nil,
		contentType: "text/xml",
		headers:     map[string]string{},
	}

	response, err := queue.doRequest(req)
	if err != nil {
		errChan <- err
		return
	}

	defer response.Body.Close()
	rs := MsgReceive{}
	//err = xml.NewDecoder(response.Body).Decode(rs)

	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		errChan <- err
		return
	}
	//fmt.Printf("receive message: %s \n", data)
	err = xml.Unmarshal(data, &rs)

	if err != nil {
		errChan <- err
		return
	}

	messageChan <- rs
	return
}

//删除队列消息
func (queue *Queue) Delete(receiptHandle string, errChan chan error) {
	req := &request{
		endpoint: queue.Endpoint,
		method:   http.MethodDelete,
		path:     getPath(queue.QueueName),
		params: map[string]string{
			"ReceiptHandle": receiptHandle,
		},
		payload:     nil,
		contentType: "text/xml",
		headers:     map[string]string{},
	}

	_, err := queue.doRequest(req)
	if err != nil {
		errChan <- err
		return
	}

	errChan <- nil
	return
}