Skip to content

Instantly share code, notes, and snippets.

@slok
Created March 14, 2017 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slok/ec6e1066530eb1f1005a4404e024e2ab to your computer and use it in GitHub Desktop.
Save slok/ec6e1066530eb1f1005a4404e024e2ab to your computer and use it in GitHub Desktop.
A simple HTTP server to mock responses
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
func initFlags(addr *string, port *int, retCode *int, body *string) {
flag.StringVar(addr, "addr", "0.0.0.0", "addr where http server will listen")
flag.IntVar(port, "port", 9876, "port where http server will listen")
flag.IntVar(retCode, "return-code", http.StatusOK, "return code that will be on the response of every request")
flag.StringVar(body, "body", "mocked response", "return body that will be on the response of every request")
flag.Parse()
}
func mightyHandler(retCode int, retBody string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(retCode)
w.Write([]byte(retBody))
log.Printf("Request to '%s' with method '%s' received", r.URL.Path, r.Method)
}
}
func main() {
var addr, rbody string
var port, rcode int
initFlags(&addr, &port, &rcode, &rbody)
log.Printf("Starting mock HTTP server with %d return code", rcode)
laddr := fmt.Sprintf("%s:%d", addr, port)
log.Printf("Listening on %s", laddr)
if err := http.ListenAndServe(laddr, mightyHandler(rcode, rbody)); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment