【GOLANG】http请求代码

前端之家收集整理的这篇文章主要介绍了【GOLANG】http请求代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 一. http请求,设置超时
  1. func Request(method,baseUrl,path string,body io.Reader) ([]byte,int,error) {
  2. client := http.Client{
  3. Transport: &http.Transport{
  4. Dial: func(netw,addr string) (net.Conn,error) {
  5. deadline := time.Now().Add(25 * time.Second)
  6. c,err := net.DialTimeout(netw,addr,time.Second*20)
  7. if err != nil {
  8. return nil,err
  9. }
  10. c.SetDeadline(deadline)
  11. return c,nil
  12. },},}
  13.  
  14. url := fmt.Sprintf("%s%s",path)
  15. req,err := http.NewRequest(method,url,body)
  16. if err != nil {
  17. return nil,err
  18. }
  19.  
  20. req.Header.Set("Content-Type","application/json")
  21. resp,err := client.Do(req)
  22. if err != nil {
  23. return nil,err
  24. }
  25.  
  26. data,err := IoUtil.ReadAll(resp.Body)
  27. if err != nil {
  28. return nil,err
  29. }
  30. defer resp.Body.Close()
  31. return data,resp.StatusCode,nil
  32. }


  1. 二. goroutine 定时器
  1. var exit = make(chan error)
  2. tc := time.NewTicker(time.Second * 5)
  3. go func() {
  4. for {
  5. select {
  6. case <-tc.C:
  7. exit <- fmt.Errorf("{request agent timeout}")
  8. return
  9. default:
  10. data,code,err = Request("GET",httpHost,path,bytes.NewBuffer(nil))
  11. if err != nil {
  12. exit <- fmt.Errorf("{request agent error %v}",err)
  13. return
  14. }
  15. if code != http.StatusOK {
  16. exit <- fmt.Errorf("{request agent network abnormal}")
  17. break
  18. }
  19. exit <- nil
  20. return
  21. }
  22. }
  23. }()
  24. err = <-exit
  25. if err != nil {
  26. return RET_ERROR,fmt.Errorf("{request agent Failed finally %v}",err)
  27. }

三. 注册API handler

  1. <span style="font-size:14px;">func startApiServer(engine *driver.Engine) error {
  2. router := api.HandlerRouter(engine)
  3. http.Handle("/",router)
  4.  
  5. addr := fmt.Sprintf(":%d",engine.Config.HTTPPort)
  6. if err := http.ListenAndServe(addr,nil); err != nil {
  7. return err
  8. }
  9.  
  10. return nil
  11. }</span>
  1. var mRouter = map[string]map[string]func(*driver.Engine,http.ResponseWriter,*http.Request){
  2. "GET": {
  3. "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": {
  4. "{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": {
  5. "{user_id}/db/delete/{group_id}": deleteHagroupHandler,}
  6.  
  7. func HandlerRouter(engine *driver.Engine) http.Handler {
  8. router := mux.NewRouter()
  9.  
  10. for method,routes := range mRouter {
  11. for route,fct := range routes {
  12. localRoute := RVERSION + route
  13. localMethod := method
  14. handler := handlerRequest(engine,fct)
  15. router.Path(localRoute).Methods(localMethod).HandlerFunc(handler)
  16. }
  17. }
  18.  
  19. router.NotFoundHandler = http.NotFoundHandler()
  20. return router
  21. }
  22.  
  23. func handlerRequest(engine *driver.Engine,handlerFunc func(*driver.Engine,*http.Request)) func(http.ResponseWriter,*http.Request) {
  24. return func(w http.ResponseWriter,r *http.Request) {
  25. engine.Log.Info("server API handRequest: %s",r.URL)
  26. handlerFunc(engine,w,r)
  27. }
  28. }

猜你在找的Go相关文章