https://github.com/linka-cloud/go-fork-listener
https://github.com/linka-cloud/go-fork-listener
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/linka-cloud/go-fork-listener
- Owner: linka-cloud
- License: apache-2.0
- Created: 2022-09-28T14:20:19.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-09-28T15:20:00.000Z (over 2 years ago)
- Last Synced: 2024-12-30T07:21:54.185Z (5 months ago)
- Language: Go
- Size: 13.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-fork-listener
[](https://golang.org/)
[](https://pkg.go.dev/go.linka.cloud/go-fork-listener)Go package for listening on a socket and forking a detached child process on each connection.
This is useful if you need to be able to restart a process without interrupting any connections, like *sshd*.
**Only unix like systems are supported as the connection is passed to the child process via file descriptor.**
## Usage
```go
import fork "go.linka.cloud/go-fork-listener"
```## Example
### Simple http server
```go
package mainimport (
"net/http"
"os""github.com/sirupsen/logrus"
"go.linka.cloud/go-fork-listener"
)func main() {
logrus.SetLevel(logrus.DebugLevel)
logrus.Infof("running with pid %d", os.Getpid())
lis, err := fork.Listen("tcp", ":8080")
if err != nil {
logrus.Fatal(err)
}
defer lis.Close()
if err := http.Serve(lis, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("Hello from child process!\n")); err != nil {
logrus.Error(err)
}
})); err != nil && !fork.IsClosed(err) {
logrus.Fatal(err)
}
}
```### Fork aware http server
```go
package mainimport (
"net/http"
"os""github.com/sirupsen/logrus"
"go.linka.cloud/go-fork-listener"
)func main() {
logrus.SetLevel(logrus.DebugLevel)
logrus.Infof("running with pid %d", os.Getpid())
lis, err := fork.Listen("tcp", ":8080")
if err != nil {
logrus.Fatal(err)
}
defer lis.Close()if lis.IsParent() {
// do some configuration checks or other things that need to be done only once
if err := lis.Run(); err != nil {
logrus.Fatal(err)
}
return
}// do some handler dependencies initialization
if err := http.Serve(lis, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("Hello from child process!\n")); err != nil {
logrus.Error(err)
}
})); err != nil && !fork.IsClosed(err) {
logrus.Fatal(err)
}
}```