How to handle HTTP responses using Golang?

WBOY
Release: 2024-06-05 13:30:03
Original
681 people have browsed it

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()
Copy after login

Get the status code

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

statusCode := resp.StatusCode
Copy after login

Get the header

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

header := resp.Header
Copy after login

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 {
    // 处理错误
}
Copy after login

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 {
Copy after login

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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!