【GOLANG】http请求代码

前端之家收集整理的这篇文章主要介绍了【GOLANG】http请求代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一. 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",path)
	req,err := http.NewRequest(method,url,body)
	if err != nil {
		return nil,err
	}

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

	data,err := IoUtil.ReadAll(resp.Body)
	if err != nil {
		return nil,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.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)
	}
}
原文链接:https://www.f2er.com/go/190168.html

猜你在找的Go相关文章