Hello world
If you don't have Golang installed please Follow the instructions here
Now let's start our journey by just saying Hello world
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", handler)
err := http.ListenAndServe("127.0.0.1:8080", nil)
if err != nil {
panic(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world"))
}
Run it
All the book examples can be run if you clone the book repo. go to the goexamples directory and run them using
go run ./example-name
start the HTTP server:
cd goexamples
go run ./example-helloworld
Try it:
For testing the web server we are going to use curl
Open another terminal
curl -i http://localhost:8080
What's happenning here
With only 17 lines of code Go:
- Starts a webserver that is listening on port 8080
- When an HTTP request is made it executes the
handlerfunction
Next Steps
In the next section we are going to explain in more detail what is happening.
We are going to exampine the net/http and in particular
we are going to focus on http.Server, http.Request, http.ResponseWriter, http.ServeMux.