first commit

pull/5/head
Evan Chen 2021-10-15 16:17:56 +08:00
commit 87ad47e371
6 changed files with 116 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
bin

11
Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM golang:1.17.2-alpine3.14 as builder
WORKDIR /src
COPY . .
RUN go build -o /go/bin/myip main.go
FROM alpine:3.14
EXPOSE 5080
COPY --from=builder /go/bin/myip /go/bin/myip
ENTRYPOINT ["/go/bin/myip"]

2
Makefile Normal file
View File

@ -0,0 +1,2 @@
build:
go build -o bin/myip

17
README.md Normal file
View File

@ -0,0 +1,17 @@
# Myip
a tool that can get your public ip
```shell
Usage of myip:
-b string
the address the server binds on (default "0.0.0.0")
-p string
port to listen|connect (default "5080")
-s run in server mode
-u string
hostname to ask for (default "kumoly.io")
```
env: `MYIP_PORT`, `MYIP_HOST`

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module kumoly.io/tools/myip
go 1.17

82
main.go Normal file
View File

@ -0,0 +1,82 @@
package main
import (
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
)
var (
serverMode bool
addr string
port string
envP string
host string
envHost string
)
func init() {
envP = os.Getenv("MYIP_PORT")
envHost = os.Getenv("MYIP_HOST")
flag.BoolVar(&serverMode, "s", false, "run in server mode")
flag.StringVar(&host, "u", "kumoly.io", "hostname to ask for")
flag.StringVar(&port, "p", "5080", "port to listen|connect")
flag.StringVar(&addr, "b", "0.0.0.0", "the address the server binds on")
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: myip [options]\n")
flag.PrintDefaults()
}
func main() {
flag.Parse()
if envP != "" {
port = envP
}
if envHost != "" {
host = envHost
}
if serverMode {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("X-Real-Ip")
if ip == "" {
ip = r.Header.Get("X-Forwarded-For")
}
if ip == "" {
var err error
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
}
fmt.Fprint(w, ip+"\n")
})
err := http.ListenAndServe(addr+":"+port, nil)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
} else {
res, err := http.Get("http://" + host + ":" + port)
if err != nil {
fmt.Println(err)
os.Exit(2)
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
os.Exit(3)
}
fmt.Println(strings.TrimRight(string(body), "\r\n"))
}
}