MCPcopy Index your code
hub / github.com/rdegges/ipify-api / GetIP

Function GetIP

api/get_ip.go:22–63  ·  view source on GitHub ↗

GetIP returns a user's public facing IP address (IPv4 OR IPv6). By default, it will return the IP address in plain text, but can also return data in both JSON and JSONP if requested to.

(w http.ResponseWriter, r *http.Request, _ httprouter.Params)

Source from the content-addressed store, hash-verified

20// By default, it will return the IP address in plain text, but can also return
21// data in both JSON and JSONP if requested to.
22func GetIP(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
23
24 err := r.ParseForm()
25 if err != nil {
26 panic(err)
27 }
28
29 // We'll always grab the first IP address in the X-Forwarded-For header
30 // list. We do this because this is always the *origin* IP address, which
31 // is the *true* IP of the user. For more information on this, see the
32 // Wikipedia page: https://en.wikipedia.org/wiki/X-Forwarded-For
33 ip := net.ParseIP(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]).String()
34
35 // If the user specifies a 'format' querystring, we'll try to return the
36 // user's IP address in the specified format.
37 if format, ok := r.Form["format"]; ok && len(format) > 0 {
38 jsonStr, _ := json.Marshal(models.IPAddress{ip})
39
40 switch format[0] {
41 case "json":
42 w.Header().Set("Content-Type", "application/json")
43 fmt.Fprintf(w, string(jsonStr))
44 return
45 case "jsonp":
46 // If the user specifies a 'callback' parameter, we'll use that as
47 // the name of our JSONP callback.
48 callback := "callback"
49 if val, ok := r.Form["callback"]; ok && len(val) > 0 {
50 callback = val[0]
51 }
52
53 w.Header().Set("Content-Type", "application/javascript")
54 fmt.Fprintf(w, callback+"("+string(jsonStr)+");")
55 return
56 }
57 }
58
59 // If no 'format' querystring was specified, we'll default to returning the
60 // IP in plain text.
61 w.Header().Set("Content-Type", "text/plain")
62 fmt.Fprintf(w, ip)
63}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected