liwanglin/main.go

52 lines
1.1 KiB
Go

package main
import (
"flag"
"fmt"
"net"
"net/http"
"strings"
)
func main() {
var host string
var port int
flag.StringVar(&host, "h", GetIp(), "IP地址")
flag.IntVar(&port, "p", 12564, "端口")
flag.Parse()
fmt.Println(host)
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)
}
}
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
}