feat: add public IP detection for VPS/NAS deployment

- Add getPublicIP() via api.ipify.org with configurable timeout
- Startup log now shows both local and public access URLs
- Graceful fallback: skip public IP if network unreachable
- Update README with dual-IP log example for both CN/EN
This commit is contained in:
ShukeBta
2026-05-17 00:19:38 +08:00
parent dd8f2a466c
commit 158fffaba0
3 changed files with 40 additions and 6 deletions
+30 -4
View File
@@ -89,10 +89,19 @@ func main() {
go func() {
localIP := getLocalIP()
logger.Info("server is ready",
zap.String("local", fmt.Sprintf("http://%s:%d", localIP, cfg.App.Port)),
zap.String("listen", srv.Addr),
)
publicIP := getPublicIP(3 * time.Second)
if publicIP != "" {
logger.Info("server is ready",
zap.String("local", fmt.Sprintf("http://%s:%d", localIP, cfg.App.Port)),
zap.String("public", fmt.Sprintf("http://%s:%d", publicIP, cfg.App.Port)),
zap.String("listen", srv.Addr),
)
} else {
logger.Info("server is ready",
zap.String("local", fmt.Sprintf("http://%s:%d", localIP, cfg.App.Port)),
zap.String("listen", srv.Addr),
)
}
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatal("listen failed", zap.Error(err))
}
@@ -180,3 +189,20 @@ func getLocalIP() string {
}
return "localhost"
}
// getPublicIP tries to detect the public-facing IP by querying ipify.org.
// Returns empty string if detection fails (e.g. no internet, timeout).
func getPublicIP(timeout time.Duration) string {
client := &http.Client{Timeout: timeout}
resp, err := client.Get("https://api.ipify.org")
if err != nil {
return ""
}
defer resp.Body.Close()
buf := make([]byte, 64)
n, err := resp.Body.Read(buf)
if err != nil || n == 0 || resp.StatusCode != http.StatusOK {
return ""
}
return string(buf[:n])
}