About
This article is showing you how to create a minimal HTTP server.
Minimal Server
- Main
func main() {
// A handler pattern that ends with a slash matches any URL that has the pattern as a prefix.
http.HandleFunc("/", handler) // each request calls the handler function which gives the path as output
http.HandleFunc("/count", counter) // each count request calls counter
http.HandleFunc("/echo", echo) // echo the HTTP request
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
- handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}
- If two concurrent requests try to update count at the same time, it might not be incremented consistently the program would have a serious bug called a race condition. mu.Lock prevents that.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}
- echoes the HTTP request.
func echo(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
}
}
- Test by clicking on the the following URL http://localhost:8000/echo?q=1 . You should see the following HTTP get request
GET /echo?q=1 HTTP/1.1
Header["Upgrade-Insecure-Requests"] = ["1"]
Header["Cache-Control"] = ["max-age=0"]
Header["User-Agent"] = ["Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0"]
Header["Accept"] = ["text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"]
Header["Accept-Language"] = ["en,nl;q=0.7,en-US;q=0.3"]
Header["Accept-Encoding"] = ["gzip, deflate"]
Header["Connection"] = ["keep-alive"]
Host = "localhost:8000"
RemoteAddr = "127.0.0.1:52670"
Form["q"] = ["1"]