How to do it...

In this recipe, we are going to create a simple HTTP server that will render Hello World! when we browse http://localhost:8080 or execute curl http://localhost:8080 from the command line. Perform the following steps:

  1. Create http-server.go and copy the following content:
package mainimport (  "fmt"  "log"  "net/http")const (  CONN_HOST = "localhost"  CONN_PORT = "8080")func helloWorld(w http.ResponseWriter, r *http.Request) {  fmt.Fprintf(w, "Hello World!")}func main() {  http.HandleFunc("/", helloWorld)  err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)  if err != nil   {    log.Fatal("error starting http server : ", err)    return  }}
  1. Run the program with the following command:
$ go run http-server.go

Get Go Web Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.