return a binary response from a http server in go

To return a binary response from a HTTP server in Go, you can follow these steps:

  1. Create a byte buffer containing the binary data you want to return.
  2. Set the appropriate HTTP headers for the binary data (such as Content-Type, Content-Length).
  3. Write the binary data to the HTTP response body.

Here's an example implementation:

main.go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/binary", func(w http.ResponseWriter, r *http.Request) {
		// create byte buffer with binary data
		data := []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f}

		// set HTTP headers
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", "attachment; filename=myfile.bin")
		w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data)))

		// write binary data to response body
		if _, err := w.Write(data); err != nil {
			// handle error
		}
	})

	http.ListenAndServe(":8080", nil)
}
595 chars
26 lines

In the above example, we create a byte buffer containing the binary data "Hello". Then, we set the appropriate HTTP headers for a binary response. Finally, we write the binary data to the response body using w.Write().

related categories

gistlibby LogSnag