websocket-based lrcproto server

add initialID option

+23 -13
+13 -5
options.go
··· 9 9 ) 10 10 11 11 type options struct { 12 - welcome *string 13 - writer *io.Writer 14 - verbose bool 15 - pubChan chan PubEvent 16 - initChan chan lrcpb.Event_Init 12 + welcome *string 13 + writer *io.Writer 14 + verbose bool 15 + pubChan chan PubEvent 16 + initChan chan lrcpb.Event_Init 17 + initialID *uint32 17 18 } 18 19 19 20 type Option func(option *options) error ··· 24 25 return errors.New("welcome must be at most 50 runes") 25 26 } 26 27 options.welcome = &welcome 28 + return nil 29 + } 30 + } 31 + 32 + func WithInitialID(id uint32) Option { 33 + return func(options *options) error { 34 + options.initialID = &id 27 35 return nil 28 36 } 29 37 }
+10 -8
server.go
··· 6 6 "github.com/gorilla/websocket" 7 7 "github.com/rachel-mp4/lrcproto/gen/go" 8 8 "google.golang.org/protobuf/proto" 9 - "unicode/utf16" 10 9 "log" 11 10 "net/http" 12 11 "sync" 12 + "unicode/utf16" 13 13 ) 14 14 15 15 type Server struct { ··· 84 84 if options.pubChan != nil { 85 85 s.pubChan = options.pubChan 86 86 } 87 + if options.initialID != nil { 88 + s.lastID = *options.initialID 89 + } 87 90 88 91 s.clients = make(map[*client]bool) 89 92 s.clientsMu = sync.Mutex{} 90 93 s.idmapsMu = sync.Mutex{} 91 94 s.clientToID = make(map[*client]*uint32) 92 95 s.idToClient = make(map[uint32]*client) 93 - s.lastID = 0 94 96 s.eventBus = make(chan clientEvent, 100) 95 97 return &s, nil 96 98 } ··· 117 119 } 118 120 119 121 // Stop stops a server if it has started, and returns an error if it is already stopped 120 - func (s *Server) Stop() error { 122 + func (s *Server) Stop() (uint32, error) { 121 123 if s.ctx == nil { 122 - return nil 124 + return s.lastID, nil 123 125 } 124 126 select { 125 127 case <-s.ctx.Done(): 126 - return errors.New("cannot stop already stopped server") 128 + return s.lastID, errors.New("cannot stop already stopped server") 127 129 default: 128 130 s.cancel() 129 131 s.logDebug("Goodbye world :c") 130 - return nil 132 + return s.lastID, nil 131 133 } 132 134 } 133 135 ··· 404 406 405 407 insertRunes := []rune(insert) 406 408 insertUTF16Units := utf16.Encode(insertRunes) 407 - result := make([]uint16, 0, len(baseUTF16Units) + len(insertUTF16Units)) 409 + result := make([]uint16, 0, len(baseUTF16Units)+len(insertUTF16Units)) 408 410 result = append(result, baseUTF16Units[:index]...) 409 411 result = append(result, insertUTF16Units...) 410 412 result = append(result, baseUTF16Units[index:]...) ··· 436 438 if uint32(len(baseUTF16Units)) < end { 437 439 return "", errors.New("index out of range") 438 440 } 439 - result := make([]uint16, 0, uint32(len(baseUTF16Units)) + start - end) 441 + result := make([]uint16, 0, uint32(len(baseUTF16Units))+start-end) 440 442 result = append(result, baseUTF16Units[:start]...) 441 443 result = append(result, baseUTF16Units[end:]...) 442 444 resultRunes := utf16.Decode(result)