go语言请求和python请求的一些区别,比如python get请求就是把参数全部整理好,导入request包,调用函数,就可以实行了,:requests.get(url=url,data=json,headers=headers),输入结果,response.code
二go语言是:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 目标URL
url := "你的URL"
// 创建HTTP请求
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("create request failed, err:", err)
return
}
// 设置请求头(Token)
req.Header.Set("Token", "461170c3f5052cf302b81c97f9c96243")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("get failed, err:", err)
return
}
defer resp.Body.Close()
// 读取响应体
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("read from resp.Body failed, err:", err)
return
}
// 打印响应内容
fmt.Println(string(body))
}
go的post请求:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
// 定义请求数据结构
type RequestData struct {
ID string `json:"id"`
}
func main() {
// 目标URL
url := "你的URL"
// 构造请求数据
requestData := RequestData{
ID: "7270329807238373376",
}
// 发送POST请求
responseBody, err := sendPostRequest(url, "62b401b1c10b0e511c0b9784fad48bf8", requestData)
if err != nil {
log.Printf("Error sending request: %v", err)
return
}
// 打印响应状态码和响应体
fmt.Printf("Response Body: %s\n", string(responseBody))
var n int16 = 34
var m int32
m = int32(n)
fmt.Printf("32 bit int is: %d\n", m)
fmt.Printf("16 bit int is: %d\n", n)
a := 123
fmt.Printf("%1.2d\n", a)
}
// sendPostRequest 发送POST请求并返回响应体
func sendPostRequest(url, token string, data RequestData) ([]byte, error) {
// 将请求数据编码为JSON
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("error encoding JSON: %v", err)
}
// 创建HTTP请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Token", token)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()
// 读取响应体
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
// 检查响应状态码
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return body, nil
}
他们之间的区别
Go 和 Python 在发送 HTTP POST 请求时有一些显著的区别,主要体现在语法、库的使用方式以及代码风格上。以下是两者的对比:
---
## 1. **库和依赖**
- **Go**:
- Go 的标准库 `net/http` 提供了完整的 HTTP 客户端和服务器功能,无需额外安装第三方库。
- 代码简洁,依赖少。
- **Python**:
- Python 的标准库 `urllib` 也可以发送 HTTP 请求,但通常使用更友好的第三方库 `requests`。
- 需要额外安装 `requests` 库(`pip install requests`)。
---
## 2. **发送 POST 请求的代码示例**
### **Go 示例**
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type RequestData struct {
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
url := "https://example.com/api"
requestData := RequestData{
Name: "John Doe",
Email: "john.doe@example.com",
}
// 将结构体编码为 JSON
jsonData, err := json.Marshal(requestData)
if err != nil {
log.Fatalf("Error encoding JSON: %v", err)
}
// 发送 POST 请求
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatalf("Error sending request: %v", err)
}
defer resp.Body.Close()
// 读取响应
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response: %v", err)
}
fmt.Println("Response:", string(body))
}
```
### **Python 示例**
```python
import requests
import json
url = "https://example.com/api"
data = {
"name": "John Doe",
"email": "john.doe@example.com"
}
# 发送 POST 请求
response = requests.post(url, json=data)
# 打印响应
print("Response:", response.json())
```
---
## 3. **主要区别**
### **1. 语法和代码风格**
- **Go**:
- 需要手动将结构体编码为 JSON(使用 `json.Marshal`)。
- 需要显式设置请求头(如 `Content-Type`)。
- 错误处理需要手动检查(`if err != nil`)。
- 代码相对冗长,但更底层,适合需要精细控制的场景。
- **Python**:
- 使用 `requests` 库,代码简洁直观。
- 可以直接传递字典作为 JSON 数据(`json=data`)。
- 错误处理通过异常捕获(`try-except`)。
- 代码更简洁,适合快速开发。
---
### **2. 请求头设置**
- **Go**:
- 需要显式设置请求头,例如:
```go
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer token")
```
- 使用 `http.NewRequest` 创建请求对象时,可以更灵活地设置请求头和参数。
- **Python**:
- 使用 `requests` 库时,可以通过 `headers` 参数直接设置请求头:
```python
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer token"
}
response = requests.post(url, json=data, headers=headers)
```
---
### **3. 错误处理**
- **Go**:
- 使用显式的错误检查(`if err != nil`)。
- 需要手动处理每个可能出错的地方。
- **Python**:
- 使用异常处理(`try-except`)。
- 例如:
```python
try:
response = requests.post(url, json=data)
response.raise_for_status() # 检查 HTTP 错误
except requests.exceptions.RequestException as e:
print("Error:", e)
```
---
### **4. 性能**
- **Go**:
- Go 是编译型语言,性能较高,适合高并发场景。
- 标准库的 `net/http` 性能优异,适合构建高性能的 HTTP 客户端和服务器。
- **Python**:
- Python 是解释型语言,性能较低,但在 I/O 密集型任务中表现良好。
- `requests` 库虽然易用,但在高并发场景下性能不如 Go。
---
### **5. 并发支持**
- **Go**:
- 天生支持并发,可以使用 Goroutine 轻松实现并发请求。
- 例如:
```go
go func() {
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
// 处理响应
}()
```
- **Python**:
- 需要使用多线程(`threading`)或多进程(`multiprocessing`)来实现并发。
- 例如:
```python
from threading import Thread
def send_request():
response = requests.post(url, json=data)
print(response.json())
thread = Thread(target=send_request)
thread.start()
```
---
## 4. **总结**
| 特性 | Go | Python |
|---------------------|--------------------------------------|------------------------------------|
| **库** | 标准库 `net/http` | 第三方库 `requests` |
| **代码简洁性** | 较冗长,需要手动编码 JSON 和错误处理 | 简洁直观,适合快速开发 |
| **性能** | 高性能,适合高并发场景 | 性能较低,适合 I/O 密集型任务 |
| **并发支持** | 原生支持 Goroutine | 需要多线程或多进程 |
| **错误处理** | 显式错误检查(`if err != nil`) | 异常处理(`try-except`) |
| **适用场景** | 高性能、高并发、底层控制 | 快速开发、脚本、中小型项目 |
如果你需要高性能和高并发,Go 是更好的选择;如果你追求开发效率和代码简洁性,Python 更适合。
部分来着网络,供大家参考学习