liwanglin/main.go

52 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-05-11 17:15:31 +08:00
package main
import (
"flag"
"fmt"
2024-05-13 11:31:02 +08:00
"net"
2024-05-11 17:15:31 +08:00
"net/http"
2024-05-13 11:31:02 +08:00
"strings"
2024-05-11 17:15:31 +08:00
)
func main() {
var host string
var port int
2024-05-13 11:31:02 +08:00
flag.StringVar(&host, "h", GetIp(), "IP地址")
2024-05-17 11:32:31 +08:00
flag.IntVar(&port, "p", 12564, "端口")
2024-05-11 17:15:31 +08:00
flag.Parse()
2024-05-17 11:32:31 +08:00
fmt.Println(host)
2024-05-11 17:15:31 +08:00
address := fmt.Sprintf("%s:%d", host, port)
http.HandleFunc("/ping", func(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprintln(writer, fmt.Sprintf("%s by %s", "pong", address))
})
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprintln(writer, fmt.Sprintf("%s by %s", "hello world", address))
})
err := http.ListenAndServe(address, nil)
if nil != err {
panic(err)
}
}
2024-05-13 11:31:02 +08:00
func GetIp() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "127.0.0.1"
}
retIp := ""
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip := ipnet.IP.String()
if strings.HasPrefix(ip, "172.") {
retIp = ip
break
}
}
}
}
return retIp
}