在 Scotty 应用程序终止后清理

Cleaning up after a Scotty application is terminated

我有一个侦听 Unix 套接字的 Scotty 应用程序。我希望应用程序在退出时删除套接字(即当我键入 Ctrl-C 时),但我不确定如何来完成这个。我的 main 函数看起来像

main = do
    sock <- socket AF_UNIX Stream 0
    bind sock $ SockAddrUnix "/tmp/my_app.sock"
    listen sock maxListenQueue

    scottySocket def sock $ do
        ...

    removeFile "/tmp/my_app.sock"

当我输入 Ctrl-C 时,removeFile 函数没有被调用——这似乎是一个中断Scotty 框架没有或不能捕捉。有什么方法可以执行这样的清理操作吗?

最简单的原则性方法可能是使用 Control.Exception 中的 bracket:

main = bracket acquireSock cleanupSock $ \(sock, _) -> do
    listen sock maxListenQueue
    scottySocket def sock $ do
        ...
    where
    -- Acquiring the resource.
    acquireSock = do
        sock <- socket AF_UNIX Stream 0
        let sockPath = "/tmp/my_app.sock"
        bind sock $ SockAddrUnix sockPath
        return (sock, sockPath)
    -- Releasing the resource.
    cleanupSock (sock, sockPath) = do
        removeFile sockPath
        close sock