Getting Started with Golang-a simple HTTP client

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

After reading the first two chapters of Go WEB programming, you can start writing code.

Import ("FMT" "Io/ioutil" "Log" "Net/http" "Net/url") func main () {//resp, _: = DoG  ET ("http://www.baidu.com")//resp, _: = DoPost ("http://www.baidu.com", "Application/json;charset=utf-8") resp, _ : = Dopostform ("http://www.baidu.com") defer resp. The special syntax of Body.close ()//go, which executes resp before the execution of the main function finishes. Body.close () fmt. Println (resp. StatusCode)//HTTP response code output if resp. StatusCode = = http. Statusok {//If the response code is the body, err: = Ioutil. ReadAll (resp. Body)//The body of the response is read out if err! = Nil {//If there is an abnormal fmt. PRINTLN (ERR)//Print the exception to log. Fatal (ERR)//log} FMT. PRINTLN (String)///text output of the response to console}}/** requests **/func doget (URL string) (R *http) as get. Response, e error) {resp, err: = http. Get (URL) if err! = Nil {fmt. Println (resp. StatusCode) fmt. PRINTLN (Err) log. Fatal (Err)} return resp, err}/** to postThe way to request **/func doPost (URL string, bodyType string) (R *http. Response, e error) {resp, err: = http. Post (URL, bodyType, nil) if err! = Nil {fmt. Println (resp. StatusCode) fmt. PRINTLN (Err) log. Fatal (Err)} return resp, err}/** requests **/func dopostform (Urlstr string) as a post form (R *http. Response, e error) {V: = URL. Values{"method": {"Get"}, "id": {"1"}} v.add ("Name1", "1") V.add ("Name2", "2") resp, err: = http. Postform (Urlstr, v) if err! = Nil {fmt. Println (resp. StatusCode) fmt. PRINTLN (Err) log.  Fatal (Err)} return resp, err}

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.