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=%+v\n", 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))
}

效果图:

猜你喜欢

转载自blog.csdn.net/mmssww2/article/details/81293858