Table of Contents
提供了 xinzheng 常用的golang代码块
提供了基于 unix 套接字
服务的进程间通信,用于 client
对daemon程序交互。
package main
import(
common "common-go"
"flag"
"log"
)
const SOCKET_FILE=".example.socket"
func main(){
cmd := flag.String("s","","The signal for app")
flag.Parse()
server := common.NewUnixSocketServer(SOCKET_FILE)
if *cmd != "start"{
responseBody,err := server.Dail(*cmd)
if err!=nil{
log.Fatal(err)
}else{
log.Pringln(string(responseBody))
}
return
}
go func(){
defer server.Stop()
for{
select{
case <- server.Stoped():
return
default:
//do your daemon service
}
}
}()
if err := server.Listen();err!=nil{
//stop you daemon if necessary
log.Fatal(err)
}
}
return *UnixSocketServer
返回默认服务。提供了,daemon服务起停和状态查询的功能。
type UnixSocketHandler func(*UnixSocketServer, net.Conn) error
func defaultsocketHandler(s *UnixSocketServer, c net.Conn) error {
for {
buf := make([]byte, 512)
nr, err := c.Read(buf)
if err != nil {
return nil
}
data := buf[0:nr]
switch string(data) {
case "status":
_, err = fmt.Fprintf(c, "running:%d", os.Getpid())
case "stop":
_, err = fmt.Fprintf(c, "stop:%d", os.Getpid())
s.cannel()
default:
_, err = fmt.Fprintf(c, "invalid signal")
}
if err != nil {
return err
}
}
}