soso

package module
v0.0.0-...-54e5686 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2019 License: MIT Imports: 11 Imported by: 0

README

Golang WebSocket Framework (Warning! Not maintained)

Soso-server
Additional libs

soso-client soso-auth

##Install

  go get -u github.com/happierall/soso-server

##Usage

  import (
  	"fmt"

  	soso "github.com/happierall/soso-server"
  )

  func main() {

    // Simple Use:
    Router := soso.Default()

    Router.CREATE("message", func (m *soso.Msg) {
      m.Success(map[string]interface{}{
        "id": 1,
      })
    })

    Router.Run(4000)

  }
  // Add routes as list:
  var Routes = soso.Routes{}
  Routes.CREATE("user", UserCreate)

  // Handler:
  func UserCreate(m *soso.Msg) {

    type Data struct {
      ID int64 `json:"id"`
    }
    data := &Data{}
    m.ReadData(data)

    // Send direct message:
    soso.SendMsg("notify", "created", m.Session,
      map[string]interface{}{
        "text": "Congratulation for first message",
      },
    )

    m.Success(map[string]interface{}{
      "id": data.ID,
    })

  }

  Router := soso.Default()
  Router.HandleRoutes(Routes)

  // You can handle net/http handlers
  http.HandleFunc("/oauth/callback/github", callbackGithub)

  // And run
  Router.Run(4000)
// Custom listener:
Router := soso.Default()
Router.Handle("user", "create", func (m *soso.Msg) {})
http.HandleFunc("/soso", Router.Receiver)
http.ListenAndServe("localhost:4000", nil)

Client request (if use without soso-client)

  // javascript pure:
  var sock = new WebSocket("ws://localhost:4000/soso")

  var data = {
      model: "message",
      action: "create",
      data: {msg: "hello world"},
      log: {},
      other: {},
  }

  sock.onopen = () => {

    sock.send( JSON.stringify( data ) )

  }

Middleware and Auth


import (
  soso "github.com/happierall/soso-server"
  jose "github.com/dvsekhvalnov/jose2go"
)

func main() {
  Router := soso.Default()

  Router.Middleware.Before(func (m *soso.Msg, start time.Time) {
  	token, uid, err := readToken(m)

    // User is blank, you can use it
  	m.User.ID = strconv.FormatInt(uid, 10)
  	m.User.Token = token
  	m.User.IsAuth = true
  	m.User.IsAnonymous = true
  })

  Router.SEARCH("user", func(m *soso.Msg) {
    if m.User.IsAuth {
      fmt.Println(m.User.Token, m.User.ID)
    }
  })

  Router.Run(4000)
}

Events and Sessions

  func main() {
    Router := soso.Default()

    soso.Sessions.OnOpen(func(session soso.Session) {
      fmt.Println("Client connected")
    })

    soso.Sessions.OnClose(func(session soso.Session) {
      fmt.Println("Client disconnected")
    })

    Router.Middleware.Before(func (m *soso.Msg, start time.Time) {
      
      uid := AuthUser()

      if m.User.IsAuth {
        soso.Sessions.Push(m.Session, uid)) 
      }

    })


    Router.Run(4000)
  }
License

MIT

Documentation

Index

Constants

View Source
const (
	Version string = "3.3.0"
)

Variables

View Source
var (
	WebSocketReadBufSize  = 1024
	WebSocketWriteBufSize = 1024

	WriteWait = 10 * time.Second // Milliseconds until write times out.
	PongWait  = 60 * time.Second // Timeout for waiting on pong.

	// Send pings to peer with this period. Must be less than pongWait.
	PingPeriod = (PongWait * 9) / 10 // Milliseconds between pings.

	MaxMessageSize    int64 = 1024 * 1024
	MessageBufferSize       = 256
)
View Source
var (
	LastLogID int = 1
)
View Source
var (
	Loger = l.New()
)
View Source
var Sessions = NewSessionList()

Functions

func DisableDebug

func DisableDebug()

func EnableDebug

func EnableDebug()

func SendError

func SendError(model, action string, session Session, levelInt int, levelStr Level, userMsg string)

func SendMsg

func SendMsg(model, action string, session Session, data map[string]interface{})

func SosoWebsocketReceiver

func SosoWebsocketReceiver(rw http.ResponseWriter, req *http.Request, engine *Engine)

Types

type Engine

type Engine struct {
	Router
}

func Default

func Default() *Engine

func New

func New() *Engine

func (*Engine) Receiver

func (s *Engine) Receiver(w http.ResponseWriter, r *http.Request)

func (*Engine) Run

func (s *Engine) Run(port int) error

func (*Engine) RunReceiver

func (s *Engine) RunReceiver(session Session)

type HandlerFunc

type HandlerFunc func(*Msg)

type Level

type Level int64
const (
	// System is unusable(Ex: This level should not be used by applications)
	LevelEmergency Level = iota
	// Should be corrected immediately(Ex: Loss of the primary ISP connection)
	LevelAlert
	// Critical conditions(Ex: A failure in the system's primary application)
	LevelCritical
	// Error conditions(Ex: An application has exceeded its file storage limit and attempts to write are failing)
	LevelError
	// May indicate that an error will occur if action is not taken (Ex: A non-root file system has only 2GB remaining)
	LevelWarning
	// Events that are unusual, but not error conditions.
	LevelNotice
	// Normal operation events that require no action (Ex: An application has started, paused or ended successfully.
	LevelInfo
	// Information useful to developers for debugging an application
	LevelDebug
)

func (Level) String

func (l Level) String() string

type Log

type Log struct {
	CodeKey string `json:"code_key"`
	CodeStr string `json:"code_str"`

	LevelInt int    `json:"level_int"`
	LevelStr string `json:"level_str"`

	LogID   string `json:"log_id"`
	UserMsg string `json:"user_msg"`
}

func NewLog

func NewLog(code_key int, lvl_str Level, user_msg string) Log

type Msg

type Msg struct {
	Request  *Request
	Response *Response

	User    User
	Context map[string]string

	// Client socket session
	Session Session

	Router *Engine
}

func (*Msg) Error

func (c *Msg) Error(code int, level Level, err error)

func (*Msg) Log

func (m *Msg) Log(code_key int, lvl_str Level, user_msg string)

func (*Msg) ReadData

func (m *Msg) ReadData(object interface{}) error

func (*Msg) ReadOther

func (m *Msg) ReadOther(object interface{}) error

func (*Msg) Send

func (c *Msg) Send()

func (*Msg) Success

func (c *Msg) Success(Data interface{})

type Request

type Request struct {
	Action string           `json:"action"`
	Model  string           `json:"model"`
	Log    Log              `json:"log"`
	Data   *json.RawMessage `json:"data"`
	Other  *json.RawMessage `json:"other"`
}

Request

func NewRequest

func NewRequest(msg []byte) (*Request, error)

type Response

type Response struct {
	Model  string      `json:"model"`
	Action string      `json:"action"`
	Data   interface{} `json:"data"`
	Log    Log         `json:"log"`
	Other  interface{} `json:"other"`
}

direct and indirect responses

func NewResponse

func NewResponse(msg *Msg) *Response

func (*Response) NewLog

func (r *Response) NewLog(code_key int, lvl_str Level, user_msg string) *Response

func (Response) Result

func (r Response) Result() Response

type Route

type Route struct {
	Model  string
	Action string

	Handler HandlerFunc
}

type Router

type Router struct {
	Delay int // ms. For testing only

	Routes     []Route
	Middleware middleware
}

func (*Router) CREATE

func (r *Router) CREATE(model string, handler HandlerFunc)

func (*Router) DELETE

func (r *Router) DELETE(model string, handler HandlerFunc)

func (*Router) FLUSH

func (r *Router) FLUSH(model string, handler HandlerFunc)

func (*Router) GET

func (r *Router) GET(model string, handler HandlerFunc)

func (*Router) Handle

func (r *Router) Handle(model string, action string, handler HandlerFunc)

func (*Router) HandleList

func (r *Router) HandleList(routes []Route)

func (*Router) HandleRoutes

func (r *Router) HandleRoutes(routes Routes)

func (*Router) SEARCH

func (r *Router) SEARCH(model string, handler HandlerFunc)

func (*Router) UPDATE

func (r *Router) UPDATE(model string, handler HandlerFunc)

type Routes

type Routes struct {
	List []Route
}

func (*Routes) CREATE

func (r *Routes) CREATE(model string, handler HandlerFunc)

func (*Routes) DELETE

func (r *Routes) DELETE(model string, handler HandlerFunc)

func (*Routes) FLUSH

func (r *Routes) FLUSH(model string, handler HandlerFunc)

func (*Routes) GET

func (r *Routes) GET(model string, handler HandlerFunc)

func (*Routes) Handle

func (r *Routes) Handle(model, action string, handler HandlerFunc)

func (*Routes) SEARCH

func (r *Routes) SEARCH(model string, handler HandlerFunc)

func (*Routes) UPDATE

func (r *Routes) UPDATE(model string, handler HandlerFunc)

type Session

type Session interface {
	// Id returns a session id
	ID() string
	// Recv reads one text frame from session
	Recv() ([]byte, error)
	// Send sends one text frame to session
	Send(string) error
	// Close closes the session with provided code and reason.
	Close(status uint32, reason string) error
	IsClosed() bool
}

type SessionList

type SessionList interface {
	// Push adds session to collection
	Push(session Session, uid string) int
	// Get retries all active sessions for the user
	Get(uid string) []Session
	// Get UID - user id by session
	GetUID(session Session) (uid string, exists bool)
	// Pull removes session object from collection
	Pull(session Session) bool
	// Size returns count of active sessions
	Size(uid string) int

	// OnOpen handler at init new session
	OnOpen(func(Session))
	// OnClose handler at close session
	OnClose(func(Session))
	// OnOpenExecute fire it if session open
	// Automatical if used Router.Sessions
	OnOpenExecute(Session)
	// OnCloseExecute fire it if session close
	// Automatical if used Router.Sessions
	OnCloseExecute(Session)
}

func NewSessionList

func NewSessionList() SessionList

type SessionListImpl

type SessionListImpl struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*SessionListImpl) Get

func (s *SessionListImpl) Get(uid string) []Session

func (*SessionListImpl) GetUID

func (s *SessionListImpl) GetUID(session Session) (string, bool)

func (*SessionListImpl) OnClose

func (s *SessionListImpl) OnClose(handler func(session Session))

func (*SessionListImpl) OnCloseExecute

func (s *SessionListImpl) OnCloseExecute(session Session)

OnCloseExecute Execute close handler and pull session from list Use if custom SessionList

func (*SessionListImpl) OnOpen

func (s *SessionListImpl) OnOpen(handler func(session Session))

func (*SessionListImpl) OnOpenExecute

func (s *SessionListImpl) OnOpenExecute(session Session)

OnOpenExecute Execute open handler Use if custom SessionList

func (*SessionListImpl) Pull

func (s *SessionListImpl) Pull(session Session) bool

func (*SessionListImpl) Push

func (s *SessionListImpl) Push(session Session, uid string) int

func (*SessionListImpl) Size

func (s *SessionListImpl) Size(uid string) int

type User

type User struct {
	ID          string
	Token       string
	IsAuth      bool
	IsAnonymous bool
}

func (*User) IntID

func (u *User) IntID() (int64, error)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL