发布时间:2024-12-23 00:39:52
Once installed, you can create a new Go module by running the following commands:
``` $ mkdir myapi $ cd myapi $ go mod init example.com/myapi ``` 此命令将创建一个新的Go模块并初始化您的项目。To send a simple GET request, you can use the `Get` function from the `http` package:
```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err := http.Get("https://api.example.com/users") if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(body)) } ``` 在此示例中,我们使用`http.Get`函数发送一个GET请求,并使用`ioutil.ReadAll`函数读取响应的主体。Here is an example of how to send a GET request with query parameters:
```go package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main() { baseURL := "https://api.example.com/users" params := url.Values{} params.Add("page", "1") params.Add("limit", "10") url := fmt.Sprintf("%s?%s", baseURL, params.Encode()) resp, err := http.Get(url) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(body)) } ``` 在此示例中,我们使用`url.Values`类型构建查询参数,并使用`Encode`函数将其编码为查询字符串。然后,我们将查询字符串附加到基本URL,并发送GET请求。Here is an example of how to send a POST request:
```go package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { url := "https://api.example.com/users" payload := strings.NewReader(`{"name": "John", "age": 30}`) resp, err := http.Post(url, "application/json", payload) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(body)) } ``` 在此示例中,我们使用`strings.NewReader`函数将有效载荷转换为`io.Reader`接口,并将其传递给`http.Post`函数。Here is an example of how to send a request with custom headers:
```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { url := "https://api.example.com/users" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error:", err) return } req.Header.Set("Authorization", "Bearer YOUR_TOKEN") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(body)) } ``` 在此示例中,我们创建了一个新的`http.Request`对象,并使用`Header.Set`函数设置自定义头。然后,我们使用客户端执行请求。