make a http request with a custom body as binary and return a binary response in go

Here is an example code that makes an HTTP request with a custom binary body and returns a binary response using Go's built-in net/http package:

main.go
package main

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

func main() {
    url := "https://example.com"
    data := []byte{0x01, 0x02, 0x03, 0x04}

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
    if err != nil {
        log.Fatal("Error creating new request:", err)
    }

    req.Header.Add("Content-Type", "application/octet-stream")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal("Error sending request:", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal("Error reading response body:", err)
    }

    fmt.Println("Response body:", body)
}
725 chars
36 lines

In this example, the binary data is stored in the data variable as a byte slice. We create a new POST request to url with the data as the request body using bytes.NewBuffer(data).

We add a Content-Type header with the value of application/octet-stream to indicate that the data is binary.

We then create a new http.Client and send the request with client.Do(req). When the response is received, we read the binary response body using ioutil.ReadAll(resp.Body). Finally, we print the response body to the console with fmt.Println("Response body:", body).

related categories

gistlibby LogSnag