码迷,mamicode.com
首页 > 其他好文 > 详细

Golang 服务器返回公网地址

时间:2019-09-04 00:27:56      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:服务器   默认参数   help   string   ESS   print   ini   com   hand   

gitee地址: https://gitee.com/wang_li/ReturnOutIP

代码

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "os"
    "strings"
    "time"
)

var (
    h bool
    LitenAddr string
    ListenRoute string
)

func init() {
    flag.BoolVar(&h,"h",false,"This help")
    flag.StringVar(&LitenAddr,"ListenAddr","0.0.0.0:93","Set http server listen address")
    flag.StringVar(&ListenRoute,"ListenRoute","/4u6385IP","Set http server listen Route")
}

func OutIPAddress(w http.ResponseWriter, r *http.Request) {
    slice01 := strings.Split(r.RemoteAddr,":")
    log.Println(time.Now(),"-- 4u6385IP --",r)
    fmt.Fprintf(w,slice01[0])
}

func main() {
    flag.Parse()

    if h {
        flag.Usage()
        os.Exit(0)
    }

    if ! strings.HasPrefix(ListenRoute,"/") {
        ListenRoute = "/" + ListenRoute
    }

    http.HandleFunc(ListenRoute,OutIPAddress)

    log.Println("Server running on http://" + LitenAddr + ListenRoute)

    s := &http.Server{
        Addr:    LitenAddr,
        ReadTimeout:10*time.Second,
        WriteTimeout:10*time.Second,
        MaxHeaderBytes:1<<20,
    }
    log.Fatal(s.ListenAndServe())
}

 

打包为可执行文件

# go build -o ReturnOutIP

 

获取帮助

# ./ReturnOutIP -h
Usage of ./ReturnOutIP:
  -ListenAddr string
        Set http server listen address (default "0.0.0.0:93")
  -ListenRoute string
        Set http server listen Route (default "/4u6385IP")
  -h    This help
#

 

默认参数
默认运行监听的端口为: 0.0.0.0:93 监听的http路由为 /4u6385IP

# ./ReturnOutIP
2019/09/03 15:36:55 Server running on http://0.0.0.0:93/4u6385IP

 

指定监听的端口和路由

``` bash
# ./ReturnOutIP -ListenAddr "0.0.0.0:95" -ListenRoute /OutIP
2019/09/03 15:41:24 Server running on http://0.0.0.0:95/OutIP
```

 

客户端扩展: https://www.cnblogs.com/wang-li/p/11437310.html

 



Golang 服务器返回公网地址

标签:服务器   默认参数   help   string   ESS   print   ini   com   hand   

原文地址:https://www.cnblogs.com/wang-li/p/11453633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!