golang net\http包简单的使用
发布时间:2020-12-16 09:31:01 所属栏目:大数据 来源:网络整理
导读:HTTP服务端: package mainimport ("fmt""net/http")func HandConn(w http.ResponseWriter,r *http.Request) {//用户请求方法fmt.Println(r.Method)//用户请求地址fmt.Println(r.URL)//请求头fmt.Println(r.Header)w.Write([]byte("hello go"))}func main()
HTTP服务端: package main import ( "fmt" "net/http" ) func HandConn(w http.ResponseWriter,r *http.Request) { //用户请求方法 fmt.Println(r.Method) //用户请求地址 fmt.Println(r.URL) //请求头 fmt.Println(r.Header) w.Write([]byte("hello go")) } func main() { //注册处理函数,用户连接自动调用指定的处理函数 http.HandleFunc("/",HandConn) //监听http端口 http.ListenAndServe(":8000",nil) } HTTP客户端 package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) //httpget func httpGet() { resp,err := http.Get("http://127.0.0.1:8000") if err != nil { fmt.Println("Get err=",err) return } defer resp.Body.Close() fmt.Println("stats=",resp.Status) fmt.Println("StatusCode=",resp.StatusCode) fmt.Println("Header=",resp.Header) buf := make([]byte,1024*4) var temp string for { n,_ := resp.Body.Read(buf) if n == 0 { break } temp += string(buf[:n]) } fmt.Println("Body=",temp) } //httppost func httpPost() { user := Users{"user1","aaa"} if bs,err := json.Marshal(user); err == nil { req := bytes.NewBuffer([]byte(bs)) body_type := "application/json;charset=utf-8" resp,_ := http.Post("http://127.0.0.1:8000",body_type,req) body,_ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) defer resp.Body.Close() } } type Users struct { Name string `json:"name"` ID string `json:"id"` } func main() { httpGet() httpPost() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |