美文网首页Go语言实践Go
Go语言学习笔记22.http编程

Go语言学习笔记22.http编程

作者: 快乐的提千万 | 来源:发表于2019-11-07 10:48 被阅读0次

服务端:

package main

import (
    "fmt"
    "net/http"
)

//w, 给客户端回复数据
//r, 读取客户端发送的数据
func HandConn(w http.ResponseWriter, r *http.Request) {
    fmt.Println("r.Method = ", r.Method) //请求模式  GET
    fmt.Println("r.URL = ", r.URL)//请求地址 /
    fmt.Println("r.Header = ", r.Header)//请求头  map[Accept-Encoding:[gzip] User-Agent:[Go-http-client/1.1]]
    fmt.Println("r.Body = ", r.Body)//请求体   {}

    w.Write([]byte("hello go")) //给客户端回复数据
}

func main() {
    //注册处理函数,用户连接,自动调用指定的处理函数
    http.HandleFunc("/", HandConn)

    //监听绑定
    http.ListenAndServe(":8000", nil)
}

客户端:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    //resp, err := http.Get("http://www.baidu.com")
    resp, err := http.Get("http://127.0.0.1:8000")
    if err != nil {
        fmt.Println("http.Get err = ", err)
        return
    }

    defer resp.Body.Close()

    fmt.Println("Status = ", resp.Status)  //返回状态 200 OK
    fmt.Println("StatusCode = ", resp.StatusCode)  //状态码 200
    fmt.Println("Header = ", resp.Header) //返回头   map[Content-Length:[8] Content-Type:[text/plain; charset=utf-8] Date:[Tue, 08 Oct 2019 07:38:41 GMT]]
    fmt.Println("Body = ", resp.Body)//返回体   &{0xc0000da000 {0 0} false <nil> 0x610250 0x6101d0}

    buf := make([]byte, 4*1024)
    var tmp string

    for {
        n, err := resp.Body.Read(buf)
        if n == 0 {
            fmt.Println("read err = ", err) //read err =  EOF
            break
        }
        tmp += string(buf[:n])
    }

    fmt.Println("tmp = ", tmp) //tmp =  hello go

}

相关文章

网友评论

    本文标题:Go语言学习笔记22.http编程

    本文链接:https://www.haomeiwen.com/subject/wekebctx.html