dev

package
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2025 License: MIT Imports: 17 Imported by: 0

README

Flow框架开发环境增强模块

这是Flow框架的开发环境增强模块,为开发者提供了一系列工具和功能,以提高开发效率和调试能力。

功能特点

  • 热重载支持:自动监听文件变更并重新加载应用
  • 调试信息增强:提供详细的日志记录和调试信息展示
  • 开发服务器:集成的开发服务器,支持静态文件、代理和调试功能
  • 开发环境配置:灵活的配置选项,适应不同的开发需求

快速开始

基本使用
package main

import (
    "github.com/zzliekkas/flow/dev"
)

func main() {
    // 创建配置
    config := dev.NewConfig()
    
    // 配置热重载
    config.EnableHotReload(true)
    config.AddWatchDir("./src")
    
    // 创建开发服务器
    server, err := dev.NewDevServer(config)
    if err != nil {
        panic(err)
    }
    
    // 启动服务器
    if err := server.Start(); err != nil {
        panic(err)
    }
    
    // 保持运行直到程序结束
    select {}
}
使用热重载功能
// 创建热重载器
config := dev.NewConfig()
reloader, err := dev.NewHotReloader(config)
if err != nil {
    panic(err)
}

// 配置热重载器
reloader.AddFileExtension(".go", ".html", ".css", ".js")
reloader.OnReload(func() {
    // 重新编译和运行应用的逻辑
    println("检测到变更,正在重新加载...")
})

// 启动热重载器
if err := reloader.Start(); err != nil {
    panic(err)
}
使用调试日志记录器
// 创建日志记录器
logger := dev.NewDebugLogger(nil)

// 设置日志文件
err := logger.SetLogFile("./logs/debug.log")
if err != nil {
    panic(err)
}

// 记录不同级别的日志
logger.Debug("这是一条调试日志")
logger.Info("这是一条信息日志")
logger.Warn("这是一条警告日志")
logger.Error("这是一条错误日志")

// 记录SQL查询
logger.LogSQL("SELECT * FROM users", nil, 10*time.Millisecond, nil)

详细配置

配置选项

开发环境支持以下配置选项:

热重载配置
  • EnableHotReload(bool): 启用/禁用热重载
  • AddWatchDir(string): 添加要监视的目录
  • SetIgnorePatterns(...string): 设置要忽略的文件模式
  • SetReloadDelay(time.Duration): 设置重载延迟时间
调试配置
  • EnableVerboseLogging(bool): 启用/禁用详细日志
  • EnableShowRoutes(bool): 启用/禁用路由信息显示
  • EnableShowSQL(bool): 启用/禁用SQL查询显示
  • EnableShowHTTP(bool): 启用/禁用HTTP请求和响应显示
  • EnableProfiler(bool): 启用/禁用性能分析
  • SetProfilerPort(int): 设置性能分析端口
  • EnableConsole(bool): 启用/禁用调试控制台
  • SetConsolePort(int): 设置控制台端口
服务器配置
  • SetServerHost(string): 设置服务器地址
  • SetServerPort(int): 设置服务器端口
  • EnableHTTPS(bool): 启用/禁用HTTPS
  • EnableOpenBrowser(bool): 启用/禁用自动打开浏览器
  • SetStaticDir(string): 设置静态文件目录
  • AddProxy(path, target string): 添加代理设置
  • EnableWebSocket(bool): 启用/禁用WebSocket
  • EnableCORS(bool): 启用/禁用跨域
  • AddHeader(key, value string): 添加自定义响应头

开发服务器功能

开发服务器提供以下主要功能:

  1. 静态文件服务:自动提供静态文件访问
  2. API代理:支持将请求代理到其他服务器
  3. 热重载集成:自动检测文件变更并重启应用
  4. 调试路由:提供调试信息查看和控制
  5. 性能分析:集成性能分析工具

调试功能

调试日志记录器提供以下功能:

  1. 多级别日志:支持Debug、Info、Warn、Error、Fatal等级别
  2. 路由记录:记录注册的路由信息
  3. SQL查询记录:记录执行的SQL查询、参数和耗时
  4. HTTP请求记录:记录请求和响应的详细信息
  5. 调试信息导出:支持导出完整的调试信息

最佳实践

  1. 仅在开发环境使用:这些功能主要用于开发过程,生产环境应禁用或移除
  2. 合理配置监视目录:只监视必要的目录,避免监视过多文件导致性能问题
  3. 使用日志文件:对于长时间运行的开发会话,建议将日志输出到文件
  4. 利用性能分析:定期检查性能分析结果,及早发现潜在问题

常见问题

热重载不工作

可能的原因:

  • 监视的目录不正确
  • 文件变更太频繁,被合并处理
  • 系统限制了文件监视数量

解决方法:

  • 检查配置的监视目录
  • 增加重载延迟时间
  • 调整系统文件监视限制 (如Linux上的inotify限制)
服务器无法启动

可能的原因:

  • 端口被占用
  • 权限不足
  • 配置错误

解决方法:

  • 更改服务器端口
  • 以适当权限运行
  • 检查配置参数

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigExample

func ConfigExample()

ConfigExample 配置示例

func Example

func Example()

Example 开发环境示例

func IntegratedExample

func IntegratedExample()

IntegratedExample 集成使用示例

func StartWithHotReload

func StartWithHotReload()

StartWithHotReload 使用热重载启动应用的示例

func UsageWithDebugLogger

func UsageWithDebugLogger()

UsageWithDebugLogger 调试日志记录器使用示例

Types

type Config

type Config struct {
	// 应用根目录
	RootDir string

	// 热重载配置
	Reload ReloadConfig

	// 调试配置
	Debug DebugConfig

	// 开发服务器配置
	Server ServerConfig

	// 环境变量
	Env map[string]string

	// 自定义设置
	Settings map[string]interface{}
}

Config 开发环境配置

func NewConfig

func NewConfig() *Config

NewConfig 创建新的开发环境配置

func (*Config) AddHeader

func (c *Config) AddHeader(key, value string) *Config

AddHeader 添加自定义响应头

func (*Config) AddProxy

func (c *Config) AddProxy(path, target string) *Config

AddProxy 添加代理设置

func (*Config) AddSetting

func (c *Config) AddSetting(key string, value interface{}) *Config

AddSetting 添加自定义设置

func (*Config) AddWatchDir

func (c *Config) AddWatchDir(dir string) *Config

AddWatchDir 添加监视目录

func (*Config) EnableCORS

func (c *Config) EnableCORS(enabled bool) *Config

EnableCORS 启用跨域

func (*Config) EnableConsole

func (c *Config) EnableConsole(enabled bool) *Config

EnableConsole 启用调试控制台

func (*Config) EnableHTTPS

func (c *Config) EnableHTTPS(enabled bool) *Config

EnableHTTPS 启用HTTPS

func (*Config) EnableHotReload

func (c *Config) EnableHotReload(enabled bool) *Config

EnableHotReload 启用热重载

func (*Config) EnableOpenBrowser

func (c *Config) EnableOpenBrowser(enabled bool) *Config

EnableOpenBrowser 启用自动打开浏览器

func (*Config) EnableProfiler

func (c *Config) EnableProfiler(enabled bool) *Config

EnableProfiler 启用性能分析

func (*Config) EnableShowHTTP

func (c *Config) EnableShowHTTP(enabled bool) *Config

EnableShowHTTP 启用显示HTTP请求和响应

func (*Config) EnableShowRoutes

func (c *Config) EnableShowRoutes(enabled bool) *Config

EnableShowRoutes 启用显示路由信息

func (*Config) EnableShowSQL

func (c *Config) EnableShowSQL(enabled bool) *Config

EnableShowSQL 启用显示SQL查询

func (*Config) EnableVerboseLogging

func (c *Config) EnableVerboseLogging(enabled bool) *Config

EnableVerboseLogging 启用详细日志

func (*Config) EnableWebSocket

func (c *Config) EnableWebSocket(enabled bool) *Config

EnableWebSocket 启用WebSocket

func (*Config) GetWatchDirsAbsolute

func (c *Config) GetWatchDirsAbsolute() []string

GetWatchDirsAbsolute 获取绝对路径的监视目录列表

func (*Config) Load

func (c *Config) Load(configFile string) error

Load 从配置文件加载配置

func (*Config) Save

func (c *Config) Save(configFile string) error

Save 保存配置到文件

func (*Config) SetConsolePort

func (c *Config) SetConsolePort(port int) *Config

SetConsolePort 设置控制台端口

func (*Config) SetEnv

func (c *Config) SetEnv(key, value string) *Config

SetEnv 设置环境变量

func (*Config) SetIgnorePatterns

func (c *Config) SetIgnorePatterns(patterns ...string) *Config

SetIgnorePatterns 设置忽略的文件模式

func (*Config) SetProfilerPort

func (c *Config) SetProfilerPort(port int) *Config

SetProfilerPort 设置性能分析端口

func (*Config) SetReloadCallback

func (c *Config) SetReloadCallback(callback func()) *Config

SetReloadCallback 设置重载回调

func (*Config) SetReloadDelay

func (c *Config) SetReloadDelay(delay time.Duration) *Config

SetReloadDelay 设置重载延迟时间

func (*Config) SetRootDir

func (c *Config) SetRootDir(dir string) *Config

SetRootDir 设置应用根目录

func (*Config) SetServerHost

func (c *Config) SetServerHost(host string) *Config

SetServerHost 设置服务器地址

func (*Config) SetServerPort

func (c *Config) SetServerPort(port int) *Config

SetServerPort 设置服务器端口

func (*Config) SetStaticDir

func (c *Config) SetStaticDir(dir string) *Config

SetStaticDir 设置静态文件目录

func (*Config) ShouldIgnoreFile

func (c *Config) ShouldIgnoreFile(path string) bool

ShouldIgnoreFile 检查是否应该忽略文件

func (*Config) String

func (c *Config) String() string

String 返回配置的字符串表示

type DebugConfig

type DebugConfig struct {
	// 是否启用详细日志
	VerboseLogging bool

	// 是否显示路由信息
	ShowRoutes bool

	// 是否显示SQL查询
	ShowSQL bool

	// 是否显示HTTP请求和响应
	ShowHTTP bool

	// 是否启用性能分析
	EnableProfiler bool

	// 性能分析端口
	ProfilerPort int

	// 是否启用调试控制台
	EnableConsole bool

	// 控制台端口
	ConsolePort int
}

DebugConfig 调试配置

type DebugLogger

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

DebugLogger 调试日志记录器

func NewDebugLogger

func NewDebugLogger(config *Config) *DebugLogger

NewDebugLogger 创建调试日志记录器

func (*DebugLogger) AddRoute

func (l *DebugLogger) AddRoute(route RouteInfo)

AddRoute 添加路由信息

func (*DebugLogger) Close

func (l *DebugLogger) Close() error

Close 关闭日志记录器

func (*DebugLogger) Debug

func (l *DebugLogger) Debug(v ...interface{})

Debug 记录调试级别日志

func (*DebugLogger) Debugf

func (l *DebugLogger) Debugf(format string, v ...interface{})

Debugf 记录调试级别日志(格式化)

func (*DebugLogger) DumpDebugInfo

func (l *DebugLogger) DumpDebugInfo(w io.Writer) error

DumpDebugInfo 导出调试信息

func (*DebugLogger) Error

func (l *DebugLogger) Error(v ...interface{})

Error 记录错误级别日志

func (*DebugLogger) Errorf

func (l *DebugLogger) Errorf(format string, v ...interface{})

Errorf 记录错误级别日志(格式化)

func (*DebugLogger) Fatal

func (l *DebugLogger) Fatal(v ...interface{})

Fatal 记录致命级别日志并退出

func (*DebugLogger) Fatalf

func (l *DebugLogger) Fatalf(format string, v ...interface{})

Fatalf 记录致命级别日志并退出(格式化)

func (*DebugLogger) GetHTTPRequests

func (l *DebugLogger) GetHTTPRequests() []HTTPInfo

GetHTTPRequests 获取HTTP请求记录

func (*DebugLogger) GetRoutes

func (l *DebugLogger) GetRoutes() []RouteInfo

GetRoutes 获取所有路由信息

func (*DebugLogger) GetSQLQueries

func (l *DebugLogger) GetSQLQueries() []SQLInfo

GetSQLQueries 获取SQL查询记录

func (*DebugLogger) Info

func (l *DebugLogger) Info(v ...interface{})

Info 记录信息级别日志

func (*DebugLogger) Infof

func (l *DebugLogger) Infof(format string, v ...interface{})

Infof 记录信息级别日志(格式化)

func (*DebugLogger) LogHTTPRequest

func (l *DebugLogger) LogHTTPRequest(id, method, path string, headers http.Header, body []byte, ip string)

LogHTTPRequest 记录HTTP请求

func (*DebugLogger) LogHTTPResponse

func (l *DebugLogger) LogHTTPResponse(id string, statusCode int, headers http.Header, body []byte)

LogHTTPResponse 记录HTTP响应

func (*DebugLogger) LogSQL

func (l *DebugLogger) LogSQL(query string, args []interface{}, duration time.Duration, err error)

LogSQL 记录SQL查询

func (*DebugLogger) SetColor

func (l *DebugLogger) SetColor(enabled bool) *DebugLogger

SetColor 设置是否启用控制台颜色

func (*DebugLogger) SetLevel

func (l *DebugLogger) SetLevel(level LogLevel) *DebugLogger

SetLevel 设置日志级别

func (*DebugLogger) SetLogFile

func (l *DebugLogger) SetLogFile(filePath string) error

SetLogFile 设置日志文件

func (*DebugLogger) SetOutput

func (l *DebugLogger) SetOutput(w io.Writer) *DebugLogger

SetOutput 设置日志输出

func (*DebugLogger) SetPrefix

func (l *DebugLogger) SetPrefix(prefix string) *DebugLogger

SetPrefix 设置日志前缀

func (*DebugLogger) Warn

func (l *DebugLogger) Warn(v ...interface{})

Warn 记录警告级别日志

func (*DebugLogger) Warnf

func (l *DebugLogger) Warnf(format string, v ...interface{})

Warnf 记录警告级别日志(格式化)

type DevServer

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

DevServer 开发服务器

func NewDevServer

func NewDevServer(config *Config) (*DevServer, error)

NewDevServer 创建开发服务器

func (*DevServer) ForceRestart

func (s *DevServer) ForceRestart()

ForceRestart 强制重启应用

func (*DevServer) GetStatus

func (s *DevServer) GetStatus() ServerStatus

GetStatus 获取服务器状态

func (*DevServer) Start

func (s *DevServer) Start() error

Start 启动开发服务器

func (*DevServer) Stop

func (s *DevServer) Stop() error

Stop 停止开发服务器

func (*DevServer) Use

func (s *DevServer) Use(middleware MiddlewareFunc)

Use 使用中间件

type FileChange

type FileChange struct {
	// 文件路径
	Path string

	// 变更类型
	Op fsnotify.Op

	// 变更时间
	Time time.Time
}

FileChange 文件变更信息

type HTTPInfo

type HTTPInfo struct {
	// 请求ID
	ID string
	// 请求方法
	Method string
	// 请求路径
	Path string
	// 请求头
	Headers http.Header
	// 请求体
	Body []byte
	// 状态码
	StatusCode int
	// 响应头
	ResponseHeaders http.Header
	// 响应体
	ResponseBody []byte
	// 开始时间
	StartTime time.Time
	// 结束时间
	EndTime time.Time
	// 持续时间
	Duration time.Duration
	// IP地址
	IP string
}

HTTPInfo HTTP信息

type HTTPLog

type HTTPLog struct {
	// 请求记录
	Requests []HTTPInfo
	// contains filtered or unexported fields
}

HTTPLog HTTP日志

type HotReloader

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

HotReloader 热重载器

func NewHotReloader

func NewHotReloader(config *Config) (*HotReloader, error)

NewHotReloader 创建热重载器

func (*HotReloader) AddFileExtension

func (r *HotReloader) AddFileExtension(ext ...string) *HotReloader

AddFileExtension 添加监听的文件类型

func (*HotReloader) AddFileMatcher

func (r *HotReloader) AddFileMatcher(matcher func(string) bool) *HotReloader

AddFileMatcher 添加文件匹配器

func (*HotReloader) ForceReload

func (r *HotReloader) ForceReload()

ForceReload 强制触发重载

func (*HotReloader) GetChangesChannel

func (r *HotReloader) GetChangesChannel() <-chan FileChange

GetChangesChannel 获取变更通道

func (*HotReloader) GetReloadChannel

func (r *HotReloader) GetReloadChannel() <-chan struct{}

GetReloadChannel 获取重载通道

func (*HotReloader) GetStats

func (r *HotReloader) GetStats() WatchStats

GetStats 获取监视器统计

func (*HotReloader) IsRunning

func (r *HotReloader) IsRunning() bool

IsRunning 检查热重载器是否正在运行

func (*HotReloader) OnReload

func (r *HotReloader) OnReload(callback func()) *HotReloader

OnReload 设置重载回调

func (*HotReloader) Start

func (r *HotReloader) Start() error

Start 启动热重载器

func (*HotReloader) Stop

func (r *HotReloader) Stop() error

Stop 停止热重载器

type LogLevel

type LogLevel int

LogLevel 日志级别

const (
	// DebugLevel 调试级别
	DebugLevel LogLevel = iota
	// InfoLevel 信息级别
	InfoLevel
	// WarnLevel 警告级别
	WarnLevel
	// ErrorLevel 错误级别
	ErrorLevel
	// FatalLevel 致命级别
	FatalLevel
)

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

MiddlewareFunc 中间件函数类型

type ReloadConfig

type ReloadConfig struct {
	// 是否启用热重载
	Enabled bool

	// 监视的目录列表
	WatchDirs []string

	// 忽略的文件模式
	IgnorePatterns []string

	// 重载延迟时间(毫秒)
	DelayMilliseconds int

	// 重载回调
	OnReload func()

	// 最大触发频率(秒)
	MaxFrequency int
}

ReloadConfig 热重载配置

type RouteInfo

type RouteInfo struct {
	// 方法
	Method string
	// 路径
	Path string
	// 处理器
	Handler string
	// 中间件
	Middlewares []string
	// 分组
	Group string
}

RouteInfo 路由信息

type RouteLog

type RouteLog struct {
	// 路由列表
	Routes []RouteInfo
	// contains filtered or unexported fields
}

RouteLog 路由日志

type SQLInfo

type SQLInfo struct {
	// 查询语句
	Query string
	// 参数
	Args []interface{}
	// 执行时间
	Duration time.Duration
	// 发生时间
	Time time.Time
	// 调用栈
	Stack string
	// 发生错误
	Error error
}

SQLInfo SQL信息

type SQLLog

type SQLLog struct {
	// SQL查询列表
	Queries []SQLInfo
	// contains filtered or unexported fields
}

SQLLog SQL日志

type ServerConfig

type ServerConfig struct {
	// 服务器地址
	Host string

	// 服务器端口
	Port int

	// 是否启用HTTPS
	EnableHTTPS bool

	// 是否启用自动打开浏览器
	OpenBrowser bool

	// 静态文件目录
	StaticDir string

	// 代理设置
	Proxies map[string]string

	// 自定义中间件
	Middlewares []interface{}

	// 是否启用WebSocket
	EnableWebSocket bool

	// 是否启用跨域
	EnableCORS bool

	// 自定义响应头
	Headers map[string]string
}

ServerConfig 开发服务器配置

type ServerStatus

type ServerStatus struct {
	// 运行时间
	Uptime time.Duration

	// 请求数
	RequestCount int

	// 活跃请求数
	ActiveRequests int

	// 错误数
	ErrorCount int
}

ServerStatus 服务器状态

type WatchStats

type WatchStats struct {
	// 监视的目录数量
	DirCount int

	// 最近的变更
	RecentChanges []FileChange

	// 最后重载时间
	LastReload time.Time
}

WatchStats 监视器统计

Jump to

Keyboard shortcuts

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