| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package test
-
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "testing"
- "time"
- )
-
- type ExchangeRequest struct {
- ChannelName string `json:"channel_name"`
- ExchangeName string `json:"exchange_name"`
- ExchangeType string `json:"exchange_type"`
- Durable bool `json:"durable"`
- Internal bool `json:"internal"`
- AutoDelete bool `json:"auto_delete"`
- NoWait bool `json:"no_wait"`
- Arguments map[string]string `json:"arguments"`
- }
-
- func TestCreateexchange(t *testing.T) {
- // 1. 准备请求数据
- requestData := ExchangeRequest{
- ChannelName: "test_channel",
- ExchangeName: "test_exchange",
- ExchangeType: "direct", // direct, fanout, topic, headers
- Durable: true,
- Internal: false,
- AutoDelete: false,
- NoWait: false,
- Arguments: map[string]string{
- "x-delayed-type": "direct",
- },
- }
-
- // 2. 将数据转换为JSON
- jsonData, err := json.Marshal(requestData)
- if err != nil {
- fmt.Printf("JSON编码失败: %v\n", err)
- return
- }
-
- // 3. 发送HTTP POST请求
- url := "http://localhost:9090/api/rabbitmq/exchange/create"
-
- // 如果服务端需要认证,添加JWT token
- token := "your-jwt-token-here" // 替换为实际的JWT token
-
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
- if err != nil {
- fmt.Printf("创建请求失败: %v\n", err)
- return
- }
-
- // 添加请求头
- req.Header.Set("Content-Type", "application/json")
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
-
- // 4. 发送请求并获取响应
- client := &http.Client{
- Timeout: 10 * time.Second,
- }
-
- resp, err := client.Do(req)
- if err != nil {
- fmt.Printf("请求失败: %v\n", err)
- return
- }
- defer resp.Body.Close()
-
- // 5. 读取响应
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- fmt.Printf("读取响应失败: %v\n", err)
- return
- }
-
- // 6. 输出结果
- fmt.Printf("状态码: %d\n", resp.StatusCode)
- fmt.Printf("响应头: %v\n", resp.Header)
- fmt.Printf("响应体: %s\n", string(body))
- }
|