package cmd import ( "fmt" "log" "net" "net/http" "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 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) { 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 } } r.Header.Add("X-Myip", ip) fmt.Fprint(w, ip+"\n") }) err := http.ListenAndServe(addr+":"+port, simpleLogger(http.DefaultServeMux)) if err != nil { log.Println(err) return err } return nil } func simpleLogger(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // for name, values := range r.Header { // // Loop over all values for the name. // for _, value := range values { // fmt.Println(name, value) // } // } user := r.URL.Query().Get("name") if user == "" { user = r.URL.String() } log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, user, r.Header.Get("User-Agent")) handler.ServeHTTP(w, r) }) }