Saturday, May 18, 2024
HomeGolangRestrict learn bytes utilizing io.LimitedReader in Go (Golang)

Restrict learn bytes utilizing io.LimitedReader in Go (Golang)



There are conditions whenever you need to restrict the variety of bytes learn, e.g., from a server response or a file. In such a case, you may depend bytes throughout studying and cease the method on the proper second. Nevertheless, there are easier strategies in Go. Utilizing the io.LimitedReader wrapper, you may learn the set variety of bytes from the underlying reader with out modifying the studying code, because it creates a brand new io.Reader restricted to a hard and fast variety of N bytes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package deal important

import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "strings"
)

func important() {
    r := strings.NewReader("https://gosamples.dev")

    limitedReader := &io.LimitedReader{R: r, N: 8}
    physique, err := ioutil.ReadAll(limitedReader)
    if err != nil {
        log.Deadly(err)
    }
    fmt.Println(string(physique))
}

Output:

Have a look at the instance. Within the important() operate, we initialize a easy strings.Reader that comprises an URL, and we need to learn the primary 8 bytes from it. To do that, we create a brand new io.LimitedReader in line 14 that takes the underlying io.Reader and the variety of bytes to learn as arguments. Consequently, when studying knowledge from this stream, we is not going to get greater than the set variety of N bytes.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments