dpv46227 2017-08-21 01:48
浏览 157

Go HTML模板如何从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条回答 默认 最新

  • dpcyx08288 2017-08-21 06:53
    关注

    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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据