Go NopCloser

Jmnote (토론 | 기여)님의 2024년 6월 26일 (수) 16:13 판 (새 문서: ==개요== ;Go NopCloser <syntaxhighlight lang='go' run> package main import ( "bytes" "fmt" "io" "net/http" ) func get(url string) (*http.Response, error) { resp, err := http...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

Go NopCloser
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))
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}