返回
用Go实现获取公网IP的Web服务
后端
2023-09-04 05:12:42
正文
1. 创建一个新的Go项目
首先,创建一个新的Go项目。您可以使用以下命令:
mkdir my-ip-service
cd my-ip-service
go mod init myip
2. 创建一个main.go文件
接下来,创建一个名为main.go的文件。这是我们的程序的入口点。
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 获取公网IP地址
ip, err := getPublicIP()
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// 将IP地址转换为JSON格式
response, err := json.Marshal(ip)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// 将JSON数据写入响应
w.Header().Set("Content-Type", "application/json")
w.Write(response)
})
// 监听端口8080
log.Fatal(http.ListenAndServe(":8080", nil))
}
// 获取公网IP地址
func getPublicIP() (string, error) {
// 使用ifconfig命令获取公网IP地址
output, err := exec.Command("ifconfig").Output()
if err != nil {
return "", err
}
// 查找公网IP地址
ip := ""
for _, line := range strings.Split(string(output), "\n") {
if strings.Contains(line, "inet addr:") {
ip = strings.Split(line, ":")[1]
break
}
}
// 返回公网IP地址
return ip, nil
}
3. 运行Web服务
现在,您可以使用以下命令运行Web服务:
go run main.go
4. 测试Web服务
现在,您可以使用浏览器或curl来测试Web服务。
在浏览器中,您可以访问以下URL:
http://localhost:8080
在curl中,您可以使用以下命令:
curl http://localhost:8080
您应该会看到一个JSON响应,其中包含当前服务器的公网IP地址。
{
"ip": "127.0.0.1"
}
5. 部署Web服务
现在,您可以将Web服务部署到生产环境。您可以使用以下命令将Web服务打包成可执行文件:
go build -o my-ip-service
然后,您可以将可执行文件复制到生产环境并运行它。
总结
现在,您已经知道如何使用Go编写一个简单的Web服务,该服务可以返回当前服务器的公网IP地址。