Hugo集成大善人Cloudflare+D1网页访客统计服务
本文主要是采用开源项目analytics_with_cloudflare 。 analytics_with_cloudflare服务部署 下载项目文件 git clone https://github.com/yestool/analytics_with_cloudflare 安装依赖 cd analytics_with_cloudflare npm install -g wrangler npm install hono 登录 跳转cloudflare网页授权 npx wrangler login 创建D1数据库:[web_analytics] 数据库名称为web_analytics,与package.json内保持一致 npx wrangler d1 create web_analytics 成功后显示: ✅ Successfully created DB web_analytics [[d1_databases]] binding = "DB" # available in your Worker on env.DB database_name = "web_analytics" database_id = "<unique-ID-for-your-database>" 配置worker和D1数据库绑定 将上个步骤返回的unique-ID-for-your-database写进wrangler.toml中 name = "analytics_with_cloudflare" main = "src/index.ts" compatibility_date = "2024-06-14" [[d1_databases]] binding = "DB" # available in your Worker on env.DB database_name = "web_analytics" database_id = "<unique-ID-for-your-database>" 初始化D1数据库的表结构 npm run initSql 修改src/index.ts 内容 const body = await c.req.json() const hostname = body.hostname const url_path = body.url const referrer = body.referrer const pv = body.pv const uv = body.uv // 添加以下两行 const spv = body.spv const suv = body.suv // 中间代码忽略 // 修改下面代码内容 const resData:{pv?: number, uv?: number, spv?: number, suv?: number} = {} // 中间代码忽略 if (uv){ const total = await c.env.DB.prepare('SELECT COUNT(*) AS total from (select DISTINCT visitor_ip from t_web_visitor where website_id = ? and url_path = ?) t').bind(websiteId, url_path).first('total'); resData['uv'] = Number(total) } // 添加以下两段代码 if (spv){ const total = await c.env.DB.prepare('SELECT COUNT(*) AS total from t_web_visitor where website_id = ?').bind(websiteId).first('total'); resData['spv'] = Number(total) } if (suv){ const total = await c.env.DB.prepare('SELECT COUNT(*) AS total from (select DISTINCT visitor_ip from t_web_visitor where website_id = ?) t').bind(websiteId).first('total'); resData['suv'] = Number(total) } // 修改完成 完整代码内容,可以下载index.ts 原来的代码只支撑返回单个页面的访问数据,不支持返回整个网站的访问数据,增加spv和suv两个返回值,分别是全站访问人次和全站访问人数。 ...