Support listening on unix socket

This commit is contained in:
Balakrishnan Balasubramanian 2023-03-29 00:16:20 -04:00
parent 4e54219efb
commit fb8fa61546

39
main.go
View File

@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path"
@ -29,13 +30,19 @@ func main() {
log.Panicln("CHKBOT_API_TOKEN is empty")
}
port := func() int {
port, unixSocketPath := func() (int, string) {
portStr := os.Getenv("CHKBOT_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
return port
defaultPort := 28923
if strings.HasPrefix(portStr, "unix/") {
return defaultPort, strings.TrimPrefix(portStr, "unix/")
}
return 28923
if port, err := strconv.Atoi(portStr); err == nil {
return port, ""
}
return defaultPort, ""
}()
dataPath := func() string {
@ -45,7 +52,7 @@ func main() {
}
if err := os.MkdirAll(dataPath, 0755); err != nil {
log.Panicf("Failed to create datapath, path: %s, err: %s\n", dataPath, err)
log.Panicf("Failed to create datapath, path: %q, err: %s\n", dataPath, err)
}
return dataPath
}()
@ -63,7 +70,14 @@ func main() {
return "unknown"
}()
log.Printf("Grocery List bot (%s) starting with datapath:%s, port:%d\n", commit, dataPath, port)
listeningOn := func() string {
if unixSocketPath != "" {
return fmt.Sprintf("socket: %q", unixSocketPath)
}
return fmt.Sprintf("port: %v", port)
}()
log.Printf("Grocery List bot (%s) starting with datapath: %q, %s\n", commit, dataPath, listeningOn)
var chats sync.Map
if err := loadData(dataPath, &chats); err != nil {
@ -123,7 +137,7 @@ func main() {
chatID := update.CallbackQuery.Message.Chat.ID
g, ok := chats.Load(chatID)
if !ok {
log.Printf("Chat not found: %d\n", chatID)
log.Printf("Chat not found: %v\n", chatID)
return
}
gl := g.(*glist.GList)
@ -131,6 +145,13 @@ func main() {
}
})
if unixSocketPath != "" {
l, err := net.Listen("unix", unixSocketPath)
if err != nil {
log.Panicf("Unable to listen to unix socket in path: %q err:%v\n", unixSocketPath, err)
}
log.Panicln(http.Serve(l, nil))
}
log.Panicln(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
@ -276,11 +297,11 @@ func loadData(dataPath string, chats *sync.Map) error {
var gl glist.GList
data, err := os.ReadFile(path.Join(dataPath, name))
if err != nil {
return fmt.Errorf("failed read file, name: %s, err:%w", name, err)
return fmt.Errorf("failed read file, name: %q, err:%w", name, err)
}
err = json.Unmarshal(data, &gl)
if err != nil {
return fmt.Errorf("failed to parse data, data:%s, err:%w", data, err)
return fmt.Errorf("failed to parse data, data:%q, err:%w", data, err)
}
chats.Store(gl.ChatID, &gl)
}