码迷,mamicode.com
首页 > Web开发 > 详细

Beego接收Json, 并发请求, 返回Json

时间:2020-06-16 14:59:58      阅读:189      评论:0      收藏:0      [点我收藏+]

标签: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
}

  

Beego接收Json, 并发请求, 返回Json

标签:make   nil   done   github   api   taobao   func   git   out   

原文地址:https://www.cnblogs.com/km2mvp/p/13140706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!