You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
what-is-my-ip/what-is-my-ip.go

32 lines
660 B
Go

package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
)
func main() {
http.HandleFunc("/", getIP)
fmt.Println("listening on port 3000")
http.ListenAndServe(":3000", nil)
}
func getIP(w http.ResponseWriter, req *http.Request) {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
handleError(w, err, "Could not get IP address from request")
return
}
io.WriteString(w, ip+"\n")
log.Printf("Give response IP %s\n", ip)
}
func handleError(resp http.ResponseWriter, err error, message string) {
resp.WriteHeader(http.StatusBadRequest)
io.WriteString(resp, message)
log.Printf("Error handling request: %s (%s)", message, err)
}