Read Web pages using Go's net/http implementation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Package Main
Import(
"FMT"
"Io/ioutil"//[1]
"Net/http"//[2]
"OS"//[3]
"Path/filepath"//[4]
)
FuncMain (){
Iflen(OS. Args)!=2{
Fmt. Printf ("useage:%shttp://url",filepath. Base (OS. args[0]))
Os. Exit (1)
}
RESP,err: =http. Get (OS. args[1])
Iferr!=Nil{
Fmt. PRINTLN (Err)//go language will contain a detailed description of the error, you can try different parameters to test
Os. Exit (2)
}
 defer Resp. Body.close () //the Client must Close  the Response Body  when finished  with it: 
Body,err2: =ioutil. ReadAll (resp. Body)//The package "1" is used here
Iferr2!=Nil{
Fmt. Println (ERR2)
Os. Exit (3)
}
Fmt. Printf ("%s",body)
}

# #生成程序测试 Getwebpage.exe
Useage:getwebpage.exe Http://urlGetwebpage.exe HTTP://WW
Get http://ww:dial Tcp:GetAddrInfoW:No Such host is known.Getwebpage.exe htt
Get htt:unsupported protocol scheme ""

Instructions in DOS after executing the command "godoc-http=:8000" can be found in the relevant package http://127.0.0.1:8000/pkg/net/http/http://127.0.0.1:8000/pkg/io/ioutil/ #ReadAll Package HTTP provides HTTP client and server implementations. Get, Head, Post, and Postform make HTTP (or HTTPS) Requests:resp, err: = http. Get ("http://example.com/") ... resp, err: = http. Post ("Http://example.com/upload", "Image/jpeg", &buf) ... resp, err: = http. Postform ("Http://example.com/form", url. values{"key": {"Value"}, "id": {"123"}})
Func ReadAll (R io. Reader) ([]byte, error) ReadAll reads from R until an error or EOF and returns the data it read. A successful call returns err = = Nil, not err = = EOF. Because ReadAll is defined-to-read from SRC until-eof, it does not treat a EOF from read as a error to be reported.
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.