golang net\http包简单的使用

golang net\http包简单的使用,第1张

概述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.Heade

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.HandleFunc("/",HandConn)	//监听http端口	http.ListenAndServe(":8000",nil)}

http客户端

package mainimport (	"bytes"	"enCoding/Json"	"fmt"	"io/IoUtil"	"net/http")//httpgetfunc 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)}//httppostfunc 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()}
总结

以上是内存溢出为你收集整理的golang net\http包简单的使用全部内容,希望文章能够帮你解决golang net\http包简单的使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1269033.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存