如何在 Go (Golang) 中通过 POST 请求发送 JSON 字符串
大家好!我刚开始学习 Go,正在尝试通过 POST 请求将 JSON 数据发送到外部 REST API。我有一个包含用户数据的 struct,想以 JSON 格式发送到服务器。
这是我当前的代码,但无法正常工作:
```go
package main
import (
"fmt"
"net/http"
"strings"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func main() {
user := User{
Name: "伊万·彼得罗夫",
Email: "ivan@example.com",
Age: 30,
}
// 尝试发送 JSON 字符串
resp, err := http.Post(
"https://api.example.com/users",
"application/json",
strings.NewReader(user), // 这行不行!
)
if err != nil {
fmt.Println("错误:", err)
return
}
defer resp.Body.Close()
fmt.Println("状态:", resp.Status)
}
```
编译错误:`cannot use