| Writing a basic HTTP server is easy using the
net/httppackage. |    
package main
 | 
        
        
          |  | import (
    "fmt"
    "net/http"
)
 | 
        
        
          | A fundamental concept in net/httpservers is
handlers. A handler is an object implementing thehttp.Handlerinterface. A common way to write
a handler is by using thehttp.HandlerFuncadapter
on functions with the appropriate signature. | 
func hello(w http.ResponseWriter, req *http.Request) {
 | 
        
        
          | Functions serving as handlers take a
http.ResponseWriterand ahttp.Requestas
arguments. The response writer is used to fill in the
HTTP response. Here our simple response is just
“hello\n”. | 
    fmt.Fprintf(w, "hello\n")
}
 | 
        
        
          |  | func headers(w http.ResponseWriter, req *http.Request) {
 | 
        
        
          | This handler does something a little more
sophisticated by reading all the HTTP request
headers and echoing them into the response body. | 
    for name, headers := range req.Header {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
}
 | 
        
        
          |  | func main() {
 | 
        
        
          | We register our handlers on server routes using the
http.HandleFuncconvenience function. It sets up
the default router in thenet/httppackage and
takes a function as an argument. | 
    http.HandleFunc("/hello", hello)
    http.HandleFunc("/headers", headers)
 | 
        
        
          | Finally, we call the ListenAndServewith the port
and a handler.niltells it to use the default
router we’ve just set up. | 
    http.ListenAndServe(":8090", nil)
}
 |