1. 程式人生 > >go http協議和檔案操作

go http協議和檔案操作

package main

import (
    "fmt"
    "net/http"
    "os"
)

func main() {

    Client := &http.Client{}
    url := "http://www.baidu.com"
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        panic("failure to get info from baidu")
    }
    response, err := Client.Do(req)
    if
err != nil { panic("fail") } str := make([]byte, 2048) size, err := response.Body.Read(str) if size == 0 { panic(err) } fmt.Printf("%v", string(str)) defer response.Body.Close() file, err := os.OpenFile("my.txt", os.O_RDWR, 0666) if err != nil { println
("error occuer") panic(err) } else { println("write data ok") file.Write(str) } defer file.Close() }