Go语言模拟http服务器与客户端数据交互 - Go语言中文社区

Go语言模拟http服务器与客户端数据交互


废话少说:实现服务器打印输出客户端的请求参数,客户端打印服务器返回的数据

服务器:


package main
 
import (
	"flag"
	"fmt"
	"net/http"
)
 
func main() {
	host := flag.String("host", "127.0.0.1", "listen host")
	port := flag.String("port", "8088", "listen port")
 
	http.HandleFunc("/hello", Hello)
 
	err := http.ListenAndServe(*host+":"+*port, nil)
 
	if err != nil {
		panic(err)
	}
}
 
func Hello(w http.ResponseWriter, req *http.Request) {
	w.Write([]byte("Hello World"))
	fmt.Printf(" req.header=%+v,n req.usr.string=%+v,n req.url.path=%+vn", req.Header, req.URL.String(), req.URL.Path)
	req.ParseForm()
	d := req.Form
	fmt.Println(d)
}

客户端:


package main
 
import (
	"fmt"
	"io/ioutil"
	"net/http"
)
 
func main() {
	response, _ := http.Get("http://localhost:8088/hello?a=100")
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	fmt.Println(string(body))
}

效果图:

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/mmssww2/article/details/81293858
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 21:53:02
  • 阅读 ( 1110 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢