一. 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) } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
有疑问加站长微信联系(非本文作者)