Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reliably unlink() a Unix domain socket in Go programming language
    text
    copied!<p>I have a Go program hosting a simple HTTP service on <code>localhost:8080</code> so I can connect my public <code>nginx</code> host to it via the <code>proxy_pass</code> directive, as a reverse proxy to serve part of my site's requests. This is all working great, no problems there.</p> <p>I want to convert the Go program to host the HTTP service on a Unix domain socket instead of a local TCP socket for improved security and to reduce the unnecessary protocol overhead of TCP.</p> <p><strong>PROBLEM</strong>: The problem is that Unix domain sockets cannot be reused once they are <code>bind()</code> to, even after program termination. The second time (and every time after) I run the Go program it exits with a fatal error <code>"address already in use"</code>.</p> <p>Common practice is to <code>unlink()</code> Unix domain sockets (i.e. remove the file) when the server shuts down. However, this is tricky in Go. My first attempt was to use the <code>defer</code> statement in my main func (see below), but it is not getting run if I interrupt the process with a signal like CTRL-C. I suppose this is to be expected. Disappointing, but not unexpected.</p> <p><strong>QUESTION</strong>: Is there a best practice on how to <code>unlink()</code> the socket when the server process shuts down (either gracefully or ungracefully)?</p> <p>Here's part of my <code>func main()</code> that starts the server listening for reference:</p> <pre><code>// Create the HTTP server listening on the requested socket: l, err := net.Listen("unix", "/tmp/mysocket") if err != nil { log.Fatal(err) } else { // Unix sockets must be unlink()ed before being reused again. // Unfortunately, this defer is not run when a signal is received, e.g. CTRL-C. defer func() { os.Remove("/tmp/mysocket") }() log.Fatal(http.Serve(l, http.HandlerFunc(indexHtml))) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload