写的第一个程序很简单,但是意义非凡。通过http将网页抓取,保存到本地。程序如下
package main import ( "fmt" "os" "log" "net/http" ) func main(){ resp,err := http.Get("http://www.baidu.com") if err != nil{ //handle error fmt.Println(err) log.Fatal(err) } if resp.StatusCode == http.StatusOK{ fmt.Println(resp.StatusCode) } defer resp.Body.Close() buf := make([]byte,1024) //create file f,err1 := os.OpenFile("baidu.html",os.O_RDWR|os.O_CREATE|os.O_APPEND,os.ModePerm) if err1 != nil{ panic(err1) return } defer f.Close() for { n,_ := resp.Body.Read(buf) if 0 == n {break} f.WriteString(string(buf[:n])) } }原文链接:https://www.f2er.com/go/191457.html