How to make API requests using Golang

PHPz
Release: 2023-04-14 09:41:41
Original
1188 people have browsed it

Golang is a modern programming language, and it is becoming more and more popular in the field of back-end languages. Its advantages include efficient concurrency processing, memory safety, and garbage collection mechanisms. In this article, we will explore how to make API requests using Golang.

First, we need to start by installing Golang. Golang portable installation package can be downloaded from the official website https://golang.org/dl/.

After the installation is complete, we need to install an HTTP client. In this article, we will use the "net/http" package and the "json" package. These two packages are standard libraries that come with Golang, so we don't need to install them.

We need to define a structure to store the data we request. In this example, we will request a REST API and get a JSON response. Therefore, we need a struct to parse the JSON and store the response.

Next, we need to create an HTTP client. In Golang, we use the "http.Client" type to create HTTP clients. This client allows us to specify timeouts and other options.

Next, we need to define an HTTP request. In Golang, we use the "http.NewRequest()" function to create HTTP requests. This function allows us to specify request type, URL, header, Body and other parameters.

Next, we need to send an HTTP request and get the response. In Golang, we use the "client.Do()" function to send HTTP requests. This function will return an "http.Response" structure, which contains the response we need and some metadata.

Finally, we need to parse the JSON response. In Golang, we use "json.Unmarshal()" function to parse JSON response. Using this function, we can convert JSON data into the structure type we defined.

To sum up, this is a basic Golang request API framework.

package main

import (
    "net/http"
    "encoding/json"
    "fmt"
    "time"
)

type ApiResponse struct {
    Data string `json:"data"`
}

func main() {
    client := &http.Client{
        Timeout: time.Second * 10,
    }

    req, err := http.NewRequest("GET", "https://api.example.com/data", nil)
    if err != nil {
        fmt.Println(err)
    }

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer my_token")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
    }

    defer resp.Body.Close()

    var apiResponse ApiResponse
    err = json.NewDecoder(resp.Body).Decode(&apiResponse)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(apiResponse.Data)
}
Copy after login

In this example, we sent an HTTP GET request to "https://api.example.com/data" and the API will return a JSON response. We first created an HTTP client, and then used the "http.NewRequest()" method to create an HTTP request that used header information such as "Content-Type" and "Authorization". Finally, we use "client.Do()" to send the request and the "json.Unmarshal()" method to parse the JSON response.

Summary:

It is very simple to use HTTP client to request API in Golang. We only need to use the "net/http" package and "json" package in the standard library to complete the request and parse the response. Finally, we can convert the API's response into the structure type we define for use in our program.

The above is the detailed content of How to make API requests using Golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template