Go html template how to get user IP in function from funcMap -


i know how user ip *http.requeststruct:

strings.split(r.remoteaddr, ":")[0] 

and know how define template.funcmap:

funcmap = template.funcmap{                                                                    // gets time since post posted                                             "since": func(t time.time) string {                                                            s := time.since(t).string()                                                            return strings.replace(s[:strings.lastindex(s, "m")+1], "h", "h ", 1)          },                                                                             }                                                                                      

how users ip template function defined in template.funcmap?

the func map intended helper functions, rather data, , should defined once before parsing templates, isn't place it. should instead pass in data view when executing template.

this fit better in data/context view. example if use map[string]interface{} (one of few places i'd use interface{}), can assign there:

userip := strings.split(r.remoteaddr, ":")[0] data := map[string]interface{}{"userip":userip} err := tmpl.execute(w,data) 

template:

<p>user ip:{{.userip}}</p> 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -