aqi

package module
v1.6.0 Latest Latest
Warning

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

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

README

Aqi

Aqi is a Golang Websocket business framework that supports net/http, gin, chi, etc. It integrates underlying third-party libraries such as viper, gorm, gobwa/ws, gjson, zap, asynq, which facilitates the rapid development of Websocket applications.

Installation

go get -u github.com/wonli/aqi

简体中文

Usage

On the first run, a config-dev.yaml configuration file will be automatically generated in the working directory. You can configure the application start port, database, and other settings.

After the service starts, use wscat to establish a websocket connection with the server. Here is a screenshot of the operation.

img

Interaction Protocol

Input and output uniformly use JSON. Here, Action is the name registered in the routing, and Params are in JSON string format.


type Context struct {
	...
	Action   string
	Params   string
	...
}

Response Format:

type Action struct {
	Action string `json:"action"`

	Code int    `json:"code"`
	Msg  string `json:"msg,omitempty"`
	Data any    `json:"data,omitempty"`
}
Quick Start

In ahi.Init, specify the configuration file via aqi.ConfigFile, which defaults to yaml format. The service name and port are specified in the yaml file path through aqi.HttpServer. The contents of the entry file are as follows:

package main

import (
	"net/http"
	"time"

	"github.com/wonli/aqi"
	"github.com/wonli/aqi/ws"
)

func main() {
	app := aqi.Init(
		aqi.ConfigFile("config.yaml"),
		aqi.HttpServer("Aqi", "port"),
	)

	// Create router
	mux := http.NewServeMux()
	// WebSocket Handler
	mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		ws.HttpHandler(w, r)
	})

	// Register router
	wsr := ws.NewRouter()
	wsr.Add("hi", func(a *ws.Context) {
		a.Send(ws.H{
			"hi": time.Now(),
		})
	})

	app.WithHttpServer(mux)

	// 启动应用
	app.Start()
}
With Gin

aqi can be very conveniently integrated with other WEB frameworks. You just need to correctly register handler and app.WithHttpServer. It supports any implementation of http.Handler.

package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"github.com/wonli/aqi"
	"github.com/wonli/aqi/ws"
)

func main() {
	app := aqi.Init(
		aqi.ConfigFile("config.yaml"),
		aqi.HttpServer("Aqi", "port"),
	)

	engine := gin.Default()
	// Handler
	engine.GET("/ws", func(c *gin.Context) {
		ws.HttpHandler(c.Writer, c.Request)
	})

	// Router
	wsr := ws.NewRouter()
	wsr.Add("hi", func(a *ws.Context) {
		a.Send(ws.H{
			"hi": time.Now(),
		})
	})

	app.WithHttpServer(engine)
	app.Start()
}
Middlewares

First, define a simple logging middleware that prints the received action before processing the request and prints the response content after processing.

func logMiddleware() func(a *ws.Context) {
	return func(a *ws.Context) {
		log.Printf("Request action: %s ", a.Action)
		a.Next()
		log.Printf("Reqponse data: %s ", a.Response.Data)
	}
}

Register the middleware to the router using the Use method.

// 注册WebSocket路由
wsr := ws.NewRouter()
wsr.Use(logMiddleware()).Add("hi", func(a *ws.Context) {
    a.Send(ws.H{
        "hi": time.Now(),
    })
})

You can also use the form of router groups.

// Router
wsr := ws.NewRouter()
r1 := wsr.Use(logMiddleware())
{
    r1.Add("hi", func(a *ws.Context) {
        a.Send(ws.H{
            "hi": time.Now(),
        })
    })

    r1.Add("say", func(a *ws.Context) {
        a.Send(ws.H{
            "say": "hi",
        })
    })
}

This way, the console will print logs before and after each request.

Production Mode

Compiling Aqi directly will run in dev mode. To run in production mode, pass the following parameters during compilation. For more details, please refer to the examples/Makefile file.

LDFLAGS = "-X '$(FLAGS_PKG).BuildDate=$(BUILD_DATE)' \
		   -X '$(FLAGS_PKG).Branch=$(GIT_BRANCH)' \
		   -X '$(FLAGS_PKG).CommitVersion=$(GIT_COMMIT)' \
		   -X '$(FLAGS_PKG).Revision=$(GIT_REVISION)' \
		   -extldflags '-static -s -w'"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Branch        string
	Revision      string
	BuildDate     string
	CommitVersion string
)

Functions

func AsciiLogo(serverName ...string)

Types

type AppConfig

type AppConfig struct {

	//运行时数据存储基础路径
	DataPath string

	//应用日志文件配置路径
	LogPathKey string

	//默认语言
	Language string

	//服务名称,support.Version
	//当指定 HttpServerPortFindPath 时,在配置读取之后从配置路径获取http端口
	Servername             []string
	ServerPort             string
	HttpServerPortFindPath string

	ConfigType string //配置文件类型
	ConfigPath string //配置文件路径
	ConfigName string //配置文件名称

	Configs map[string]any

	Guard      ws.GuardFunc //守护回调
	HttpServer http.Handler //http server

	RemoteProvider *RemoteProvider //远程配置支持etcd, consul

	WatchHandler func()
	// contains filtered or unexported fields
}

func Init

func Init(options ...Option) *AppConfig

func (*AppConfig) GetDataPath

func (a *AppConfig) GetDataPath(dir string) string

func (*AppConfig) IsDevMode

func (a *AppConfig) IsDevMode() bool

func (*AppConfig) Start

func (a *AppConfig) Start()

func (*AppConfig) WithHttpServer

func (a *AppConfig) WithHttpServer(svr http.Handler)

func (*AppConfig) WriteDefaultConfig

func (a *AppConfig) WriteDefaultConfig() error

type Aqi

type Aqi struct {
	AppConfig *AppConfig
}

func Use

func Use() *Aqi

type Option

type Option func(config *AppConfig) error

func ConfigFile

func ConfigFile(file string) Option

func DataPath

func DataPath(path string) Option

func Guard added in v1.5.0

func Guard(fn ws.GuardFunc) Option

func HttpServer

func HttpServer(name, portFindPath string) Option

func Language

func Language(lng string) Option

func LogConfig

func LogConfig(configKeyPath string) Option

func Server

func Server(name ...string) Option

func WatchHandler

func WatchHandler(handler func()) Option

type Provider

type Provider string
const ProviderConsul Provider = "consul"
const ProviderEtcd Provider = "etcd"

type RemoteProvider

type RemoteProvider struct {
	Name     Provider //服务商名称
	Path     string   //路径
	Endpoint string   //服务器地址
	Type     string   //json, yaml等
}

func ParseRemoteProvider

func ParseRemoteProvider(s string) *RemoteProvider

ParseRemoteProvider 格式 provider[s]://endpoint/path.type 例:consul://localhost:8500/a.yaml 表示远程配置中心为consul,服务器地址为http://localhost:8500, path为a, 配置类型是yaml scheme加s表示服务器支持ssl

Directories

Path Synopsis
cmd
aqi command
internal
cli
bytefmt
Package bytefmt contains helper methods and constants for converting to and from a human-readable byte format.
Package bytefmt contains helper methods and constants for converting to and from a human-readable byte format.
geo
ip
pem
rmb

Jump to

Keyboard shortcuts

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