kuromi

package module
v0.0.0-...-95a8a4b Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2025 License: BSD-2-Clause Imports: 7 Imported by: 0

README

kuromi

GoDoc

Minimalist websocket framework for Go. 世界クロミ化計画

Kuromi is websocket framework based on github.com/coder/websocket and rewrite of github.com/olahol/melody that abstracts away the tedious parts of handling websockets. It gets out of your way so you can write real-time apps. Features include:

  • Clear and easy interface similar to net/http or Gin.
  • A simple way to broadcast to all or selected connected sessions.
  • Message buffers making concurrent writing safe.
  • Automatic handling of sending ping/pong heartbeats that timeout broken sessions.
  • Store data on sessions.

Install

go get github.com/fshiori/kuromi

Example: chat

Chat

package main

import (
	"net/http"

	"github.com/fshiori/kuromi"
)

func main() {
	k := kuromi.New()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		k.HandleRequest(w, r)
	})

	k.HandleMessage(func(s *kuromi.Session, msg []byte) {
		k.Broadcast(msg)
	})

	http.ListenAndServe(":5000", nil)
}

Documentation

Index

Constants

View Source
const (
	CloseMessage websocket.MessageType = websocket.MessageText + 1000
)

Variables

View Source
var (
	ErrClosed            = errors.New("kuromi instance is closed")
	ErrSessionClosed     = errors.New("session is closed")
	ErrWriteClosed       = errors.New("tried to write to closed a session")
	ErrMessageBufferFull = errors.New("session message buffer is full")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	WriteWait                 time.Duration // Duration until write times out.
	PongWait                  time.Duration // Timeout for waiting on pong.
	PingPeriod                time.Duration // Duration between pings.
	MaxMessageSize            int64         // Maximum size in bytes of a message.
	MessageBufferSize         int           // The max amount of messages that can be in a sessions buffer before it starts dropping them.
	ConcurrentMessageHandling bool          // Handle messages from sessions concurrently.
}

Config kuromi configuration struct.

type Kuromi

type Kuromi struct {
	Config        *Config
	AcceptOptions *websocket.AcceptOptions
	// contains filtered or unexported fields
}

Kuromi implements a websocket manager.

func New

func New() *Kuromi

New creates a new kuromi instance with default Upgrader and Config.

func (*Kuromi) Broadcast

func (k *Kuromi) Broadcast(msg []byte) error

Broadcast broadcasts a text message to all sessions.

func (*Kuromi) BroadcastBinary

func (k *Kuromi) BroadcastBinary(msg []byte) error

BroadcastBinary broadcasts a binary message to all sessions.

func (*Kuromi) BroadcastBinaryFilter

func (k *Kuromi) BroadcastBinaryFilter(msg []byte, fn func(*Session) bool) error

BroadcastBinaryFilter broadcasts a binary message to all sessions that fn returns true for.

func (*Kuromi) BroadcastBinaryOthers

func (k *Kuromi) BroadcastBinaryOthers(msg []byte, s *Session) error

BroadcastBinaryOthers broadcasts a binary message to all sessions except session s.

func (*Kuromi) BroadcastFilter

func (k *Kuromi) BroadcastFilter(msg []byte, fn func(*Session) bool) error

BroadcastFilter broadcasts a text message to all sessions that fn returns true for.

func (*Kuromi) BroadcastMultiple

func (k *Kuromi) BroadcastMultiple(msg []byte, sessions []*Session) error

BroadcastMultiple broadcasts a text message to multiple sessions given in the sessions slice.

func (*Kuromi) BroadcastOthers

func (k *Kuromi) BroadcastOthers(msg []byte, s *Session) error

BroadcastOthers broadcasts a text message to all sessions except session s.

func (*Kuromi) Close

func (k *Kuromi) Close() error

Close closes the kuromi instance and all connected sessions.

func (*Kuromi) CloseWithMsg

func (k *Kuromi) CloseWithMsg(code websocket.StatusCode, reason string) error

CloseWithMsg closes the kuromi instance with the given close payload and all connected sessions. Use the FormatCloseMessage function to format a proper close message payload.

func (*Kuromi) HandleClose

func (k *Kuromi) HandleClose(fn func(*Session, int, string) error)

HandleClose sets the handler for close messages received from the session. The code argument to h is the received close code or CloseNoStatusReceived if the close message is empty. The default close handler sends a close frame back to the session.

The application must read the connection to process close messages as described in the section on Control Frames above.

The connection read methods return a CloseError when a close frame is received. Most applications should handle close messages as part of their normal error handling. Applications should only set a close handler when the application must perform some action before sending a close frame back to the session.

func (*Kuromi) HandleConnect

func (k *Kuromi) HandleConnect(fn func(*Session))

HandleConnect fires fn when a session connects.

func (*Kuromi) HandleDisconnect

func (k *Kuromi) HandleDisconnect(fn func(*Session))

HandleDisconnect fires fn when a session disconnects.

func (*Kuromi) HandleError

func (k *Kuromi) HandleError(fn func(*Session, error))

HandleError fires fn when a session has an error.

func (*Kuromi) HandleMessage

func (k *Kuromi) HandleMessage(fn func(*Session, []byte))

HandleMessage fires fn when a text message comes in. NOTE: by default Kuromi handles messages sequentially for each session. This has the effect that a message handler exceeding the read deadline (Config.PongWait, by default 1 minute) will time out the session. Concurrent message handling can be turned on by setting Config.ConcurrentMessageHandling to true.

func (*Kuromi) HandleMessageBinary

func (k *Kuromi) HandleMessageBinary(fn func(*Session, []byte))

HandleMessageBinary fires fn when a binary message comes in.

func (*Kuromi) HandlePong

func (k *Kuromi) HandlePong(fn func(*Session))

HandlePong fires fn when a pong is received from a session.

func (*Kuromi) HandleRequest

func (k *Kuromi) HandleRequest(w http.ResponseWriter, r *http.Request) error

HandleRequest upgrades http requests to websocket connections and dispatches them to be handled by the kuromi instance.

func (*Kuromi) HandleRequestWithKeys

func (k *Kuromi) HandleRequestWithKeys(w http.ResponseWriter, r *http.Request, keys map[string]any) error

HandleRequestWithKeys does the same as HandleRequest but populates session.Keys with keys.

func (*Kuromi) HandleSentMessage

func (k *Kuromi) HandleSentMessage(fn func(*Session, []byte))

HandleSentMessage fires fn when a text message is successfully sent.

func (*Kuromi) HandleSentMessageBinary

func (k *Kuromi) HandleSentMessageBinary(fn func(*Session, []byte))

HandleSentMessageBinary fires fn when a binary message is successfully sent.

func (*Kuromi) IsClosed

func (k *Kuromi) IsClosed() bool

IsClosed returns the status of the kuromi instance.

func (*Kuromi) Len

func (k *Kuromi) Len() int

Len return the number of connected sessions.

func (*Kuromi) Sessions

func (k *Kuromi) Sessions() ([]*Session, error)

Sessions returns all sessions. An error is returned if the kuromi session is closed.

type Session

type Session struct {
	Request *http.Request
	Keys    map[string]any
	// contains filtered or unexported fields
}

Session wrapper around websocket connections.

func (*Session) Close

func (s *Session) Close() error

Close closes session.

func (*Session) CloseWithMsg

func (s *Session) CloseWithMsg(code websocket.StatusCode, reason string) error

CloseWithMsg closes the session with the provided payload. Use the FormatCloseMessage function to format a proper close message payload.

func (*Session) Get

func (s *Session) Get(key string) (value any, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Session) IsClosed

func (s *Session) IsClosed() bool

IsClosed returns the status of the connection.

func (*Session) MustGet

func (s *Session) MustGet(key string) any

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Session) Set

func (s *Session) Set(key string, value any)

Set is used to store a new key/value pair exclusively for this session. It also lazy initializes s.Keys if it was not used previously.

func (*Session) UnSet

func (s *Session) UnSet(key string)

UnSet will delete the key and has no return value

func (*Session) WebsocketConnection

func (s *Session) WebsocketConnection() *websocket.Conn

WebsocketConnection returns the underlying websocket connection. This can be used to e.g. set/read additional websocket options or to write sychronous messages.

func (*Session) Write

func (s *Session) Write(msg []byte) error

Write writes message to session.

func (*Session) WriteBinary

func (s *Session) WriteBinary(msg []byte) error

WriteBinary writes a binary message to session.

Directories

Path Synopsis
examples
chat command

Jump to

Keyboard shortcuts

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