Skip to content

Instantly share code, notes, and snippets.

@hawx
Last active February 5, 2016 11:21
Show Gist options
  • Save hawx/1a36c17c51bef601a437 to your computer and use it in GitHub Desktop.
Save hawx/1a36c17c51bef601a437 to your computer and use it in GitHub Desktop.
HTTP Listener
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
func requestToString(r *http.Request) string {
s := r.Proto + " " + r.Method + " " + r.URL.String() + "\n"
for k, v := range r.Header {
s += k + ": " + strings.Join(v, ", ") + "\n"
}
body, err := ioutil.ReadAll(r.Body)
if err == nil {
s += "\n" + string(body) + "\n"
}
return s
}
func main() {
port := ":8080"
if len(os.Args) > 1 {
port = ":" + os.Args[1]
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Println(requestToString(r))
})
log.Println("Listening on port", port)
log.Fatal(http.ListenAndServe(port, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment