工具说明:在进行内网穿透(如调试 mole-go)或配置服务器白名单时,频繁查询公网 IP 是刚需。为了告别繁琐的登录和搜索,我开发了这个集成在博客中的实时探测组件。

🌐 公网 IP 探测

🌐 当前公网 IP: 正在探测...

🛠️ 核心实现逻辑

这个工具基于 Hugo 的 Shortcode 功能实现,采用了异步加载技术,确保不会影响页面的首屏渲染速度。

1. 结构设计

利用 HTML5 的 fetch API 调用轻量级的 IP 接口,并结合 navigator.clipboard 实现一键复制。

2. 代码实现

layouts/shortcodes/myip.html 中存入以下代码:

<!-- 样式与布局 -->
<div style="background: var(--code-bg); border: 1px solid var(--border); border-radius: 8px; padding: 15px; display: flex; align-items: center; justify-content: space-between;">
    <div style="display: flex; align-items: center; gap: 10px;">
        <svg xmlns="http://www.w3.org" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>
        <span style="font-weight: bold; color: var(--primary);">我的公网 IP:</span>
        <code id="ip-display" style="font-size: 1.1em; background: none; padding: 0;">正在探测...</code>
    </div>
    <button id="copy-btn" onclick="copyIP()" style="background: var(--primary); color: #fff; border: none; border-radius: 4px; padding: 4px 10px; cursor: pointer; font-size: 12px; display: none;">复制</button>
</div>

<script>
    // 逻辑部分详见项目源码...
    function fetchIP() {
        // 使用 ipify API 获取 IP
        fetch('https://api.ipify.org')
            .then(response => response.json())
            .then(data => {
                const ipSpan = document.getElementById('ip-display');
                ipSpan.innerText = data.ip;
                document.getElementById('copy-btn').style.display = 'inline-block';
            })
            .catch(() => {
                document.getElementById('ip-display').innerText = '获取失败,请检查网络';
            });
    }

    function copyIP() {
        const ip = document.getElementById('ip-display').innerText;
        navigator.clipboard.writeText(ip).then(() => {
            const btn = document.getElementById('copy-btn');
            const originalText = btn.innerText;
            btn.innerText = '已复制!';
            setTimeout(() => { btn.innerText = originalText; }, 2000);
        });
    }

    // 页面加载完成后立即执行
    document.addEventListener('DOMContentLoaded', fetchIP);
</script>

💡 为什么选 Shortcode?

  • 零依赖:不需要复杂的后端环境,完全前端实现。
  • 高复用:除了 About 页面和专门的文章,未来在任何技术教程中只需一行
    {{< myip >}}即可调用。
  • SEO 友好:文章不仅自用,还能通过搜索“Hugo IP查询插件”为本站引流。

🚀 这样做的好处:

  1. 自留地工具化:把“实验室”的一部分功能静态化了。即使不登录,只要访问这篇文章(甚至你可以把它通过 hugo.toml 的菜单直接链接到“IP查询”),就能立刻用到工具。
  2. 置顶方便:通过 weight: 1 或在 Front Matter 中设置 pinned: true(取决于主题)