文章目录
- 一、发送请求和接收请求示例
- 1.1 发送请求
- 1.2 接收请求
- 二、发送form-data格式的数据示例
用go语言发送请求和接收请求的快速参考
一、发送请求和接收请求示例
1.1 发送请求
package mainimport ("bytes""encoding/json""fmt""net/http"
)type Payload struct {Name string `json:"topic"`Value string `json:"data"`
}func main() {// 构造要发送的数据payload := Payload{Name: "example",Value: "this is a test",}// 将数据编码为JSONjsonData, err := json.Marshal(payload)if err != nil {fmt.Println("Error encoding JSON:", err)return}// 发送POST请求resp, err := http.Post("http://localhost:8080/devStatistic/pushDevStatistic","application/json", bytes.NewBuffer(jsonData))if err != nil {fmt.Println("Error sending POST request:", err)return}defer resp.Body.Close()// 打印响应状态fmt.Println("Response status:", resp.Status)
}
1.2 接收请求
package mainimport ("encoding/json""fmt""io/ioutil""net/http"
)type Payload struct {Name string `json:"name"`Value string `json:"value"`
}func handler(w http.ResponseWriter, r *http.Request) {if r.Method == "POST" {// 读取请求体中的数据body, err := ioutil.ReadAll(r.Body)if err != nil {http.Error(w, "Error reading request body", http.StatusInternalServerError)return}// 打印原始请求体内容fmt.Println("Received request body:", string(body))// 将请求体数据解析为结构体var payload Payloaderr = json.Unmarshal(body, &payload)if err != nil {http.Error(w, "Error parsing JSON", http.StatusBadRequest)return}// 打印解析后的数据fmt.Printf("Parsed data: Name = %s, Value = %s\n", payload.Name, payload.Value)// 返回响应fmt.Fprintf(w, "Received data: Name = %s, Value = %s\n", payload.Name, payload.Value)} else {// 处理其他请求w.WriteHeader(http.StatusMethodNotAllowed)}
}func main() {http.HandleFunc("/", handler)fmt.Println("Server is running on http://localhost:8080")if err := http.ListenAndServe(":8080", nil); err != nil {fmt.Println("Error starting server:", err)}
}
二、发送form-data格式的数据示例
// sender.go
package mainimport ("bytes""fmt""mime/multipart""net/http"
)// SendHTTPSMessage 使用 multipart/form-data 发送消息
func SendHTTPSMessage(topic, text, ip string, port int) error {// 创建一个缓冲区用来存放 form-data 数据var formDataBuffer bytes.Bufferwriter := multipart.NewWriter(&formDataBuffer)// 添加 form-data 字段err := writer.WriteField("topic", topic)if err != nil {return fmt.Errorf("error adding topic field: %v", err)}err = writer.WriteField("content", text)if err != nil {return fmt.Errorf("error adding content field: %v", err)}// 关闭 writer,以便生成完整的 form-dataerr = writer.Close()if err != nil {return fmt.Errorf("error closing writer: %v", err)}// 构建目标 URLurl := fmt.Sprintf("https://%s:%d/api/send_message", ip, port)// 创建 HTTP POST 请求req, err := http.NewRequest("POST", url, &formDataBuffer)if err != nil {return fmt.Errorf("error creating HTTP request: %v", err)}// 设置请求头的 Content-Type 为 multipart/form-data,并包含 boundary 信息req.Header.Set("Content-Type", writer.FormDataContentType())// 创建 HTTP 客户端并发送请求client := &http.Client{}resp, err := client.Do(req)if err != nil {return fmt.Errorf("error sending HTTPS request: %v", err)}defer resp.Body.Close()// 打印响应状态fmt.Println("Response Status:", resp.Status)return nil
}
解释
- 使用 multipart.NewWriter** 创建 form-data**:
- multipart.NewWriter 创建了一个 writer,可以将字段添加到 form-data。
- 使用 WriteField 方法添加 topic 和 content 字段到 form-data。
- 设置 Content-Type:
- req.Header.Set(“Content-Type”, writer.FormDataContentType()) 会自动生成包含 boundary 的 Content-Type,这是 multipart/form-data 必需的格式。
- 发送请求:
- 创建 HTTP 客户端并发送请求,与 JSON 的方式相同。