Go-lang 101
一個簡單的 Go-lang 小程式:綁定 UNIX socket 並設定接收資料、設定 timeout 以及在 Ctrl-C 之後正確離開程式:
// ~ Copyright (C) 2020-2020 cmj <cmj@cmj.tw>. All right reserved. ~
package main
import (
"time"
"fmt"
"net"
"os"
"os/signal"
)
func main() {
srv, err := net.Listen("unix", "/tmp/test.sock")
if err != nil {
fmt.Println("cannot create unix socket", err)
return
}
defer srv.Close()
ch := make(chan []byte, 2)
ch_ctrl := make(chan os.Signal, 1)
signal.Notify(ch_ctrl, os.Interrupt)
go func(){
for {
if sk, err := srv.Accept(); err != nil {
// cannot create new connection
return
} else {
// create new go-routine to process the command
go func(conn net.Conn) {
msg := make([]byte, 8196)
nbytes, err := conn.Read(msg)
defer conn.Close()
if err == nil && nbytes > 0 {
msg = msg[:nbytes]
ch <- msg
}
}(sk)
}
}
}()
for {
select {
case msg := <-ch:
fmt.Println("recv", string(msg))
case <-time.After(time.Second):
fmt.Println("timeout")
case <- ch_ctrl:
fmt.Println("CTRL-C")
return
}
}
}