跳到主要内容

框架集成指南

🎯 概述

Anima 提供了针对主流 Web 框架的 SDK 和插件,让你无需手动管理隧道,只需在项目中安装对应的包,启动开发服务器时自动创建隧道。

核心优势:

  • ✅ 零配置,开箱即用
  • ✅ 开发服务器启动时自动创建隧道
  • ✅ 进程退出时自动清理
  • ✅ 支持热重载
  • ✅ 团队成员即装即用

🚀 Node.js 生态

Express.js

安装

npm install @anima/express

使用

const express = require('express');
const anima = require('@anima/express');

const app = express();

// 开发环境自动启用隧道
if (process.env.NODE_ENV === 'development') {
app.use(anima({
token: process.env.ANIMA_TOKEN,
subdomain: 'myapp', // 可选:自定义子域名
autoStart: true,
onReady: (url) => {
console.log(`🌐 公网地址: ${url}`);
}
}));
}

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});

运行

ANIMA_TOKEN=your-token npm start

# 输出:
# Server started on http://localhost:3000
# 🌐 公网地址: https://myapp.anima4.cn

Next.js

安装

npm install @anima/next

配置

// next.config.js
const { withAnima } = require('@anima/next');

/** @type {import('next').NextConfig} */
const nextConfig = {
// 你的配置
};

module.exports = withAnima(nextConfig, {
enabled: process.env.NODE_ENV === 'development',
token: process.env.ANIMA_TOKEN,
subdomain: 'my-nextjs-app',
});

环境变量

# .env.local
ANIMA_TOKEN=your-token-here

运行

npm run dev

# 输出:
# ✓ Ready on http://localhost:3000
# 🚀 Anima 隧道已就绪
# 🌐 公网地址: https://my-nextjs-app.anima4.cn
# 📋 已复制到剪贴板

Vite + React/Vue

安装

npm install @anima/vite-plugin

配置

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import anima from '@anima/vite-plugin';

export default defineConfig({
plugins: [
react(),
anima({
token: process.env.VITE_ANIMA_TOKEN,
subdomain: 'my-vite-app',
openBrowser: true, // 自动打开浏览器
copyToClipboard: true, // 自动复制链接
})
]
});

运行

VITE_ANIMA_TOKEN=your-token npm run dev

Koa.js

安装

npm install @anima/koa

使用

const Koa = require('koa');
const anima = require('@anima/koa');

const app = new Koa();

// 中间件方式
if (process.env.NODE_ENV === 'development') {
app.use(anima({
token: process.env.ANIMA_TOKEN,
subdomain: 'my-koa-app',
}));
}

app.use(async ctx => {
ctx.body = 'Hello Koa';
});

app.listen(3000);

NestJS

安装

npm install @anima/nestjs

配置

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AnimaTunnel } from '@anima/nestjs';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

// 开发环境启用隧道
if (process.env.NODE_ENV === 'development') {
const tunnel = new AnimaTunnel({
token: process.env.ANIMA_TOKEN,
subdomain: 'my-nest-app',
});

await tunnel.start(3000);
}

await app.listen(3000);
}
bootstrap();

🐍 Python 生态

Flask

安装

pip install anima-flask

使用

from flask import Flask
from anima import AnimaTunnel
import os

app = Flask(__name__)

@app.route('/')
def hello():
return 'Hello Flask!'

if __name__ == '__main__':
# 开发环境自动启用隧道
if os.getenv('FLASK_ENV') == 'development':
with AnimaTunnel(
token=os.getenv('ANIMA_TOKEN'),
subdomain='my-flask-app'
) as tunnel:
print(f'🌐 公网地址: {tunnel.url}')
app.run(debug=True)
else:
app.run()

运行

FLASK_ENV=development ANIMA_TOKEN=your-token python app.py

# 输出:
# * Running on http://127.0.0.1:5000
# 🌐 公网地址: https://my-flask-app.anima4.cn

Django

安装

pip install anima-django

配置

# settings.py

# 开发环境配置
if DEBUG:
INSTALLED_APPS += ['anima_django']

ANIMA_CONFIG = {
'token': os.getenv('ANIMA_TOKEN'),
'subdomain': 'my-django-app',
'auto_start': True,
}

中间件(可选)

# settings.py
MIDDLEWARE = [
'anima_django.middleware.AnimaTunnelMiddleware',
# ... 其他中间件
]

运行

ANIMA_TOKEN=your-token python manage.py runserver

# 输出:
# Starting development server at http://127.0.0.1:8000/
# 🚀 Anima 隧道已启动
# 🌐 公网地址: https://my-django-app.anima4.cn

FastAPI

安装

pip install anima-fastapi

使用

from fastapi import FastAPI
from anima import AnimaTunnel
import os
import uvicorn

app = FastAPI()

@app.get("/")
def read_root():
return {"message": "Hello FastAPI"}

if __name__ == "__main__":
# 开发模式启用隧道
if os.getenv('ENV') == 'development':
tunnel = AnimaTunnel(
token=os.getenv('ANIMA_TOKEN'),
subdomain='my-fastapi-app'
)

with tunnel:
print(f'🌐 公网地址: {tunnel.url}')
uvicorn.run(app, host="0.0.0.0", port=8000)
else:
uvicorn.run(app, host="0.0.0.0", port=8000)

🐘 PHP 生态

Laravel

安装

composer require anima/laravel

配置

// config/anima.php
return [
'enabled' => env('ANIMA_ENABLED', env('APP_ENV') === 'local'),
'token' => env('ANIMA_TOKEN'),
'subdomain' => env('ANIMA_SUBDOMAIN', 'my-laravel-app'),
'auto_start' => true,
];

环境变量

# .env
ANIMA_ENABLED=true
ANIMA_TOKEN=your-token-here
ANIMA_SUBDOMAIN=my-laravel-app

运行

php artisan serve

# 输出:
# Laravel development server started: http://127.0.0.1:8000
# 🚀 Anima 隧道已启动
# 🌐 公网地址: https://my-laravel-app.anima4.cn

Symfony

安装

composer require anima/symfony-bundle

配置

# config/packages/anima.yaml
anima:
enabled: '%kernel.debug%'
token: '%env(ANIMA_TOKEN)%'
subdomain: 'my-symfony-app'

🎮 Go 生态

Gin

安装

go get github.com/anima/gin-tunnel

使用

package main

import (
"os"
"github.com/gin-gonic/gin"
anima "github.com/anima/gin-tunnel"
)

func main() {
r := gin.Default()

// 开发环境启用隧道
if gin.Mode() == gin.DebugMode {
tunnel := anima.New(&anima.Config{
Token: os.Getenv("ANIMA_TOKEN"),
Subdomain: "my-gin-app",
})

if err := tunnel.Start(); err != nil {
panic(err)
}
defer tunnel.Close()

println("🌐 公网地址:", tunnel.URL())
}

r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello Gin",
})
})

r.Run(":8080")
}

Echo

安装

go get github.com/anima/echo-tunnel

使用

package main

import (
"os"
"github.com/labstack/echo/v4"
anima "github.com/anima/echo-tunnel"
)

func main() {
e := echo.New()

// 中间件方式
if os.Getenv("ENV") == "development" {
e.Use(anima.Middleware(&anima.Config{
Token: os.Getenv("ANIMA_TOKEN"),
Subdomain: "my-echo-app",
}))
}

e.GET("/", func(c echo.Context) error {
return c.String(200, "Hello Echo")
})

e.Start(":8080")
}

💎 Ruby 生态

Rails

安装

# Gemfile
gem 'anima-rails'
bundle install

配置

# config/environments/development.rb
Rails.application.configure do
# 启用 Anima 隧道
config.middleware.use Anima::Tunnel,
token: ENV['ANIMA_TOKEN'],
subdomain: 'my-rails-app'
end

运行

ANIMA_TOKEN=your-token rails server

# 输出:
# => Booting Puma
# => Rails 7.0.0 application starting in development
# 🚀 Anima 隧道已启动
# 🌐 公网地址: https://my-rails-app.anima4.cn
# => Run `rails server --help` for more startup options

Sinatra

安装

gem install anima-sinatra

使用

require 'sinatra'
require 'anima'

# 开发环境启用隧道
if development?
use Anima::Tunnel,
token: ENV['ANIMA_TOKEN'],
subdomain: 'my-sinatra-app'
end

get '/' do
'Hello Sinatra!'
end

⚙️ 高级配置

完整配置选项

// Node.js 示例
anima({
// === 必需配置 ===
token: process.env.ANIMA_TOKEN, // API Token

// === 隧道配置 ===
subdomain: 'myapp', // 自定义子域名
region: 'cn-shanghai', // 服务器区域
protocol: 'http', // http 或 tcp

// === 功能开关 ===
enabled: true, // 是否启用
autoStart: true, // 自动启动
openBrowser: true, // 自动打开浏览器
copyToClipboard: true, // 复制链接到剪贴板

// === 安全配置 ===
allowedIPs: ['192.168.1.0/24'], // IP 白名单
password: 'secret', // 访问密码

// === 团队协作 ===
shareWith: ['team@example.com'], // 分享给团队成员
maxConnections: 10, // 最大连接数

// === 调试选项 ===
logLevel: 'info', // 日志级别
requestLogger: true, // 启用请求日志

// === 回调函数 ===
onReady: (url) => {
console.log(`隧道就绪: ${url}`);
},
onError: (error) => {
console.error(`隧道错误: ${error}`);
},
onClose: () => {
console.log('隧道已关闭');
},
onRequest: (req) => {
console.log(`请求: ${req.method} ${req.path}`);
}
});

🔒 安全最佳实践

1. 环境隔离

// ✅ 推荐:只在开发环境启用
if (process.env.NODE_ENV === 'development') {
app.use(anima({ /* ... */ }));
}

// ❌ 危险:不要在生产环境启用
app.use(anima({ /* ... */ }));

2. Token 安全

# ✅ 使用环境变量
ANIMA_TOKEN=your-token

# ✅ 使用 .env 文件(并加入 .gitignore)
echo "ANIMA_TOKEN=your-token" >> .env.local
echo ".env.local" >> .gitignore

# ❌ 不要硬编码在代码中
token: 'hardcoded-token-123' // 危险!

3. 访问控制

anima({
token: process.env.ANIMA_TOKEN,

// IP 白名单
allowedIPs: [
'192.168.1.0/24', // 公司内网
'10.0.0.0/8', // VPN 网段
],

// 访问密码
password: process.env.ANIMA_PASSWORD,

// 限制连接数
maxConnections: 5,
})

🎨 开发体验增强

自动打开浏览器

anima({
openBrowser: true, // 隧道就绪后自动打开浏览器
openBrowserPath: '/admin', // 指定打开的路径
})

生成二维码(手机测试)

anima({
showQRCode: true, // 在终端显示二维码
})

输出:

🌐 公网地址: https://myapp.anima4.cn
📱 扫描二维码在手机上测试:

█████████████████████████
██ ▄▄▄▄▄ █▀ █▀▄█ ▄▄▄▄▄ ██
██ █ █ █▀ ▀ ▄█ █ █ ██
██ █▄▄▄█ █▄▀█▀▄█ █▄▄▄█ ██
...

Webhook 调试面板

anima({
webhookPanel: true, // 启用 Webhook 调试面板
})

访问 https://myapp.anima4.cn/_anima/webhooks 查看所有请求。


🤝 团队协作

分享隧道

anima({
token: process.env.ANIMA_TOKEN,
shareWith: [
'designer@company.com',
'client@example.com'
],
// 他们会收到邮件通知,包含访问链接
})

临时访客链接

anima({
guestAccess: true,
guestExpiry: '24h', // 24小时后失效
})

📊 监控和日志

请求日志

anima({
requestLogger: true,
logFormat: 'combined', // 'combined', 'common', 'dev', 'short', 'tiny'
})

性能监控

anima({
metrics: true, // 启用性能指标收集
metricsEndpoint: '/_anima/metrics',
})

访问 https://myapp.anima4.cn/_anima/metrics 查看性能数据。


🆘 故障排查

常见问题

1. 隧道无法启动

# 检查 Token 是否正确
echo $ANIMA_TOKEN

# 检查网络连接
curl https://api.anima4.cn/health

# 查看详细日志
DEBUG=anima:* npm start

2. 子域名已被占用

// 使用随机子域名
anima({
subdomain: null, // 自动生成随机子域名
})

// 或添加后缀
anima({
subdomain: 'myapp-' + Date.now(),
})

3. 连接频繁断开

anima({
reconnect: true, // 启用自动重连
reconnectInterval: 5000, // 重连间隔(毫秒)
maxReconnects: 10, // 最大重连次数
})

🔗 相关链接


💬 反馈和建议

如果你使用的框架还没有 SDK 支持,欢迎:

我们正在持续增加更多框架的支持!🚀