3000 explained code solutions for 75 technologies


golangHow to get client IP from HTTP server


package main
import ( "fmt"; "net/http"; "strings" )

func ip(w http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(w, strings.Split(req.RemoteAddr, ":")[0])
}

func main() {
  http.HandleFunc("/ip", ip)
  http.ListenAndServe(":8222", nil)
}ctrl + c
package main

default package declaration

func main() {

declare main function that will be launched automatically

net/http

http package to work with http protocol

strings.Split(req.RemoteAddr, ":")

extract IP from client IP:PORT string

"/ip", ip

handle /ip request with ip() function

http.ListenAndServe

launch HTTP server

8222

port to listen HTTP server on


Usage example

package main
import ( "fmt"; "net/http"; "strings" )

func ip(w http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(w, strings.Split(req.RemoteAddr, ":")[0])
}

func main() {
  http.HandleFunc("/ip", ip)
  http.ListenAndServe(":8222", nil)
}
output
# returns [ip] on "localhost:8222/hi" request