博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用go的net/http实现读取web页面
阅读量:6766 次
发布时间:2019-06-26

本文共 1546 字,大约阅读时间需要 5 分钟。

hot3.png

package main
 
import (
"fmt"
"io/ioutil" //[1]
"net/http" //[2]
"os" //[3]
"path/filepath" // [4]
)
 
func main() {
if len(os.Args) != 2 {
fmt.Printf("useage:%s http://url", filepath.Base(os.Args[0]))
os.Exit(1)
}
resp, err := http.Get(os.Args[1])
if err != nil {
fmt.Println(err) //go语言会内含详细的错误描述,可以尝试不同的参数来测试
os.Exit(2)
}
defer resp.Body.Close() //The client must close the response body when finished with it:
body, err2 := ioutil.ReadAll(resp.Body) //此处使用了包【1】
if err2 != nil {
fmt.Println(err2)
os.Exit(3)
}
fmt.Printf("%s", body)
 
}
 
##生成程序测试
getwebpage.exe
useage:getwebpage.exe http://url
getwebpage.exe http://ww
Get http://ww: dial tcp: GetAddrInfoW: No such host is known.
getwebpage.exe htt
Get htt: unsupported protocol scheme ""
相关说明 
在DOS里执行命令 “godoc -http=:8000”后可以查到相关包
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 an EOF from Read as an error to be reported.

转载于:https://my.oschina.net/u/1590519/blog/262225

你可能感兴趣的文章
VMware VSphere 虚拟化&云计算学习配置笔记(七)
查看>>
android ViewPager适配器
查看>>
Listview 标题
查看>>
hello world!!!
查看>>
mysql+php+pdo批量添加大数据
查看>>
永中Office—如何制作超级方便的临时座位卡
查看>>
golang闭包
查看>>
我的友情链接
查看>>
5014.网络安全__防火墙安全策略和安全区域划分
查看>>
初识PKI
查看>>
Java注释@interface的用法【转】
查看>>
计算1-1/3+1/5-1/7+···的前n项和
查看>>
7 Steps to Upgrade IOS Image on Cisco Catalyst Switch or Router
查看>>
python购物车功能实现
查看>>
用javcscript记住用户名和密码保存在本地储存中,然后实现前端获取
查看>>
css中样式的优先级简单总结
查看>>
端口聚合配置
查看>>
易学笔记--程序猿踩过的十个最典型的坑
查看>>
Systemstate Dump分析经典案例(上)
查看>>
Win7+Ubuntu11
查看>>