Learning Go - Chapter 11. 표준 라이브러리

choko's avatar
Jun 29, 2024
Learning Go - Chapter 11. 표준 라이브러리
 

io.Reader/Writer

  • byte 형식을 주고받을때 byte stream으로 io.Reader, io.Writer 인터페이스를 사용한다.
notion image
  • Read(p []byte) (n int, err error)
    • type Reader interface { Read(p []byte) (n int, err error) }
    • example
      • 3바이트씩 Reader에서 문자열을 읽는다.
      • 반복해서 읽으면, 읽고 남은 나머지 부분을 반복해서 읽는다.
      • Stream의 끝은 err = io.EOF 을 통해 확인한다.
      • // example func main() { // create data source src := strings.NewReader("Hello Amazing World!") // create a packet p := make([]byte, 3) // slice of length `3` // read `src` until an error is returned for { // read `p` bytes from `src` n, err := src.Read(p) fmt.Printf("%d bytes read, data: %s\n", n, p[:n]) // handle error if err == io.EOF { fmt.Println("--end-of-file--") break } else if err != nil { fmt.Println("Oops! Some error occured!", err) break } } } 3 bytes read, data: Hel 3 bytes read, data: lo 3 bytes read, data: Ama 3 bytes read, data: zin 3 bytes read, data: g W 3 bytes read, data: orl 2 bytes read, data: d! 0 bytes read, data: --end-of-file--
 
  • ReadFull(r Reader, buf []byte) (n int, err error)
    • io.Read 와 다르게, 정해진 버퍼만큼을 꼭 읽는 것을 보장해야 한다.
  • ReadAll(src io.Reader) ([]byte, error)
    • 모든 데이터를 읽은 byte를 반환한다.
 
  • Write(p []byte) (n int, err error)
    • 주워진 바이트 변수에 데이터를 읽는다.
    • type Writer interface { Write(p []byte) (n int, err error) }
 
 
 
 

Time

// TODO !
 

encoding/json

// TODO !
 

net/http

// TODO !
 
 
 
ref by
Share article

Tom의 TIL 정리방