通过url获取报文
-
-
// Fetch prints the content found at each specified URL.
-
package main
-
-
import (
-
"fmt"
-
"io/ioutil"
-
"net/http"
-
"os"
-
)
-
-
func main() {
-
for _, url := range os.Args[1:] {
-
resp, err := http.Get(url)
-
if err != nil {
-
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
-
os.Exit(1)
-
}
-
b, err := ioutil.ReadAll(resp.Body)
-
resp.Body.Close()
-
if err != nil {
-
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
-
os.Exit(1)
-
}
-
fmt.Printf("%s", b)
-
}
-
}
-
-
//!-
输出结果:
----------------------------------------------------------------------------------------------
使用io.Copy从网络读取数据到标准输出,而不是ioutil.ReadAll函数
-
package main
-
-
import (
-
"fmt"
-
"io"
-
// "io/ioutil"
-
"net/http"
-
"os"
-
)
-
-
func main() {
-
for _, url := range os.Args[1:] {
-
resp, err := http.Get(url)
-
if err != nil {
-
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
-
os.Exit(1)
-
}
-
-
_, err = io.Copy(os.Stdout, resp.Body)
-
resp.Body.Close()
-
if err != nil {
-
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
-
os.Exit(1)
-
}
-
}
-
}
-
-
//!-
阅读(601) | 评论(0) | 转发(0) |