Home  >  Article  >  Backend Development  >  How to make Post request in Go

How to make Post request in Go

PHPz
PHPzOriginal
2023-04-14 14:59:393551browse

In recent years, the Go language (also known as Golang) has become increasingly popular in enterprise-level development. Its pursuit of high efficiency, high concurrency and high performance makes it one of the preferred languages ​​for web application and API development. This article will take an in-depth look at how to make Post requests in Go, let’s take a look.

Go language provides a standard package "net/http" for common Web operations. This package can create HTTP clients to send HTTP requests and read the responses as streaming responses. This makes making fast and robust POST requests to restricted web services very simple.

First, we need to build an HTTP client. For this we can use the "Client" type from the "net/http" package. The following is a simple example:

import "net/http"

client := &http.Client{}

The function of the above code is to create an HTTP client. You can use this client to complete different HTTP operations.

Next we need to construct the HTTP request, including the HTTP method (here "POST"), URL, HTTP header and HTTP body. Here is an example of HTTP request construction:

import (
    "fmt"
    "net/http"
    "net/url"
    "strings"
)

func main() {
    //构建HTTP客户端
    client := &http.Client{}

    //定义POST URL
    url := "http://localhost:8000/api/users"

    //定义HTTP负载
    data := url.Values{}
    data.Set("name", "John Doe")
    data.Set("email", "john@doe.com")
    payload := strings.NewReader(data.Encode())

    //发送POST请求
    req, err := http.NewRequest("POST", url, payload)
    if err != nil {
        fmt.Println(err)
    }

    //设置HTTP消息头
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    //执行HTTP请求
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
    }

    //输出响应到标准输出
    fmt.Println(resp.Status)
}

In the code above, we define a POST URL, an HTTP payload, and use this information to build the HTTP request. It also sets the HTTP request header, uses the HTTP client to perform the HTTP request, and then outputs the response status. It should be noted that our HTTP payload in the example uses "url.Values", which is a data type that defines HTTP queries.

With the above code, you have mastered how to build and execute a POST request with an HTTP payload in Go. At the same time, you can also add more HTTP headers and options to meet your needs.

The above is the detailed content of How to make Post request in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn