warden

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

Warden SDK

Warden SDK 是一个用于与 Warden API 交互的 Go 客户端库。它提供了简单易用的接口来获取用户列表、检查用户是否在允许列表中,并支持缓存以提高性能。

功能特性

  • 🚀 简单易用: 提供简洁的 API 接口
  • ⚡ 高性能: 内置缓存支持,减少 API 调用
  • 🔒 安全: 支持 API Key 认证
  • 📦 灵活: 可配置的超时时间、缓存 TTL 等
  • 🔌 可扩展: 支持自定义日志实现

安装

go get github.com/soulteary/warden/pkg/warden

快速开始

基本使用
package main

import (
    "context"
    "time"
    
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    // 创建客户端选项
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithAPIKey("your-api-key").
        WithTimeout(10 * time.Second).
        WithCacheTTL(5 * time.Minute)
    
    // 创建客户端
    client, err := warden.NewClient(opts)
    if err != nil {
        panic(err)
    }
    
    // 获取用户列表
    ctx := context.Background()
    users, err := client.GetUsers(ctx)
    if err != nil {
        panic(err)
    }
    
    // 检查用户是否在列表中
    exists := client.CheckUserInList(ctx, "13800138000", "user@example.com")
    if exists {
        println("User is in the allow list")
    }
}
使用自定义日志

SDK 支持自定义日志实现。例如,使用 logrus:

import (
    "github.com/sirupsen/logrus"
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    logger := logrus.StandardLogger()
    
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithLogger(warden.NewLogrusAdapter(logger))
    
    client, err := warden.NewClient(opts)
    // ...
}
分页查询
// 获取分页用户列表
resp, err := client.GetUsersPaginated(ctx, 1, 10) // 第1页,每页10条
if err != nil {
    panic(err)
}

fmt.Printf("Total users: %d\n", resp.Pagination.Total)
fmt.Printf("Total pages: %d\n", resp.Pagination.TotalPages)
for _, user := range resp.Data {
    fmt.Printf("Phone: %s, Mail: %s\n", user.Phone, user.Mail)
}
清除缓存
// 清除客户端缓存
client.ClearCache()

API 参考

Options

Options 结构体用于配置客户端:

  • BaseURL: Warden 服务地址(必需)
  • APIKey: API Key(可选)
  • Timeout: HTTP 请求超时时间(默认 10 秒)
  • CacheTTL: 缓存 TTL(默认 5 分钟)
  • Logger: 日志接口(可选,默认使用 NoOpLogger)
Client 方法
NewClient(opts *Options) (*Client, error)

创建新的 Warden 客户端。

GetUsers(ctx context.Context) ([]AllowListUser, error)

获取所有用户列表。如果缓存有效,会直接返回缓存的数据。

GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)

获取分页用户列表。

  • page: 页码(从 1 开始)
  • pageSize: 每页大小

返回 PaginatedResponse,包含:

  • Data: 用户列表
  • Pagination: 分页信息(页码、每页大小、总数、总页数)
CheckUserInList(ctx context.Context, phone, mail string) bool

检查用户是否在允许列表中。

  • phone: 用户手机号(可选)
  • mail: 用户邮箱(可选)

如果用户存在(通过手机号或邮箱匹配),返回 true;否则返回 false。

ClearCache()

清除客户端内部缓存。

类型定义

AllowListUser
type AllowListUser struct {
    Phone string `json:"phone"` // 用户手机号
    Mail  string `json:"mail"`  // 用户邮箱地址
}
PaginatedResponse
type PaginatedResponse struct {
    Data       []AllowListUser `json:"data"`
    Pagination PaginationInfo  `json:"pagination"`
}

type PaginationInfo struct {
    Page       int `json:"page"`        // 当前页码(从 1 开始)
    PageSize   int `json:"page_size"`    // 每页大小
    Total      int `json:"total"`        // 总记录数
    TotalPages int `json:"total_pages"`  // 总页数
}

错误处理

SDK 使用自定义错误类型,包含错误代码和详细信息:

if err != nil {
    if sdkErr, ok := err.(*warden.Error); ok {
        switch sdkErr.Code {
        case warden.ErrCodeUnauthorized:
            // 处理认证错误
        case warden.ErrCodeRequestFailed:
            // 处理请求失败
        // ...
        }
    }
}
错误代码
  • ErrCodeInvalidConfig: 配置无效
  • ErrCodeRequestFailed: 请求失败
  • ErrCodeInvalidResponse: 响应格式无效
  • ErrCodeUnauthorized: 未授权
  • ErrCodeNotFound: 未找到
  • ErrCodeServerError: 服务器错误

最佳实践

  1. 复用客户端: 创建一次客户端,在整个应用生命周期中复用
  2. 合理设置缓存 TTL: 根据数据更新频率设置合适的缓存时间
  3. 使用 Context: 传递 context 以支持取消和超时控制
  4. 错误处理: 始终检查并处理错误
  5. 日志记录: 在生产环境中使用合适的日志实现

示例

完整示例请参考 example 目录。

许可证

MIT License

Documentation

Overview

Package warden provides a client SDK for interacting with Warden API.

Index

Constants

View Source
const (
	ErrCodeInvalidConfig   = "INVALID_CONFIG"
	ErrCodeRequestFailed   = "REQUEST_FAILED"
	ErrCodeInvalidResponse = "INVALID_RESPONSE"
	ErrCodeUnauthorized    = "UNAUTHORIZED"
	ErrCodeNotFound        = "NOT_FOUND"
	ErrCodeServerError     = "SERVER_ERROR"
)

Predefined error codes

Variables

This section is empty.

Functions

This section is empty.

Types

type AllowListUser

type AllowListUser struct {
	Phone  string   `json:"phone"`   // User phone number
	Mail   string   `json:"mail"`    // User email address
	UserID string   `json:"user_id"` // User unique identifier (optional, auto-generated if not provided)
	Status string   `json:"status"`  // User status (e.g., "active", "inactive", "suspended")
	Scope  []string `json:"scope"`   // User permission scope (optional)
	Role   string   `json:"role"`    // User role (optional)
}

AllowListUser represents a user in the allow list.

func (*AllowListUser) IsActive added in v0.3.0

func (u *AllowListUser) IsActive() bool

IsActive checks if the user status is active.

Returns true if the user status is "active", false otherwise. This method is used to verify if a user is allowed to access the system.

func (*AllowListUser) IsValid added in v0.3.0

func (u *AllowListUser) IsValid() bool

IsValid checks if the user has a valid status for authentication.

Returns true if the user status is one of the valid statuses (currently only "active"). This method can be extended in the future to support other valid statuses if needed.

type Cache

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

Cache provides thread-safe caching for user list.

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache instance with the specified TTL.

func (*Cache) Clear

func (c *Cache) Clear()

Clear clears the cache.

func (*Cache) Get

func (c *Cache) Get() []AllowListUser

Get returns the cached user list if it's still valid, nil otherwise.

func (*Cache) Set

func (c *Cache) Set(users []AllowListUser)

Set stores the user list in cache with expiration.

type Client

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

Client is the Warden API client.

func NewClient

func NewClient(opts *Options) (*Client, error)

NewClient creates a new Warden API client with the provided options.

func (*Client) CheckUserInList

func (c *Client) CheckUserInList(ctx context.Context, phone, mail string) bool

CheckUserInList checks if a user (by phone or mail) is in the allow list and has active status. Returns false if the user is not found, has inactive/suspended status, or if there's an error. This method uses GetUserByIdentifier for better performance and includes status validation.

func (*Client) ClearCache

func (c *Client) ClearCache()

ClearCache clears the internal cache.

func (*Client) GetUserByIdentifier

func (c *Client) GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)

GetUserByIdentifier fetches a single user by phone, mail, or user_id. Only one identifier should be provided.

func (*Client) GetUsers

func (c *Client) GetUsers(ctx context.Context) ([]AllowListUser, error)

GetUsers fetches the user list from Warden API. If pagination parameters are not provided, returns all users.

func (*Client) GetUsersPaginated

func (c *Client) GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)

GetUsersPaginated fetches a paginated user list from Warden API.

type Error

type Error struct {
	Code    string // Error code
	Message string // Error message
	Err     error  // Original error (if any)
}

Error represents an error that occurred in the SDK.

func NewError

func NewError(code, message string, err error) *Error

NewError creates a new SDK error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Logger

type Logger interface {
	Debug(msg string)
	Debugf(format string, args ...interface{})
	Info(msg string)
	Infof(format string, args ...interface{})
	Warn(msg string)
	Warnf(format string, args ...interface{})
	Error(msg string)
	Errorf(format string, args ...interface{})
}

Logger defines the interface for logging operations. This allows the SDK to work with different logging libraries (e.g., zerolog, logrus, standard log).

type LogrusAdapter

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

LogrusAdapter adapts logrus.Logger to the SDK Logger interface.

func NewLogrusAdapter

func NewLogrusAdapter(logger *logrus.Logger) *LogrusAdapter

NewLogrusAdapter creates a new LogrusAdapter.

func (*LogrusAdapter) Debug

func (l *LogrusAdapter) Debug(msg string)

Debug logs a debug message using logrus.

func (*LogrusAdapter) Debugf

func (l *LogrusAdapter) Debugf(format string, args ...interface{})

Debugf logs a formatted debug message using logrus.

func (*LogrusAdapter) Error

func (l *LogrusAdapter) Error(msg string)

Error logs an error message using logrus.

func (*LogrusAdapter) Errorf

func (l *LogrusAdapter) Errorf(format string, args ...interface{})

Errorf logs a formatted error message using logrus.

func (*LogrusAdapter) Info

func (l *LogrusAdapter) Info(msg string)

Info logs an info message using logrus.

func (*LogrusAdapter) Infof

func (l *LogrusAdapter) Infof(format string, args ...interface{})

Infof logs a formatted info message using logrus.

func (*LogrusAdapter) Warn

func (l *LogrusAdapter) Warn(msg string)

Warn logs a warning message using logrus.

func (*LogrusAdapter) Warnf

func (l *LogrusAdapter) Warnf(format string, args ...interface{})

Warnf logs a formatted warning message using logrus.

type NoOpLogger

type NoOpLogger struct{}

NoOpLogger is a no-op implementation of Logger that discards all log messages. This is used as the default logger when no logger is provided.

func (*NoOpLogger) Debug

func (n *NoOpLogger) Debug(msg string)

Debug discards debug messages.

func (*NoOpLogger) Debugf

func (n *NoOpLogger) Debugf(format string, args ...interface{})

Debugf discards formatted debug messages.

func (*NoOpLogger) Error

func (n *NoOpLogger) Error(msg string)

Error discards error messages.

func (*NoOpLogger) Errorf

func (n *NoOpLogger) Errorf(format string, args ...interface{})

Errorf discards formatted error messages.

func (*NoOpLogger) Info

func (n *NoOpLogger) Info(msg string)

Info discards info messages.

func (*NoOpLogger) Infof

func (n *NoOpLogger) Infof(format string, args ...interface{})

Infof discards formatted info messages.

func (*NoOpLogger) Warn

func (n *NoOpLogger) Warn(msg string)

Warn discards warning messages.

func (*NoOpLogger) Warnf

func (n *NoOpLogger) Warnf(format string, args ...interface{})

Warnf discards formatted warning messages.

type Options

type Options struct {
	BaseURL  string        // Warden service address (required)
	APIKey   string        // API Key (optional)
	Timeout  time.Duration // HTTP request timeout (default 10s)
	CacheTTL time.Duration // Cache TTL (default 5 minutes)
	Logger   Logger        // Logger interface (optional, defaults to NoOpLogger)
}

Options contains configuration options for the Warden SDK client.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default options with sensible defaults.

func (*Options) Validate

func (o *Options) Validate() error

Validate validates the options and returns an error if invalid.

func (*Options) WithAPIKey

func (o *Options) WithAPIKey(key string) *Options

WithAPIKey sets the API key for authentication.

func (*Options) WithBaseURL

func (o *Options) WithBaseURL(url string) *Options

WithBaseURL sets the base URL for the Warden service.

func (*Options) WithCacheTTL

func (o *Options) WithCacheTTL(ttl time.Duration) *Options

WithCacheTTL sets the cache TTL.

func (*Options) WithLogger

func (o *Options) WithLogger(logger Logger) *Options

WithLogger sets the logger implementation.

func (*Options) WithTimeout

func (o *Options) WithTimeout(timeout time.Duration) *Options

WithTimeout sets the HTTP request timeout.

type PaginatedResponse

type PaginatedResponse struct {
	Data       []AllowListUser `json:"data"`
	Pagination PaginationInfo  `json:"pagination"`
}

PaginatedResponse represents a paginated response from the Warden API.

type PaginationInfo

type PaginationInfo struct {
	Page       int `json:"page"`        // Current page number (starts from 1)
	PageSize   int `json:"page_size"`   // Page size
	Total      int `json:"total"`       // Total number of records
	TotalPages int `json:"total_pages"` // Total number of pages
}

PaginationInfo contains pagination metadata.

Jump to

Keyboard shortcuts

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