create a http server and read the request body as binary and return a binary response in go

To create a HTTP server in Go, you can use the net/http package. Here's an example:

main.go
package main

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

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			body, err := ioutil.ReadAll(r.Body)
			if err != nil {
				http.Error(w, "Error reading request body", http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "application/octet-stream")
			w.Write(body)
		} else {
			http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
			return
		}
	})

	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println(err)
	}
}
585 chars
29 lines

This will create a server that listens on port 8080 and responds to all requests with the binary data from the request body. The Content-Type header is set to application/octet-stream to indicate that the response is binary data.

related categories

gistlibby LogSnag