app

package
v0.0.0-...-47a02ed Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTokenIssuer = "fast-note-sync-service"

DefaultTokenIssuer default Token issuer // 默认 Token 签发者

Variables

View Source
var DefaultPaginationConfig = PaginationConfig{
	DefaultPageSize: 10,
	MaxPageSize:     100,
}

DefaultPaginationConfig default pagination configuration // 默认分页配置

View Source
var TraceIDKey = traceIDKeyType{}

TraceIDKey is the key to store Trace ID in context TraceIDKey 是 context 中存储 Trace ID 的 key

Functions

func GetAccessHost

func GetAccessHost(c *gin.Context) string

func GetIP

func GetIP(ctx *gin.Context) (out string)

GetIP extracts the user IP from the request context.

func GetPage

func GetPage(page int) int

func GetPageOffset

func GetPageOffset(page, pageSize int) int

func GetPageSize

func GetPageSize(pageSize int) int

GetPageSize gets page size (using default configuration) GetPageSize 获取分页大小(使用默认配置)

func GetRequestIP

func GetRequestIP(c *gin.Context) string

GetRequestIP gets the request IP GetRequestIP 获取ip

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID gets Trace ID from context GetTraceID 从 context 中获取 Trace ID

func GetUID

func GetUID(ctx *gin.Context) (out int64)

GetUid extracts the user ID from the request context.

func NoteModifyLog

func NoteModifyLog(traceID string, uid int64, action string, params ...string)

NoteModifyLog records WebSocket operation logs NoteModifyLog 记录 WebSocket 操作日志 Supports both structured logs and development environment colored output 同时支持结构化日志和开发环境彩色输出 traceID: trace ID traceID: 追踪 ID uid: user ID uid: 用户 ID action: name of the operation executed action: 执行的操作名称 params: variadic parameters, usually the first is Path, the second is Vault params: 可变参数,通常第一个为 Path,第二个为 Vault

func RequestParamStrParse

func RequestParamStrParse(c *gin.Context, param any)

RequestParamStrParse parses request parameters RequestParamStrParse 解析 Keep original behavior 保持原有行为

func SetTokenToContextWithKey

func SetTokenToContextWithKey(ctx *gin.Context, tokenString string, secretKey string) error

SetTokenToContextWithKey sets Token to Context with specified key SetTokenToContextWithKey 使用指定密钥设置 Token 到 Context

func SetWSLogger

func SetWSLogger(logger *zap.Logger)

SetWSLogger sets the logger for WebSocket module SetWSLogger 设置 WebSocket 模块的日志器

func SetWSProductionMode

func SetWSProductionMode(production bool)

SetWSProductionMode sets the production mode flag for WebSocket module SetWSProductionMode 设置 WebSocket 模块的生产模式标记

Types

type AppContainer

type AppContainer interface {
	// Logger gets logger
	// Logger 获取日志器
	Logger() *zap.Logger
	// SubmitTask submits task to Worker Pool
	// SubmitTask 提交任务到 Worker Pool
	SubmitTask(ctx context.Context, task func(context.Context) error) error
	// SubmitTaskAsync submits task to Worker Pool asynchronously (without waiting for results)
	// SubmitTaskAsync 异步提交任务到 Worker Pool(不等待结果)
	SubmitTaskAsync(ctx context.Context, task func(context.Context) error) error
	// Version gets version info
	// Version 获取版本信息
	Version() VersionInfo
	// CheckVersion checks version
	// CheckVersion 检查版本
	CheckVersion(pluginVersion string) CheckVersionInfo
	// Validator gets validator (may be nil)
	// Validator 获取验证器(可能为 nil)
	Validator() ValidatorInterface
	// IsReturnSuccess whether to return success response
	// IsReturnSuccess 是否返回成功响应
	IsReturnSuccess() bool
	// GetAuthTokenKey gets Token key
	// GetAuthTokenKey 获取 Token 密钥
	GetAuthTokenKey() string
	// IsProductionMode whether it is production mode
	// IsProductionMode 是否为生产模式
	IsProductionMode() bool
}

AppContainer defines App Container interface, used to decouple pkg/app and internal/app AppContainer 定义 App Container 接口,用于解耦 pkg/app 和 internal/app This interface allows WebsocketServer to use App Container functions without circular dependency 这个接口允许 WebsocketServer 使用 App Container 的功能而不产生循环依赖

type CheckVersionInfo

type CheckVersionInfo struct {
	GithubAvailable                  bool   `json:"githubAvailable"`
	VersionIsNew                     bool   `json:"versionIsNew"`
	VersionNewName                   string `json:"versionNewName"`
	VersionNewLink                   string `json:"versionNewLink"`
	VersionNewChangelog              string `json:"versionNewChangelog"`
	VersionNewChangelogContent       string `json:"versionNewChangelogContent"`
	PluginVersionIsNew               bool   `json:"pluginVersionIsNew"`
	PluginVersionNewName             string `json:"pluginVersionNewName"`
	PluginVersionNewLink             string `json:"pluginVersionNewLink"`
	PluginVersionNewChangelog        string `json:"pluginVersionNewChangelog"`
	PluginVersionNewChangelogContent string `json:"pluginVersionNewChangelogContent"`
}

type ClientInfoMessage

type ClientInfoMessage struct {
	Name                string `json:"name"`                // Client name // 客户端名称
	Version             string `json:"version"`             // Client version // 客户端版本
	Type                string `json:"type"`                // Client type "web" | "desktop" | "mobile" | "obsidianPlugin" // 客户端类型 "web" | "desktop" | "mobile" | "obsidianPlugin"
	OfflineSyncStrategy string `json:"offlineSyncStrategy"` // Offline device sync strategy "newTimeMerge" | "ignoreTimeMerge" // 离线设备同步策略 "newTimeMerge" | "ignoreTimeMerge"
}

type ConnStorage

type ConnStorage = map[*gws.Conn]*WebsocketClient

type Datetime

type Datetime time.Time

func (Datetime) MarshalJSON

func (t Datetime) MarshalJSON() ([]byte, error)

func (*Datetime) Scan

func (t *Datetime) Scan(v interface{}) error

func (*Datetime) String

func (t *Datetime) String() string

func (*Datetime) UnmarshalJSON

func (t *Datetime) UnmarshalJSON(data []byte) error

func (Datetime) Value

func (t Datetime) Value() (driver.Value, error)

type DiffMergeEntry

type DiffMergeEntry struct {
	CreatedAt time.Time // Entry creation time // 条目创建时间
}

DiffMergeEntry represents an entry in DiffMergePaths DiffMergeEntry 表示 DiffMergePaths 中的条目 Contains creation timestamp for timeout cleanup mechanism 包含创建时间戳,用于超时清理机制

type ListRes

type ListRes struct {
	List  interface{} `json:"list"`  // Data list // 数据清单
	Pager Pager       `json:"pager"` // Pagination info // 翻页信息
}

type LogType

type LogType string
const (
	WSPingInterval         = 25
	WSPingWait             = 60
	LogInfo        LogType = "info"
	LogError       LogType = "error"
	LogWarn        LogType = "warn"
	LogDebug       LogType = "debug"
)

type Pager

type Pager struct {
	Page      int `json:"page"`      // Page number // 页码
	PageSize  int `json:"pageSize"`  // Page size // 每页数量
	TotalRows int `json:"totalRows"` // Total rows // 总行数
}

func NewPager

func NewPager(c *gin.Context, count ...int) *Pager

NewPager creates a new Pager instance from gin.Context NewPager 从 gin.Context 创建一个新的 Pager 实例

type PaginationConfig

type PaginationConfig struct {
	DefaultPageSize int
	MaxPageSize     int
}

PaginationConfig pagination configuration // 分页配置

type PaginationRequest

type PaginationRequest struct {
	Page     int `json:"page" form:"page" query:"page"`             // Page number // 页码
	PageSize int `json:"pageSize" form:"pageSize" query:"pageSize"` // Page size // 每页数量
}

PaginationRequest pagination request parameters for Swagger // 分页请求参数(用于 Swagger)

type Res

type Res struct {
	Code    int         `json:"code"`
	Status  bool        `json:"status"`
	Message interface{} `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
	Details interface{} `json:"details,omitempty"`
	Vault   interface{} `json:"vault,omitempty"`
	Context interface{} `json:"context,omitempty"`
}

Res is the unified response structure: Code/Status/Msg/Data Optional fields Vault and Details use omitempty (will not be serialized if nil) Res 是统一的响应结构:Code/Status/Msg/Data 可选字段 Vault 与 Details 使用 omitempty(nil 则不会被序列化)

type Response

type Response struct {
	Ctx *gin.Context
}

func NewResponse

func NewResponse(ctx *gin.Context) *Response

func (*Response) ToResponse

func (r *Response) ToResponse(codeObj *code.Code)

ToResponse output to browser: unified use of Res, set Details and Vault as needed ToResponse 输出到浏览器:统一使用 Res,根据情况设置 Details 与 Vault

func (*Response) ToResponseList

func (r *Response) ToResponseList(codeObj *code.Code, list interface{}, totalRows int)

ToResponseList outputs list response using ListRes as Data; also supports dynamic Vault addition ToResponseList 输出列表响应,使用 ListRes 作为 Data;同样支持 Vault 动态添加

type SessionCleaner

type SessionCleaner interface {
	Cleanup()
}

SessionCleaner interface, used to clean up session resources when the connection is disconnected SessionCleaner 接口,用于在连接断开时清理会话资源

type ShareEntity

type ShareEntity struct {
	SID       int64               `json:"sid"`       // Share record ID in database // 数据库中的分享记录 ID (Share ID)
	UID       int64               `json:"uid"`       // User ID in database // 数据库中的用户 ID (User ID)
	Resources map[string][]string `json:"resources"` // Resource list // 资源列表
	ExpiresAt time.Time           `json:"exp"`
}

ShareEntity resource sharing Claims // ShareEntity 资源分享 Claims

func GetShareEntity

func GetShareEntity(ctx *gin.Context) (out *ShareEntity)

GetShareEntity extracts the share entity from the request context.

type SupportRecord

type SupportRecord struct {
	Time    string `json:"time"`
	Item    string `json:"item"`
	Amount  string `json:"amount"`
	Unit    string `json:"unit"`
	Message string `json:"message"`
	Name    string `json:"name"`
}

type TokenConfig

type TokenConfig struct {
	SecretKey     string        `yaml:"secret-key"`         // JWT 签名密钥
	Expiry        time.Duration `yaml:"expiry"`             // Token 过期时间,默认 365 天
	ShareTokenKey string        `yaml:"share-token-key"`    // 分享专用签名密钥
	ShareExpiry   time.Duration `yaml:"share-token-expiry"` // 分享专用过期时间
	Issuer        string        `yaml:"issuer"`             // Token issuer // Token 签发者
}

TokenConfig defines Token manager configuration // TokenConfig 定义 Token 管理器的配置

type TokenManager

type TokenManager interface {
	// User authentication related // 用户认证相关
	Generate(uid int64, nickname, ip string) (string, error)
	Parse(token string) (*UserEntity, error)

	// Resource sharing related // 资源分享相关
	ShareGenerate(shareID int64, uid int64, resources map[string][]string) (string, error)
	ShareParse(token string) (*ShareEntity, error)

	Validate(token string) error
	GetSecretKey() string
}

TokenManager defines Token management interface // TokenManager 定义 Token 管理接口

func NewTokenManager

func NewTokenManager(cfg TokenConfig) TokenManager

NewTokenManager creates a new TokenManager instance NewTokenManager 创建一个新的 TokenManager 实例

type UserEntity

type UserEntity struct {
	UID      int64  `json:"uid"`
	Nickname string `json:"nickname"`
	IP       string `json:"ip"`
	jwt.RegisteredClaims
}

func ParseTokenWithKey

func ParseTokenWithKey(tokenString string, secretKey string) (*UserEntity, error)

ParseTokenWithKey parses Token with specified key ParseTokenWithKey 使用指定密钥解析 Token

type UserSelectEntity

type UserSelectEntity struct {
	UID      int64  `json:"uid"`
	Email    string `json:"email"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
}

UserSelectEntity represents the user data stored in the JWT.

type ValidError

type ValidError struct {
	Key     string
	Message string
}

func (*ValidError) Error

func (v *ValidError) Error() string

func (*ValidError) Field

func (v *ValidError) Field() string

func (*ValidError) Map

func (v *ValidError) Map() map[string]string

type ValidErrors

type ValidErrors []*ValidError

func BindAndValid

func BindAndValid(c *gin.Context, obj interface{}) (bool, ValidErrors)

BindAndValid 绑定请求参数并进行验证,支持多语言

func (ValidErrors) Error

func (v ValidErrors) Error() string

func (ValidErrors) Errors

func (v ValidErrors) Errors() []string

func (ValidErrors) ErrorsToString

func (v ValidErrors) ErrorsToString() string

func (ValidErrors) Maps

func (v ValidErrors) Maps() []map[string]string

func (ValidErrors) MapsToString

func (v ValidErrors) MapsToString() string

type ValidatorInterface

type ValidatorInterface interface {
	ValidateStruct(obj interface{}) error
}

ValidatorInterface validator interface ValidatorInterface 验证器接口

type VersionInfo

type VersionInfo struct {
	Version   string `json:"version"`
	GitTag    string `json:"gitTag"`
	BuildTime string `json:"buildTime"`
}

VersionInfo version information // 版本信息

type WSConfig

type WSConfig struct {
	GWSOption    gws.ServerOption
	PingInterval time.Duration
	PingWait     time.Duration
}

type WebSocketMessage

type WebSocketMessage struct {
	Type string `json:"type"` // Operation type, e.g., "upload", "update", "delete" // 操作类型,例如 "upload", "update", "delete"
	Data []byte `json:"data"` // File data (only used for upload and update) // 文件数据(仅在上传和更新时使用)
}

type WebsocketClient

type WebsocketClient struct {
	Server              *WebsocketServer          // WebSocket server reference // WebSocket 服务器引用,用于访问全局状态(如会话)
	Ctx                 *gin.Context              // Original HTTP upgrade request context // 原始 HTTP 升级请求的上下文
	WsCtx               context.Context           // Long-lifecycle context for WebSocket connection // WebSocket 连接的长生命周期 context
	WsCancel            context.CancelFunc        // Used to cancel WsCtx // 用于取消 WsCtx
	TraceID             string                    // Trace ID of the connection // 连接的追踪 ID
	User                *UserEntity               // Authenticated user info // 已认证用户信息,通常在握手阶段绑定
	UserClients         ConnStorage               // User connection pool // 用户连接池,支持多设备在线时广播或单点通信
	SF                  *singleflight.Group       // Concurrency control // 并发控制:相同 key 的请求只执行一次,其余等待结果
	BinaryMu            sync.Mutex                // Synchronization lock when reading and writing data // 用于读写数据时的同步锁 (不再保护 map 存储)
	ClientName          string                    // Client name (e.g., "Mac", "Windows", "iPhone") // 客户端名称 (例如 "Mac", "Windows", "iPhone")
	ClientVersion       string                    // Client version number (e.g., "1.2.4") // 客户端版本号 (例如 "1.2.4")
	IsFirstSync         bool                      // Whether it's the first sync // 是否是第一次同步过
	DiffMergePaths      map[string]DiffMergeEntry // File paths needing merging // 需要合并的文件路径,包含创建时间用于超时清理
	DiffMergePathsMu    sync.RWMutex              // Mutex lock to prevent concurrency conflicts // 互斥锁,防止并发冲突
	OfflineSyncStrategy string                    // Offline device sync strategy // 离线设备同步策略 "newTimeMerge" | "ignoreTimeMerge"
	// contains filtered or unexported fields
}

WebsocketClient struct to store each WebSocket connection and its associated state WebsocketClient 结构体来存储每个 WebSocket 连接及其相关状态

func (*WebsocketClient) BindAndValid

func (c *WebsocketClient) BindAndValid(data []byte, obj any) (bool, ValidErrors)

WebSocket version of parameter binding and validation utility functions based on global validator 基于全局验证器的 WebSocket 版本参数绑定和验证工具函数

func (*WebsocketClient) BroadcastResponse

func (c *WebsocketClient) BroadcastResponse(code *code.Code, options ...any)

BroadcastResponse converts the result to JSON format and broadcasts it to all connected clients of the current user BroadcastResponse 将结果转换为 JSON 格式并广播给当前用户的所有连接客户端

Parameters: 参数:

code: business response status code object, including status code, message and data
code: 业务响应状态码对象,包含状态码、消息和数据
options: optional parameter list
options: 可选参数列表
  - options[0] (bool):   required, whether to exclude the current client (true: exclude self, false: broadcast to all ends)
  - options[0] (bool):   必填,是否排除当前客户端 (true: 排除自己, false: 广播给所有端)
  - options[1] (string): optional, identification of action type (ActionType), used for clients to distinguish message types
  - options[1] (string): 选填,动作类型标识 (ActionType),用于客户端区分消息类型

func (*WebsocketClient) CleanupExpiredDiffMergePaths

func (c *WebsocketClient) CleanupExpiredDiffMergePaths(timeout time.Duration) int

CleanupExpiredDiffMergePaths cleans up expired DiffMergePaths entries CleanupExpiredDiffMergePaths 清理过期的 DiffMergePaths 条目 timeout: timeout duration, entries exceeding this duration will be deleted timeout: 超时时间,超过此时间的条目将被删除

func (*WebsocketClient) ClearAllDiffMergePaths

func (c *WebsocketClient) ClearAllDiffMergePaths() int

ClearAllDiffMergePaths cleans up all DiffMergePaths entries ClearAllDiffMergePaths 清理所有 DiffMergePaths 条目 Called when closing connection 在连接关闭时调用

func (*WebsocketClient) Context

func (c *WebsocketClient) Context() context.Context

Context returns the context of the WebSocket connection Context 返回 WebSocket 连接的 context Used for all operations requiring context (database queries, external calls, etc.) 用于所有需要 context 的操作(数据库查询、外部调用等)

func (*WebsocketClient) PingLoop

func (c *WebsocketClient) PingLoop(PingInterval time.Duration)

Send Ping message regularly 定期发送 Ping 消息

func (*WebsocketClient) SendBinary

func (c *WebsocketClient) SendBinary(prefix string, payload []byte) error

SendBinary sends binary messages SendBinary 发送二进制消息 prefix: 2-byte prefix prefix: 2字节前缀

func (*WebsocketClient) ToResponse

func (c *WebsocketClient) ToResponse(code *code.Code, action ...string)

ToResponse converts the result to JSON format and sends it to the client ToResponse 将结果转换为 JSON 格式并发送给客户端

func (*WebsocketClient) WithTimeout

func (c *WebsocketClient) WithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

WithTimeout creates a sub context with timeout WithTimeout 创建带超时的子 context Used for operations requiring timeout control 用于需要超时控制的操作

type WebsocketServer

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

func NewWebsocketServer

func NewWebsocketServer(c WSConfig, app AppContainer) *WebsocketServer

NewWebsocketServer creates WebSocket server instance NewWebsocketServer 创建 WebSocket 服务器实例 c: WebSocket config c: WebSocket 配置 app: App Container (Required) app: App Container(必须)

func (*WebsocketServer) AddClient

func (w *WebsocketServer) AddClient(c *WebsocketClient)

func (*WebsocketServer) AddUserClient

func (w *WebsocketServer) AddUserClient(c *WebsocketClient) ConnStorage

func (*WebsocketServer) App

func (w *WebsocketServer) App() AppContainer

App gets App Container App 获取 App Container

func (*WebsocketServer) Authorization

func (w *WebsocketServer) Authorization(c *WebsocketClient, msg *WebSocketMessage)

func (*WebsocketServer) BroadcastToUser

func (w *WebsocketServer) BroadcastToUser(uid int64, code *code.Code, action string)

func (*WebsocketServer) ClientInfo

func (w *WebsocketServer) ClientInfo(c *WebsocketClient, msg *WebSocketMessage)

func (*WebsocketServer) GetClient

func (w *WebsocketServer) GetClient(conn *gws.Conn) *WebsocketClient

func (*WebsocketServer) GetSession

func (w *WebsocketServer) GetSession(uid string, sessionID string) any

GetSession gets global binary upload session GetSession 获取全局二进制上传会话

func (*WebsocketServer) OnClose

func (w *WebsocketServer) OnClose(conn *gws.Conn, err error)

func (*WebsocketServer) OnMessage

func (w *WebsocketServer) OnMessage(conn *gws.Conn, message *gws.Message)

func (*WebsocketServer) OnOpen

func (w *WebsocketServer) OnOpen(conn *gws.Conn)

func (*WebsocketServer) OnPing

func (w *WebsocketServer) OnPing(socket *gws.Conn, payload []byte)

func (*WebsocketServer) OnPong

func (w *WebsocketServer) OnPong(socket *gws.Conn, payload []byte)

func (*WebsocketServer) RemoveClient

func (w *WebsocketServer) RemoveClient(conn *gws.Conn)

func (*WebsocketServer) RemoveSession

func (w *WebsocketServer) RemoveSession(uid string, sessionID string)

RemoveSession removes global binary upload session RemoveSession 移除全局二进制上传会话

func (*WebsocketServer) RemoveUserClient

func (w *WebsocketServer) RemoveUserClient(c *WebsocketClient)

func (*WebsocketServer) Run

func (w *WebsocketServer) Run() gin.HandlerFunc

func (*WebsocketServer) SetSession

func (w *WebsocketServer) SetSession(uid string, sessionID string, session any)

SetSession sets global binary upload session SetSession 设置全局二进制上传会话

func (*WebsocketServer) Upgrade

func (w *WebsocketServer) Upgrade()

func (*WebsocketServer) Use

func (w *WebsocketServer) Use(action string, handler func(*WebsocketClient, *WebSocketMessage))

func (*WebsocketServer) UseBinary

func (w *WebsocketServer) UseBinary(prefix string, handler func(*WebsocketClient, []byte))

func (*WebsocketServer) UseUserVerify

func (w *WebsocketServer) UseUserVerify(handler func(*WebsocketClient, int64) (*UserSelectEntity, error))

Jump to

Keyboard shortcuts

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