Exploring Go net/http Package - On How Not To Set Socket Options
Go standard library makes it super easy to start an HTTP server:
package main
import "net/http"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello there!\n"))
})
http.ListenAndServe(":8080", nil)
}
...or send an HTTP request:
package main
import "net/http"
func main() {
resp, err := http.Get("http://example.com/")
body, err := io.ReadAll(resp.Body)
}
In just ~10 lines of code, I can get a server up and running or fetch a real web page! In contrast, creating a basic HTTP server in C would take hundreds of lines, and anything beyond basics would require third-party libraries.
The Go snippets from above are so short because they rely on powerful high-level abstractions of the net
and net/http
packages. Go pragmatically chooses to optimize for frequently used scenarios, and its standard library hides many internal socket details behind these abstractions, making lots of default choices on the way. And that's very handy, but...
What if I need to fine-tune net/http
sockets before initiating the communication? For instance, how can I set some socket options like SO_REUSEPORT
or TCP_QUICKACK
?