| 1 |
package mns |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/xml" |
| 5 |
"io/ioutil" |
| 6 |
"net/http" |
| 7 |
"strconv" |
| 8 |
) |
| 9 |
|
| 10 |
接口PATH |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
func getPath(queue string) string { |
| 15 |
return "/queues/" + queue + "/messages" |
| 16 |
} |
| 17 |
|
| 18 |
队列消息 |
| 19 |
func (queue *Queue) Send(time int64, message []byte) (msg MsgSend, err error) { |
| 20 |
req := &request{ |
| 21 |
endpoint: queue.Endpoint, |
| 22 |
method: http.MethodPost, |
| 23 |
path: getPath(queue.QueueName), |
| 24 |
payload: message, |
| 25 |
contentType: "text/xml", |
| 26 |
headers: map[string]string{}, |
| 27 |
} |
| 28 |
|
| 29 |
response, err := queue.doRequest(req) |
| 30 |
if err != nil { |
| 31 |
return |
| 32 |
} |
| 33 |
|
| 34 |
defer response.Body.Close() |
| 35 |
|
| 36 |
|
| 37 |
data, err := ioutil.ReadAll(response.Body) |
| 38 |
if err != nil { |
| 39 |
return |
| 40 |
} |
| 41 |
|
| 42 |
err = xml.Unmarshal(data, &msg) |
| 43 |
|
| 44 |
if err != nil { |
| 45 |
return |
| 46 |
} |
| 47 |
|
| 48 |
return |
| 49 |
|
| 50 |
} |
| 51 |
|
| 52 |
队列消息 |
| 53 |
func (queue *Queue) Receive(messageChan chan MsgReceive, errChan chan error) { |
| 54 |
req := &request{ |
| 55 |
endpoint: queue.Endpoint, |
| 56 |
method: http.MethodGet, |
| 57 |
path: getPath(queue.QueueName), |
| 58 |
params: map[string]string{ |
| 59 |
"waitseconds": strconv.Itoa(5), |
| 60 |
}, |
| 61 |
payload: nil, |
| 62 |
contentType: "text/xml", |
| 63 |
headers: map[string]string{}, |
| 64 |
} |
| 65 |
|
| 66 |
response, err := queue.doRequest(req) |
| 67 |
if err != nil { |
| 68 |
errChan <- err |
| 69 |
return |
| 70 |
} |
| 71 |
|
| 72 |
defer response.Body.Close() |
| 73 |
rs := MsgReceive{} |
| 74 |
|
| 75 |
|
| 76 |
data, err := ioutil.ReadAll(response.Body) |
| 77 |
if err != nil { |
| 78 |
errChan <- err |
| 79 |
return |
| 80 |
} |
| 81 |
|
| 82 |
err = xml.Unmarshal(data, &rs) |
| 83 |
|
| 84 |
if err != nil { |
| 85 |
errChan <- err |
| 86 |
return |
| 87 |
} |
| 88 |
|
| 89 |
messageChan <- rs |
| 90 |
return |
| 91 |
} |
| 92 |
|
| 93 |
队列消息 |
| 94 |
func (queue *Queue) Delete(receiptHandle string, errChan chan error) { |
| 95 |
req := &request{ |
| 96 |
endpoint: queue.Endpoint, |
| 97 |
method: http.MethodDelete, |
| 98 |
path: getPath(queue.QueueName), |
| 99 |
params: map[string]string{ |
| 100 |
"ReceiptHandle": receiptHandle, |
| 101 |
}, |
| 102 |
payload: nil, |
| 103 |
contentType: "text/xml", |
| 104 |
headers: map[string]string{}, |
| 105 |
} |
| 106 |
|
| 107 |
_, err := queue.doRequest(req) |
| 108 |
if err != nil { |
| 109 |
errChan <- err |
| 110 |
return |
| 111 |
} |
| 112 |
|
| 113 |
errChan <- nil |
| 114 |
return |
| 115 |
} |