Golang 接收Get、Post请求
Get
1、接收
func GetGet(w http.ResponseWriter, r *http.Request) { defer func() { r.Body.Close() if r := recover(); r != nil { stackBytes := debug.Stack() fmt.Println("r", r, "Error", stackBytes) } }() r.ParseForm() defer func() { // 自定义返回内容 backData := struct { Code int Msg string }{ 200, "success", } bytes, err := json.Marshal(backData) if err != nil { fmt.Fprint(w, nil) return } w.Write(bytes) }() // param param1 := r.Form.Get("param1") // todo something }
2、发送
func send() { param1 := "param1" resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:8080?param1=%s", param1)) if err != nil { log.Println("http.Get err=", err) return } bytes, err := io.ReadAll(resp.Body) if err != nil { log.Println("ioutil.ReadAll err=", err) return } }
Post
1、接收
func PostGet(w http.ResponseWriter, r *http.Request) { defer func() { r.Body.Close() if r := recover(); r != nil { stackBytes := debug.Stack() fmt.Println("r", r, "Error", stackBytes) } }() r.ParseForm() defer func() { // 自定义返回内容 backData := struct { Code int Msg string }{ 200, "success", } bytes, err := json.Marshal(backData) if err != nil { fmt.Fprint(w, nil) return } w.Write(bytes) }() // must post if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } // param paramMap := make(map[string]string) _ = json.NewDecoder(r.Body).Decode(¶mMap) param1Str := paramMap["param1"] // todo something }
2、发送
func PostSend() { sendStruct := struct { Param1 string `json:"param1"` }{ "param1", } sendData, _ := json.Marshal(sendStruct) fmt.Println("sendData", string(sendData)) resp, err := http.Post("http://127.0.0.1:8080", "application/json", bytes2.NewBuffer(sendData)) if err != nil { fmt.Println("post err", err) return } defer resp.Body.Close() backBytes, err := io.ReadAll(resp.Body) if err != nil { log.Println("io.ReadAll err=", err) return } }