gopaper/server.go

69 lines
1.2 KiB
Go
Raw Normal View History

2024-10-28 23:29:20 +00:00
package main
import (
"log"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
func server(waitGroup *sync.WaitGroup) {
sockfile := "/tmp/bg-go.sock"
//Create a Unix domain socket and listen for incoming connections.
socket, err := net.Listen("unix", sockfile)
if err != nil {
panic(err)
}
//cleanup sockfile
//TODO: this only works when the program is killed from outside. Make it work via defer() too?
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
os.Remove(sockfile)
os.Exit(1)
}()
for {
//Accept incoming
conn, err := socket.Accept()
if err != nil {
log.Fatal(err)
}
//create store for incoming bytes
//handle connection in separate goroutine
go func(conn net.Conn) {
defer conn.Close()
//create buffer for incoming data
buf := make([]byte, 4096)
//read data from connection
n, err := conn.Read(buf)
if err != nil {
log.Fatal(err)
}
str := strings.TrimSpace(string(buf[:n]))
newbg, err := pickRandomImage(str)
if err != nil {
panic(err)
}
hyprpaperSet(newbg)
// // Echo the data back to the connection
// _, err = conn.Write(buf[:n])
// if err != nil {
// log.Fatal(err)
// }
}(conn)
}
}