Go的HTML模板中,如何在funcMap函数中获取用户的IP地址?

huangapple go评论75阅读模式
英文:

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

问题

我知道如何从*http.Request结构中获取用户的IP:

strings.Split(r.RemoteAddr, ":")[0]

我也知道如何定义一个template.FuncMap

funcMap = template.FuncMap{
        // 获取帖子发布后的时间
        "since": func(t time.Time) string {
                s := time.Since(t).String()
                return strings.Replace(s[:strings.LastIndex(s, "m")+1], "h", "h ", 1)
        },
}

如何从在template.FuncMap中定义的模板函数中获取用户的IP?

英文:

I know how to get the user IP from the *http.Requeststruct:

strings.Split(r.RemoteAddr, ":")[0]

And I know how to define a template.FuncMap:

funcMap = template.FuncMap{                                                           
        // gets the time since the post was 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 would I get the users IP from a template function defined in the template.FuncMap?

答案1

得分: 2

func map是用于辅助函数的,而不是用于数据,应该在解析模板之前定义一次,所以这不是一个好的位置。相反,当执行模板时,应该将数据传递给视图。

这个功能更适合在视图的数据/上下文中。例如,如果你在那里使用map[string]interface{}(我会使用interface{}的少数几个地方之一),你可以简单地在那里分配它:

userIP := strings.Split(r.RemoteAddr, ":")[0]
data := map[string]interface{}{"userIP": userIP}
err := tmpl.Execute(w, data)

模板:

用户IP:{{.userIP}}

英文:

The func map is intended for helper functions, rather than data, and should be defined once before parsing templates, so this isn't a good place for it. You should instead pass in the data to the view when executing the template.

This would fit better in your data/context for the view. For example if you use a map[string]interface{} for that (one of the few places I'd use interface{}), you can simply assign it there:

userIP := strings.Split(r.RemoteAddr, ":")[0]
data := map[string]interface{}{"userIP":userIP}
err := tmpl.Execute(w,data)

Template:

<p>User IP:{{.userIP}}</p>

huangapple
  • 本文由 发表于 2017年8月21日 09:48:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/45788395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定