Create an HTTP server in Golang from scratch
Golang already comes with a robust, powerful, production-ready HTTP server. Moreover, it is very easy to use and yet remains versatile and configurable down to the smallest detail.
The http package contains a Server object with everything we need. The absolute minimum required to start are the Addr and Handler attributes.
Addr
Addr is the address on which it will listen, it is a string with the format <ip>:<puerto>. For example, if we want to receive requests from any computer on the network on port 8080, we can set it to :8080 or 0.0.0.0:8080. If we were developing, we could use 127.0.0.1:8080 so that only our computer can access (very useful on Mac to avoid the constant firewall warning).
Handler
Handler is a function that will be invoked each time the server receives an HTTP request. This function has a ResponseWriter to send our response and a Request to read the client's request.
In the following example we log the HTTP method and the URL and then send a "Hello World!!" as a response.
package main
import (
"log"
"net/http"
)
func main() {
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL)
w.Write([]byte("Hello World!!"))
}),
}
err := s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
If everything goes well when starting the server, execution will stop at the call to ListenAndServe because it is blocking, and all incoming HTTP requests will be handled by the handler function we have defined.
In this example we always return the same response regardless of the URL received.
Serving more pages
To serve more pages, for example the home page and the login page, we must manually add conditions.
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL)
if r.URL.Path == "/" {
w.Write([]byte("<h1>Inicio</h1>"))
return
}
if r.URL.Path == "/login" {
w.Write([]byte("<h1>Login</h1>"))
return
}
// ...
}),
}
This way we will get the login page when accessing http://localhost:8080/login and the home page at http://localhost:8080/
As you may have guessed, this code is fragile and not very maintainable, but luckily there are HTTP routers, also called Mux, to make our day.
Join us!
Follow the project on Discord SeniorGo - Latam.
Join the project on GitHub.
Watch the full video on YouTube.
Comentarios