1. 程式人生 > >golang:模擬http post請求

golang:模擬http post請求

brush else div str response inf 啟動 quest ack

  1,發送http post請求(客戶端)

func httppost()  {
	data :=`{"type":"10","msg":"hello."}`
	request, _ := http.NewRequest("POST", "http://0.0.0.0:8090/msg", strings.NewReader(data))
	//post數據並接收http響應
	resp,err :=http.DefaultClient.Do(request)
	if err!=nil{
		fmt.Printf("post data error:%v\n",err)
	}else {
		fmt.Println("post a data successful.")
		respBody,_ :=ioutil.ReadAll(resp.Body)
		fmt.Printf("response data:%v\n",string(respBody))
	}
}

  2,接收方法(服務端)

package main

import (
	"net/http"
	"io/ioutil"
	"fmt"
)

func main()  {
	//設置路由和接收HTTP請求的方法
	mux :=http.NewServeMux()
	mux.HandleFunc("/msg",recvHandle)
	//設置http服務
	server :=&http.Server{
		Addr:    "0.0.0.0:8090",
		Handler: mux,
	}
	//啟動監聽
	server.ListenAndServe()
}
func recvHandle(w http.ResponseWriter, r *http.Request)  {
	body,_ :=ioutil.ReadAll(r.Body)
	fmt.Println(string(body))
	fmt.Fprintf(w,"3q your msg.")
}

  3,執行結果

技術分享圖片

golang:模擬http post請求