【GOLANG】http请求代码

zhonglinzhang · · 1830 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

一. http请求,设置超时
func Request(method, baseUrl, path string, body io.Reader) ([]byte, int, error) {
	client := http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				deadline := time.Now().Add(25 * time.Second)
				c, err := net.DialTimeout(netw, addr, time.Second*20)
				if err != nil {
					return nil, err
				}
				c.SetDeadline(deadline)
				return c, nil
			},
		},
	}

	url := fmt.Sprintf("%s%s", baseUrl, path)
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, 0, err
	}

	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return nil, 0, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, 0, err
	}
	defer resp.Body.Close()
	return data, resp.StatusCode, nil
}


二. goroutine 定时器

var exit = make(chan error)
        tc := time.NewTicker(time.Second * 5)
       
        go func() {
            for {
                select {
                case <-tc.C:
                    exit <- fmt.Errorf("{request agent timeout}")
                    return
                default:
                    data, code, err = Request("GET", httpHost, path, bytes.NewBuffer(nil))
                    if err != nil {
                        exit <- fmt.Errorf("{request agent error %v}", err)
                        return
                    }
       
                    if code != http.StatusOK {
                        exit <- fmt.Errorf("{request agent network abnormal}")
                        break
                    }
       
                    exit <- nil 
                    return
                }
            }
        }()
       
        err = <-exit
        if err != nil {
            return RET_ERROR, fmt.Errorf("{request agent failed finally %v}", err)
        }

三. 注册API handler 

<span style="font-size:14px;">func startApiServer(engine *driver.Engine) error {
	router := api.HandlerRouter(engine)
	http.Handle("/", router)

	addr := fmt.Sprintf(":%d", engine.Config.HTTPPort)
	if err := http.ListenAndServe(addr, nil); err != nil {
		return err
	}

	return nil
}</span>

var mRouter = map[string]map[string]func(*driver.Engine, http.ResponseWriter, *http.Request){
	"GET": {
		"db/queryuserinfo/{user_name}":                    getUserinfoByNameHandler,
		"{user_id}/db/querylist":                          getUserHagroupsHandler,
		"{user_id}/db/detail/{group_id}":                  getHagroupinfoHandler,
		"db/monitor/alivestatus":                          getAliveStatusHandler,
		"db/monitor/agentalivestatus/{start_id}/{end_id}": getAgentAliveStatusHandler,
		"db/monitor/keystatus/{monitor_key}/{key_value}":  getMonitKeyStatusHandler,
		"{user_id}/db/check/{group_name}":                 checkGroupNameHandler,
	},

	"POST": {
		"{user_id}/db/create":                      createHagroupHandler,
		"{user_id}/db/start/{group_id}":            startHagroupHandler,
		"{user_id}/db/restart/{group_id}":          restartHagroupHandler,
		"{user_id}/db/stop/{group_id}":             stopHagroupHandler,
		"{user_id}/db/modify/{group_id}":           modifyHagroupInfoHandler,
		"{user_id}/db/modify/cpuandmem/{group_id}": modifyHagroupCpuMemHandler,
		//		"{user_id}/db/callback/create/{group_id}":  AgentCreateHgHandler,
		//		"{user_id}/db/callback/delete/{group_id}":  AgentDeleteHgHandler,
	},

	"DELETE": {
		"{user_id}/db/delete/{group_id}": deleteHagroupHandler,
	},
}

func HandlerRouter(engine *driver.Engine) http.Handler {
	router := mux.NewRouter()

	for method, routes := range mRouter {
		for route, fct := range routes {
			localRoute := RVERSION + route
			localMethod := method
			handler := handlerRequest(engine, fct)
			router.Path(localRoute).Methods(localMethod).HandlerFunc(handler)
		}
	}

	router.NotFoundHandler = http.NotFoundHandler()
	return router
}

func handlerRequest(engine *driver.Engine, handlerFunc func(*driver.Engine, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		engine.Log.Info("server API handRequest: %s", r.URL)
		handlerFunc(engine, w, r)
	}
}




版权声明:本文为博主原创文章,未经博主允许不得转载。


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:zhonglinzhang

查看原文:【GOLANG】http请求代码

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1830 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传