myip/cmd/server.go

62 lines
1.2 KiB
Go
Raw Normal View History

2021-10-15 16:58:49 +00:00
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
}
}
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) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}