标签:make nil done github api taobao func git out
Beego接收Json, 并发请求Api, 返回Json
package controllers import ( "encoding/json" "fmt" "github.com/astaxie/beego" "io/ioutil" "net/http" "sync" ) type ApiController struct { beego.Controller } func (c *ApiController) Post() { req := make(map[string]string) data := c.Ctx.Input.RequestBody //在RequestBody中读取Json err := json.Unmarshal(data, &req) if err != nil { fmt.Println(err) } //for k, v := range req { // fmt.Println(k, v) //} result := requestApi(req) c.Data["json"] = result c.ServeJSON() return } func requestApi(urls map[string]string) (map[string]string) { apiData := make(map[string]string) var wg sync.WaitGroup wg.Add(len(urls)) for key := range urls { fmt.Println(key, "首都是", urls [key]) var url = urls [key] // 开启协程, 注意参数传递 go func(key string, url string) { res := httpGet(url) beego.Info(key) apiData[key] = string(res) wg.Done() }(key, url) } wg.Wait() // fmt.Println(reflect.TypeOf(apiData)) // 打印类型 map[string]string return apiData } func httpGet(url string) string{ resp, _ := http.Get(url) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) return string(body) } // 测试用 func (c *ApiController) Run() { urls := make(map[string]string) urls["13800138008"] = "https://suggest.taobao.com/sug?q=电脑&code=utf-8" urls["13800138001"] = "https://suggest.taobao.com/sug?q=VR&code=utf-8" urls["13800138002"] = "https://suggest.taobao.com/sug?q=手机&code=utf-8" urls["13800138004"] = "https://suggest.taobao.com/sug?q=苹果&code=utf-8" urls["13800138005"] = "https://suggest.taobao.com/sug?q=冰箱&code=utf-8" var result = requestApi(urls) fmt.Println(result) c.Data["json"] = result c.ServeJSON() return }
标签:make nil done github api taobao func git out
原文地址:https://www.cnblogs.com/km2mvp/p/13140706.html