"Golang" HTTP request code

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
One. HTTP request, setting timeout
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 (* 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}


Two. Goroutine Timer

var exit = make (chan error) TC: = time. Newticker (time. Second * 5) go func () {for {select {case &LT;-TC. C:exit <-FMT. Errorf ("{Request agent Timeout}") return Default:data, code, err = R Equest ("GET", httphost, Path, bytes. Newbuffer (nil)) if err! = Nil {exit <-FMT. Errorf ("{Request agent Error%v}", err) return} if Co De! = http. Statusok {exit <-FMT. Errorf ("{Request Agent Network abnormal}") Break} Exi T <-nil Return}}} () Err = <-exit if ER R! = Nil {return ret_error, FMT. Errorf ("{Request Agent failed finally%v}", err)}

Three. Registering 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} ": ge Tagentalivestatushandler, "Db/monitor/keystatus/{monitor_key}/{key_value}": Getmonitkeystatushandler, "{user_id}/ Db/check/{group_name} ": Checkgroupnamehandler,}," POST ": {" {user_id}/db/create ": creat          Ehagrouphandler, "{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 + Routelocalmethod : = Methodhandler: = 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)}}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.