make a http request with a custom body as binary in go

To make an HTTP request with a custom binary body in Go, you can use the net/http package and the http.NewRequest() function. The body of the request can be created using a byte slice or a bytes.Buffer. Here is an example code snippet:

main.go
func main() {
    // create a byte slice with binary data
    data := []byte{0x50, 0x4b, 0x03, 0x04, ...}

    // create a new request
    req, err := http.NewRequest("POST", "http://example.com/upload", bytes.NewReader(data))
    if err != nil {
        // handle error
    }

    // set the Content-Type header to binary data
    req.Header.Set("Content-Type", "application/octet-stream")

    // create a client and send the request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    // handle the response
    // ...
}
616 chars
25 lines

In this example, we create a byte slice with some binary data, create a new http.Request with the binary data as the body, set the Content-Type header to application/octet-stream (indicating that the body contains binary data), create an http.Client, and send the request. Finally, we handle the response according to our needs.

related categories

gistlibby LogSnag