Only accept HTTP connections from Localhost in Go?

不羁的心 提交于 2019-12-05 00:21:27


I have a simple HTTP Server standing up in Golang:

h := http.NewServeMux()
h.Handle("/somepath", MyHandler)

s := &http.Server{
    Addr:    "1234",
    Handler: h,


What is the best way to drop connections where the caller is not localhost? Currently I'm considering inspecting the underlying connection information and ensuring that the IP Address is, but this wastes a whole lot of resources (and runs through a whole bunch of Go code) before ultimately dropping the connection. Ideally, I can instrument the Golang server to drop the initial TCP SYN packet based on IP Address, and not create a TCP connection at all (or reveal that this port is listening).

What's the cleanest path forward here?


Converting VonC's comment into an answer.

You can bind the host by setting host:port in your http.Server.Addr or http.ListenAndServe.

They use net.Listen internally.

From net.Listen :

For TCP and UDP, the syntax of laddr is "host:port", like "". If host is omitted, as in ":8080", Listen listens on all available interfaces instead of just the interface with the given host address.