golang使用http客户端 多个协程同时请求接口

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"sync"
)

type ApiResponse struct {
	Code int           `json:"code"`
	Msg  string        `json:"msg"`
	Data []interface{} `json:"data"` // 使用空接口数组来表示空的数据字段
}

func main() {
	numTasks := 30 // 假设我们想要启动 5 个任务

	var wg sync.WaitGroup // 使用 sync.WaitGroup 来同步协程

	for i := 0; i < numTasks; i++ {
		wg.Add(1)                // 增加 WaitGroup 的计数
		go getTaskList(&wg, i+1) // 启动协程
	}

	wg.Wait() // 阻塞,直到所有协程调用了 Done
	fmt.Println("All tasks have completed.")
}

func getTaskList(wg *sync.WaitGroup, id int) {
	defer wg.Done() // 在函数结束时通知 WaitGroup 减少一个计数
	fmt.Printf("Task list %d started\n", id)

	baseURL := "http://qq.com/getTaskList"

	// 创建一个用于存储查询参数的 url.Values 实例
	params := url.Values{}
	// 添加参数到 params
	//params.Add("param1", "value1")

	// 将查询参数附加到基础 URL
	urlWithQuery := baseURL + "?" + params.Encode()

	// 使用 http.Get 发送 GET 请求
	resp, err := http.Get(urlWithQuery)
	if err != nil {
		fmt.Printf("Error fetching URL: %v\n", err)
		return
	}
	defer resp.Body.Close()
	var apiResponse ApiResponse

	// 打印响应状态码
	fmt.Printf("Response Status Code: %d\n", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)

	if err != nil {
		fmt.Printf("Error reading response body: %v\n", err)
		return
	}

	if err := json.Unmarshal([]byte(string(body)), &apiResponse); err != nil {
		fmt.Printf("Error decoding JSON: %v\n", err)
		return
	}

	// 打印响应体
	fmt.Printf("Response Body: %s\n", apiResponse.Msg)

	defer resp.Body.Close()
}

posted @ 2024-08-30 18:57  冯元春  阅读(87)  评论(0)    收藏  举报