Home  >  Article  >  Backend Development  >  How to handle HTTP responses using Golang?

How to handle HTTP responses using Golang?

WBOY
WBOYOriginal
2024-06-05 13:30:03681browse

Use the net/http package to process HTTP response steps in Golang: Parse the response: Use the http.Response type to obtain the response information. Get status code: Use the StatusCode field to get the response status code. Get headers: Use the Header field to get the response headers, which is a map[string][]string. Read the response body: Read the response body using the Body field, which is io.Reader. Hands-on example: Retrieve the response using the JSON API, parse the JSON and print the title of the post.

如何使用 Golang 处理 HTTP 响应?

How to handle HTTP responses using Golang

When you send an HTTP request, the server returns a response. This response contains information about the status of the request and the content of the request (if any). In Golang, you can use the net/http package to handle HTTP responses.

Parse the response

To parse the HTTP response, you can use the http.Response type. This type contains information about the response, including status code, headers, and response body. Here's how to parse the response:

resp, err := http.Get("https://example.com")
if err != nil {
    // 处理错误
}
defer resp.Body.Close()

Get the status code

To get the status code of the response, you can use the StatusCode field:

statusCode := resp.StatusCode

Get the header

To get the response header, you can use the Header field:

header := resp.Header

Header field is a map[string][]string where the keys are header names and the values ​​are a list of header values.

Read the response body

To read the response body, you can use the Body field:

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // 处理错误
}

Body The field is io.Reader from which the response body can be read.

Practical Case: Using JSON API

The following is a practical case demonstrating how to use Golang to retrieve JSON API response:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type Post struct {

The above is the detailed content of How to handle HTTP responses using Golang?. 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