2021-10-15 16:58:49 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
2021-10-16 14:50:46 +00:00
|
|
|
"time"
|
2021-10-15 16:58:49 +00:00
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
var ServerCmd = &cobra.Command{
|
|
|
|
Use: "serve",
|
|
|
|
Short: "Simple server that returns the resolved IP.",
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
StartServer()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
// declared in client
|
|
|
|
// port string
|
2021-10-16 16:52:31 +00:00
|
|
|
|
2021-10-15 16:58:49 +00:00
|
|
|
addr string
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
ServerCmd.Flags().StringVarP(&port, "port", "p", "5080", "server port to listen")
|
|
|
|
ServerCmd.Flags().StringVarP(&addr, "address", "b", "0.0.0.0", "address the server binds on")
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartServer() error {
|
|
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
2021-10-16 14:50:46 +00:00
|
|
|
ip := GetIP(r)
|
2021-10-15 16:58:49 +00:00
|
|
|
fmt.Fprint(w, ip+"\n")
|
2021-10-16 14:50:46 +00:00
|
|
|
|
|
|
|
// logging
|
|
|
|
user := r.URL.Query().Get("name")
|
|
|
|
if user == "" {
|
|
|
|
user = r.URL.String()
|
|
|
|
}
|
|
|
|
host, _, _ := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
log.Printf("%s %s %s %s %s\n", time.Now().Format("2006-01-02-15:04:05"), host, ip, user, r.Header.Get("User-Agent"))
|
2021-10-15 16:58:49 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
err := http.ListenAndServe(addr+":"+port, simpleLogger(http.DefaultServeMux))
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-16 14:50:46 +00:00
|
|
|
func GetIP(r *http.Request) string {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
2021-10-15 16:58:49 +00:00
|
|
|
func simpleLogger(handler http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-10-15 19:15:49 +00:00
|
|
|
|
|
|
|
// for name, values := range r.Header {
|
|
|
|
// // Loop over all values for the name.
|
|
|
|
// for _, value := range values {
|
|
|
|
// fmt.Println(name, value)
|
|
|
|
// }
|
|
|
|
// }
|
2021-10-16 14:50:46 +00:00
|
|
|
// log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, r.URL, r.Header.Get("User-Agent"))
|
2021-10-15 16:58:49 +00:00
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|