Skip to content

Commit

Permalink
feat(signal): Added Signal Server
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 committed Jan 26, 2024
1 parent f37140f commit 4e37ed4
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 3 deletions.
9 changes: 6 additions & 3 deletions signal/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os/signal"

"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/transport"
)

var DefaultRecoveryHandler = func(err interface{}, sig os.Signal, handler Handler) {
Expand All @@ -21,6 +20,12 @@ type Server struct {

type Option func(*Server)

func AddHandler(handler ...Handler) Option {
return func(s *Server) {
s.handlers = append(s.handlers, handler...)
}
}

func WithRecoveryHandler(handler func(interface{}, os.Signal, Handler)) Option {
return func(s *Server) {
if handler != nil {
Expand All @@ -29,8 +34,6 @@ func WithRecoveryHandler(handler func(interface{}, os.Signal, Handler)) Option {
}
}

var _ transport.Server = (*Server)(nil)

func NewServer(opts ...Option) *Server {
server := &Server{
handlers: make([]Handler, 0),
Expand Down
67 changes: 67 additions & 0 deletions signal/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package signal

import (
"bytes"
"context"
"fmt"
"os"
"syscall"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

var buffer bytes.Buffer

func TestServer(t *testing.T) {
srv := newServer()

go srv.Start(context.Background()) //nolint:errcheck

time.Sleep(2 * time.Second)

assert.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGUSR1))
assert.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGUSR2))

time.Sleep(2 * time.Second)

assert.Equal(t, `exampleHandler signal: user defined signal 1
signal: user defined signal 1, handler: *signal.example2Handler, err: example2Handler panic
exampleHandler signal: user defined signal 2
`, buffer.String())

srv.Stop(context.Background()) //nolint:errcheck
}

func newServer() *Server {
srv := NewServer(
WithRecoveryHandler(func(err interface{}, signal os.Signal, handler Handler) {
buffer.WriteString(fmt.Sprintf("signal: %s, handler: %T, err: %v\n", signal, handler, err))
}),
)

srv.Register(&exampleHandler{}, &example2Handler{})

return srv
}

type exampleHandler struct{}

func (h *exampleHandler) Listen() []os.Signal {
return []os.Signal{syscall.SIGUSR1, syscall.SIGUSR2}
}

func (h *exampleHandler) Handle(sig os.Signal) {
buffer.WriteString(fmt.Sprintf("exampleHandler signal: %s\n", sig))
}

type example2Handler struct{}

func (h *example2Handler) Listen() []os.Signal {
return []os.Signal{syscall.SIGUSR1}
}

func (h *example2Handler) Handle(os.Signal) {
panic("example2Handler panic")
}

0 comments on commit 4e37ed4

Please sign in to comment.