Go NopCloser

1 개요[ | ]

Go NopCloser
Go
Copy
package main

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

func get(url string) (*http.Response, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to get %w", err)
	}
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return resp, nil
	}
	fmt.Println("get: body=", string(bodyBytes))
	resp.Body.Close()
	resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	return resp, nil
}

func main() {
	resp, err := get("https://jsonplaceholder.typicode.com/todos/1")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println("main: body=", string(bodyBytes))
}
Loading

2 같이 보기[ | ]