refactoring

This commit is contained in:
crusader
2017-09-05 16:48:19 +09:00
parent 7b05682732
commit 0cf3116314
12 changed files with 228 additions and 66 deletions

View File

@@ -2,25 +2,18 @@ package server
import (
"context"
"time"
"git.loafle.net/commons_go/config"
"git.loafle.net/commons_go/logging"
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
)
var _s ogw.Server
func NewServer(ctx context.Context) ogw.Server {
h := &serverHandlers{
ctx: ctx,
logger: logging.WithContext(ctx),
}
h.cfg = config.Sub("websocket")
h.HandshakeTimeout = h.cfg.GetDuration("HandshakeTimeout") * time.Second
h.ReadBufferSize = h.cfg.GetInt("ReadBufferSize")
h.WriteBufferSize = h.cfg.GetInt("WriteBufferSize")
h.EnableCompression = h.cfg.GetBool("EnableCompression")
h := newServerHandler(ctx)
_s := ogw.NewServer(ctx, h)
s := ogw.NewServer(ctx, h)
ofSigningKey = []byte(config.GetString("auth.signingKey"))
return s
return _s
}

View File

@@ -2,14 +2,34 @@ package server
import (
"context"
"fmt"
"time"
"git.loafle.net/commons_go/config"
"git.loafle.net/commons_go/logging"
jwt "github.com/dgrijalva/jwt-go"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
)
var ofSigningKey []byte
func newServerHandler(ctx context.Context) ogw.ServerHandler {
h := &serverHandlers{
ctx: ctx,
logger: logging.WithContext(ctx),
}
h.cfg = config.Sub("websocket")
h.HandshakeTimeout = h.cfg.GetDuration("HandshakeTimeout") * time.Second
h.ReadBufferSize = h.cfg.GetInt("ReadBufferSize")
h.WriteBufferSize = h.cfg.GetInt("WriteBufferSize")
h.EnableCompression = h.cfg.GetBool("EnableCompression")
return h
}
type serverHandlers struct {
ogw.ServerHandlers
ctx context.Context
@@ -17,20 +37,37 @@ type serverHandlers struct {
cfg config.Configurator
}
func (sh *serverHandlers) OnConnection(soc ogw.Socket) {
sh.logger.Info("connect",
zap.String("path", soc.Path()),
zap.String("id", soc.ID()),
)
func (h *serverHandlers) OnConnection(soc ogw.Socket) {
// tokenString := string(soc.Conn().Headers().Cookie("AuthToken"))
tokenString := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJvdmVyRmxvdyIsImlhdCI6MTUwNDU5NTExOSwiZXhwIjoxNTM2MTMxMTE5LCJhdWQiOiJ3d3cub3ZlcmZsb3cuY2xvdWQiLCJzdWIiOiJvdmVyZmxvd0Bsb2FmbGUuY29tIn0.-WQi3OykPlJ9x8RcZGhWXEtGw4GhU6wmyJ_AWh2rMeUatQylfPzvmum2Xfp6pwKLMmcP76XoDPNyq06i7RKWNQ"
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return ofSigningKey, nil
})
var uid string
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
uid = claims["sub"].(string)
} else {
fmt.Println(err)
return
}
AddSocket(uid, soc)
}
func (sh *serverHandlers) OnDisconnected(soc ogw.Socket) {
sh.logger.Info("disconnect",
zap.String("path", soc.Path()),
zap.String("id", soc.ID()),
)
func (h *serverHandlers) OnDisconnected(soc ogw.Socket) {
RemoveSocket(soc)
}
func (sh *serverHandlers) OnCheckOrigin(ctx *fasthttp.RequestCtx) bool {
func (h *serverHandlers) OnCheckOrigin(ctx *fasthttp.RequestCtx) bool {
if origin := string(ctx.Request.Header.Peek("Origin")); origin != "" {
ctx.Response.Header.Set("Access-Control-Allow-Origin", origin)
if string(ctx.Method()) == "OPTIONS" && string(ctx.Request.Header.Peek("Access-Control-Request-Method")) != "" {
@@ -40,6 +77,7 @@ func (sh *serverHandlers) OnCheckOrigin(ctx *fasthttp.RequestCtx) bool {
}
return true
}
func (sh *serverHandlers) OnError(ctx *fasthttp.RequestCtx, status int, reason error) {
func (h *serverHandlers) OnError(ctx *fasthttp.RequestCtx, status int, reason error) {
}

111
server/socket_manager.go Normal file
View File

@@ -0,0 +1,111 @@
package server
import (
uch "git.loafle.net/commons_go/util/channel"
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
)
type socketsChannelAction struct {
uch.Action
uid string
soc ogw.Socket
}
type SocketManager interface {
AddSocket(uid string, soc ogw.Socket)
RemoveSocket(soc ogw.Socket)
GetSocket(uid string) ogw.Socket
GetUID(soc ogw.Socket) string
}
type socketManager struct {
sockets map[string]ogw.Socket
socketsR map[ogw.Socket]string
socketsCh chan socketsChannelAction
}
var _m SocketManager
func init() {
_m = New()
}
func New() SocketManager {
m := &socketManager{
sockets: make(map[string]ogw.Socket),
socketsR: make(map[ogw.Socket]string),
socketsCh: make(chan socketsChannelAction),
}
go m.listenChannel()
return m
}
func AddSocket(uid string, soc ogw.Socket) { _m.AddSocket(uid, soc) }
func (m *socketManager) AddSocket(uid string, soc ogw.Socket) {
ca := socketsChannelAction{
uid: uid,
soc: soc,
}
ca.Type = uch.ActionTypeCreate
m.socketsCh <- ca
}
func RemoveSocket(soc ogw.Socket) { _m.RemoveSocket(soc) }
func (m *socketManager) RemoveSocket(soc ogw.Socket) {
ca := socketsChannelAction{
soc: soc,
}
ca.Type = uch.ActionTypeDelete
m.socketsCh <- ca
}
func GetSocket(uid string) ogw.Socket { return _m.GetSocket(uid) }
func (m *socketManager) GetSocket(uid string) ogw.Socket {
var ok bool
var soc ogw.Socket
if soc, ok = m.sockets[uid]; !ok {
return nil
}
return soc
}
func GetUID(soc ogw.Socket) string { return _m.GetUID(soc) }
func (m *socketManager) GetUID(soc ogw.Socket) string {
var ok bool
var uid string
if uid, ok = m.socketsR[soc]; !ok {
return ""
}
return uid
}
func (m *socketManager) _removeSocket(ca *socketsChannelAction) {
var uid string
var ok bool
soc := ca.soc
if uid, ok = m.socketsR[soc]; !ok {
return
}
delete(m.sockets, uid)
delete(m.socketsR, soc)
}
func (m *socketManager) listenChannel() {
for {
select {
case ca := <-m.socketsCh:
switch ca.Type {
case uch.ActionTypeCreate:
m.sockets[ca.uid] = ca.soc
m.socketsR[ca.soc] = ca.uid
break
case uch.ActionTypeDelete:
m._removeSocket(&ca)
break
}
}
}
}