Table of Contents
Question content
Solution
Home Backend Development Golang Handling streaming HTTP responses

Handling streaming HTTP responses

Feb 09, 2024 pm 03:00 PM
Memory usage

处理流式 HTTP 响应

php editor Zimo introduces you to the method of processing streaming HTTP responses. When developing web applications, we often need to deal with the downloading of large files or the transmission of real-time streaming media. The traditional method of loading the entire response content at once will cause excessive memory usage and affect performance. To solve this problem, we can use streaming HTTP responses. Streaming HTTP responses can transmit response content in chunks, reducing memory usage and improving user experience. In PHP, we can use some libraries or custom methods to implement streaming HTTP responses to optimize our web applications.

Question content

I have the following example, which connects to an HTTP service that streams the response back in chunks to create a JSON structure. For each block, my code appends a byte rb array and the individual lines. However, my problem is trying to resolve when rb is complete so that I can decode it.

Am I missing something obvious here?

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "net/http"
)

func main() {

    body := []byte("test")

    resp, err := http.Post("http://localhost:8281/tap", "application/json", bytes.NewReader(body))
    if err != nil {
        fmt.Printf("%v\n", err)
        return
    }
    defer resp.Body.Close()
    fmt.Printf("Status: [%s]\n", resp.Status)
    fmt.Println()
    //var rb []byte
    reader := bufio.NewReader(resp.Body)
    var rb []byte

    for {

        line, err := reader.ReadBytes('\n')
        if err != nil {
            if err == io.EOF {
                break
            }
            fmt.Printf("Error reading streamed bytes %v", err)
        }
        rb = append(rb, line...)

        fmt.Println(rb)

    }
}
Copy after login

Solution

Ignore the bug in the program, rbComplete after the loop is interrupted.

This program does have errors:

  • The program only breaks out of the loop when EOF occurs. If any other kind of error occurs, the program will spin forever.
  • The program does not handle the situation where ReadBytes returns data and errors. An example of where this might happen is if the response does not end with a delimiter.

Looks like your goal is to absorb the entire response to rb. Use io.ReadAll to do this:

resp, err := http.Post("http://localhost:8281/tap", "application/json", bytes.NewReader(body))
if err != nil {
    fmt.Printf("%v\n", err)
    return
}
defer resp.Body.Close()
rb, err := io.ReadAll(resp.Body)
if err != nil {
    // handle error
}
var data SomeType
err = json.Unmarshal(rb, &data)
if err != nil {
     // handle error
}
Copy after login

If you want to decode the response body to JSON, then a better way is to let the JSON decoder read the response body:

resp, err := http.Post("http://localhost:8281/tap", "application/json", bytes.NewReader(body))
if err != nil {
    fmt.Printf("%v\n", err)
    return
}
defer resp.Body.Close()
var data SomeType
err := json.NewDecoder(resp.Body).Decode(&data)
Copy after login

The above is the detailed content of Handling streaming HTTP responses. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
What to do if your Huawei phone has insufficient memory (Practical methods to solve the problem of insufficient memory) What to do if your Huawei phone has insufficient memory (Practical methods to solve the problem of insufficient memory) Apr 29, 2024 pm 06:34 PM

Insufficient memory on Huawei mobile phones has become a common problem faced by many users, with the increase in mobile applications and media files. To help users make full use of the storage space of their mobile phones, this article will introduce some practical methods to solve the problem of insufficient memory on Huawei mobile phones. 1. Clean cache: history records and invalid data to free up memory space and clear temporary files generated by applications. Find "Storage" in the settings of your Huawei phone, click "Clear Cache" and select the "Clear Cache" button to delete the application's cache files. 2. Uninstall infrequently used applications: To free up memory space, delete some infrequently used applications. Drag it to the top of the phone screen, long press the "Uninstall" icon of the application you want to delete, and then click the confirmation button to complete the uninstallation. 3.Mobile application to

Detailed steps for cleaning memory in Xiaohongshu Detailed steps for cleaning memory in Xiaohongshu Apr 26, 2024 am 10:43 AM

1. Open Xiaohongshu, click Me in the lower right corner 2. Click the settings icon, click General 3. Click Clear Cache

The impact of the AI ​​wave is obvious. TrendForce has revised up its forecast for DRAM memory and NAND flash memory contract price increases this quarter. The impact of the AI ​​wave is obvious. TrendForce has revised up its forecast for DRAM memory and NAND flash memory contract price increases this quarter. May 07, 2024 pm 09:58 PM

According to a TrendForce survey report, the AI ​​wave has a significant impact on the DRAM memory and NAND flash memory markets. In this site’s news on May 7, TrendForce said in its latest research report today that the agency has increased the contract price increases for two types of storage products this quarter. Specifically, TrendForce originally estimated that the DRAM memory contract price in the second quarter of 2024 will increase by 3~8%, and now estimates it at 13~18%; in terms of NAND flash memory, the original estimate will increase by 13~18%, and the new estimate is 15%. ~20%, only eMMC/UFS has a lower increase of 10%. ▲Image source TrendForce TrendForce stated that the agency originally expected to continue to

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step May 06, 2024 pm 03:52 PM

The familiar open source large language models such as Llama3 launched by Meta, Mistral and Mixtral models launched by MistralAI, and Jamba launched by AI21 Lab have become competitors of OpenAI. In most cases, users need to fine-tune these open source models based on their own data to fully unleash the model's potential. It is not difficult to fine-tune a large language model (such as Mistral) compared to a small one using Q-Learning on a single GPU, but efficient fine-tuning of a large model like Llama370b or Mixtral has remained a challenge until now. Therefore, Philipp Sch, technical director of HuggingFace

How to fine-tune deepseek locally How to fine-tune deepseek locally Feb 19, 2025 pm 05:21 PM

Local fine-tuning of DeepSeek class models faces the challenge of insufficient computing resources and expertise. To address these challenges, the following strategies can be adopted: Model quantization: convert model parameters into low-precision integers, reducing memory footprint. Use smaller models: Select a pretrained model with smaller parameters for easier local fine-tuning. Data selection and preprocessing: Select high-quality data and perform appropriate preprocessing to avoid poor data quality affecting model effectiveness. Batch training: For large data sets, load data in batches for training to avoid memory overflow. Acceleration with GPU: Use independent graphics cards to accelerate the training process and shorten the training time.

What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory May 09, 2024 am 11:10 AM

1. First, enter the Edge browser and click the three dots in the upper right corner. 2. Then, select [Extensions] in the taskbar. 3. Next, close or uninstall the plug-ins you do not need.

Let large models no longer be 'big Mac'. This is the latest review of efficient fine-tuning of large model parameters. Let large models no longer be 'big Mac'. This is the latest review of efficient fine-tuning of large model parameters. Apr 28, 2024 pm 04:04 PM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com. Recently, large-scale AI models such as large language models and Vincentian graph models have developed rapidly. Under this situation, how to adapt to rapidly changing needs and quickly adapt large models to various downstream tasks has become an important challenge. Limited by computing resources, traditional full-parameter micro

Which one has better web performance, golang or java? Which one has better web performance, golang or java? Apr 21, 2024 am 12:49 AM

Golang is better than Java in terms of web performance for the following reasons: a compiled language, directly compiled into machine code, has higher execution efficiency. Efficient garbage collection mechanism reduces the risk of memory leaks. Fast startup time without loading the runtime interpreter. Request processing performance is similar, and concurrent and asynchronous programming are supported. Lower memory usage, directly compiled into machine code without the need for additional interpreters and virtual machines.

See all articles