I have the usual code:

req, err := http.Get(url) if err != nil { fmt.Println("Error") } else { fmt.Println("OK") content := []byte(req.Body) // или req.Header fmt.Printf("%s", hex.Dump(content)) } 

How do I use / convert / convert req.Byte, req.Header to []byte array?

    1 answer 1

    As a rule, you do not need to read all the bytes from the Body , because you can pass it directly, for example in json.NewDecoder . Sometimes reading can be harmful if for example a large file is transferred. If you really need it, you can use ioutil.ReadAll :

     b, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s", b) 

    You can output hexdamp headers like this:

     dumper := hex.Dumper(os.Stdout) err := resp.Header.Write(dumper) if err != nil { log.Fatal(err) } 

    Playground: https://play.golang.org/p/8J9s7tpj3e .

    • Thanks, it works! - massive
    • And what to use if he writes: can not use req (type http.Header) as io.Reader type in argument to ioutil.ReadAll: http.Header does not implement io.Reader (missing read method) - massive
    • @massive And why are you heading there? Read about working with net/http in the official documentation: golang.org/pkg/net/http . Next yourself. - Ainar-G
    • I need to convert my headers into a hex dump and display this. I do not need any work with http, I just need to transform and display a dump on the screen. - massive
    • @massive Needed because you don't understand the basics. Why are you even trying to read the body of the request, if you only need headers? A simple log.Println(resp.Header) would suffice. - Ainar-G