chat

package module
v0.0.0-...-49870ec Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2025 License: MIT Imports: 16 Imported by: 0

README

chat — lightweight QUIC-based chat server & client for Go

A tiny, dependency-light library that provides a simple abstraction for building chat servers and clients over QUIC. Designed for embedding into applications: session-driven API with channels for input/output and an ergonomic logging hook.

Example

inmemTokenRepo := make(map[[16]byte]struct{})

server := chat.NewServer(
    chat.ServerOptions.Handler(func(ctx context.Context, s *chat.Session) {
        in, out := s.Input(ctx), s.Output(ctx)
        defer close(out)
        out <- []byte("hello from server")
        // echo messaging
        for {
            select {
                case <-ctx.Done():
                    return
                case msg := <-in:
                    out <- msg
            }
        }
    }),
    chat.ServerOptions.TokenRepo(inmemTokenRepo),
    chat.ServerOptions.Logger(func(lvl chat.LogLevel, msg string, args ...any) {
        fmt.Println(lvl, msg, args)
    }),
)

Install

go get github.com/zhmlst/chat

Documentation

Overview

Package chat provides tools for working with the chat-oriented QUIC based protocol such as server, client, etc.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidToken is returned when a token received from a client
	// does not match the expected size or format.
	ErrInvalidToken = errors.New("invalid token")

	// ErrInternal is returned when an unexpected internal server error occurs,
	// such as failures in the handshake process or token handling.
	ErrInternal = errors.New("internal server error")
)
View Source
var ClientOptions clientOptionsNamespace

ClientOptions provides available options for client.

View Source
var ErrServerNotRunning = errors.New("server not running")

ErrServerNotRunning indicates that a server operation was attempted while the server is not running.

View Source
var ServerOptions serverOptionsNamespace

ServerOptions provides available options for server.

Functions

func LogLevelStrings

func LogLevelStrings() []string

LogLevelStrings returns a slice of all String values of the enum

func NopLogger

func NopLogger(LogLevel, string, ...any)

NopLogger is a no-operation logger that discards all log messages.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a QUIC chat client.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a client with specified options.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context) error

Dial connects the client to a server and starts the chat loop.

type ClientOption

type ClientOption func(cfg *clientConfig)

ClientOption applies option to client.

type Handler

type Handler func(ctx context.Context, s *Session)

Handler defines a function type for handling sessions.

type LogLevel

type LogLevel int8

LogLevel represents the severity level of a log message.

const (
	// LogLevelDebug represents debug-level log messages.
	LogLevelDebug LogLevel = iota
	// LogLevelInfo represents informational log messages.
	LogLevelInfo
	// LogLevelWarn represents warning-level log messages.
	LogLevelWarn
	// LogLevelError represents error-level log messages.
	LogLevelError
)

func LogLevelString

func LogLevelString(s string) (LogLevel, error)

LogLevelString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func LogLevelValues

func LogLevelValues() []LogLevel

LogLevelValues returns all values of the enum

func (LogLevel) IsALogLevel

func (i LogLevel) IsALogLevel() bool

IsALogLevel returns "true" if the value is listed in the enum definition. "false" otherwise

func (LogLevel) MarshalText

func (i LogLevel) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for LogLevel

func (LogLevel) String

func (i LogLevel) String() string

func (*LogLevel) UnmarshalText

func (i *LogLevel) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for LogLevel

type Logger

type Logger func(lvl LogLevel, msg string, arg ...any)

Logger defines a logging function.

func (Logger) Debug

func (l Logger) Debug(msg string)

Debug logs a message at debug level.

func (Logger) Error

func (l Logger) Error(msg string)

Error logs a message at error level.

func (Logger) Info

func (l Logger) Info(msg string)

Info logs a message at info level.

func (Logger) Warn

func (l Logger) Warn(msg string)

Warn logs a message at warning level.

func (Logger) With

func (l Logger) With(arg ...any) Logger

With returns a new logger that appends additional arguments to every log call.

type NopTokenRepo

type NopTokenRepo struct{}

NopTokenRepo is a no-operation TokenRepo.

func (NopTokenRepo) HasToken

func (NopTokenRepo) HasToken(context.Context, [16]byte) (bool, error)

HasToken is no-operation token check method.

func (NopTokenRepo) SaveToken

func (NopTokenRepo) SaveToken(context.Context, [16]byte) error

SaveToken is no-operation token saving method.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server provides chat sessions.

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer creates a server with specified options.

func (*Server) Run

func (s *Server) Run() error

Run starts the QUIC server and begins accepting incoming connections.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully stops the server, waiting for all active sessions to complete or until the given context expires.

func (*Server) Stop

func (s *Server) Stop() error

Stop terminates the server immediately, closing all active connections.

type ServerOption

type ServerOption func(cfg *serverConfig)

ServerOption applies option to server.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a QUIC session stream.

func NewSession

func NewSession(stream *quic.Stream, lgr Logger) (*Session, error)

NewSession a new chat session.

func (*Session) Input

func (s *Session) Input(ctx context.Context) <-chan []byte

Input returns a channel that receives incoming data from the session stream.

func (*Session) Output

func (s *Session) Output(ctx context.Context) chan<- []byte

Output returns a channel where writing to it sends data to the session stream.

type TokenRepo

type TokenRepo interface {
	SaveToken(ctx context.Context, tok [16]byte) error
	HasToken(ctx context.Context, tok [16]byte) (has bool, err error)
}

TokenRepo defines the type that stores tokens.

Directories

Path Synopsis
cmd
client command
server command
Package codes defines application-level codes used to signal the reason for closing a QUIC connection.
Package codes defines application-level codes used to signal the reason for closing a QUIC connection.
internal
msg
Package msg provides utilities for constructing, sending and receiving binary messages with fixed-size headers and variable payloads.
Package msg provides utilities for constructing, sending and receiving binary messages with fixed-size headers and variable payloads.

Jump to

Keyboard shortcuts

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