A minimal echo service in Go

Something that comes up often in the context of testing is the need for a simple service that exposes an HTTP API. The simplest non-static service I can think of is something that replies with the same input that I provide it with.

So, let’s have a look at a service written in Go that echos the input provided by a query parameter:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func handlePing(w http.ResponseWriter, r *http.Request) {
	input := r.URL.Query().Get("this")
	fmt.Fprintf(w, input)
}

func main() {
	http.HandleFunc("/echo", handlePing)
	log.Fatal(http.ListenAndServe(":4242", nil))
}

Download main.go.

I can run this service as follows, assuming it’s stored it in a file called main.go:

$ go run main.go

Now that the service is up and running, I can invoke it (in a second terminal session) like so:

$ curl "localhost:4242/echo?this=here"
here

That’s the simplest way to provide an HTTP test service. Now you can think about how to package and deploy it, for example, as a container image.

Other things to consider:

  • What if I wanted to make the port configurable?
  • How can I handle failure scenarios better (e.g. not enough memory available)?
  • Could I increase the visibility? For example, instrument it so that it exposes Prometheus metrics.

OK, that was it for this time … stay tuned ;)