V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wsseo
V2EX  ›  程序员

golang 中"r *http.Request"的实际参数是从哪来的

  •  
  •   wsseo · 2018-12-11 13:20:08 +08:00 · 2012 次点击
    这是一个创建于 1935 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main
    
    import (
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
            w.Write([]byte("hello world"))
        })
        http.ListenAndServe(":8000", nil)
    }
    

    作为 golang 初学者,不能理解"r *http.Request "为什么不需要实际参数,r 是存储在哪里的。 "w http.ResponseWriter"也不需要实际参数吗。这从语法上怎么理解?

    7 条回复    2018-12-11 17:49:04 +08:00
    liuxey
        1
    liuxey  
       2018-12-11 13:23:51 +08:00
    实际参数不是 r 吗?我觉得楼主基础知识有点缺,看不懂你的问题
    wsseo
        2
    wsseo  
    OP
       2018-12-11 13:30:38 +08:00
    @liuxey 我也觉得。我理解的是 r 是形式参数,函数不是一般需要传递实际参数吗?像这样调用的时候传递实参 func_b(r)
    xlui
        3
    xlui  
       2018-12-11 13:40:14 +08:00 via iPhone
    @wsseo 就跟 Java EE 中 servlet 的参数一样,实参是容器在调用处理方法时传进去的。具体到这个例子,匿名函数的实参是在请求 / 时 http 包内部在回调匿名函数时传进去的,实际应用中我们不需要关心。个人理解。
    liuxey
        4
    liuxey  
       2018-12-11 13:45:16 +08:00   ❤️ 1
    @wsseo #2 我大概懂你问的意思了,这些概念好久远

    http.HandleFunc 的形式参数有两个,pattern 和 handler,handler 是一个 func,签名就是 func(ResponseWriter, *Request),那么你代码里写的:

    func(w http.ResponseWriter, r *http.Request){
    w.Write([]byte("hello world"))
    }

    就是 handler 的实际参数,它的类型是 func,这里只是将这个 func 注册到默认的 defaultServeMux 中,具体传递实参是在运行中接受请求时调用的,不是通过 http.HandleFunc 调用,如果你开发过函数式类型的语言的话,这里应该很好理解。

    你可以花个一天时间看下 Golang http 的实现,源码很简单的(如何你想彻底搞懂 http 模块的话)
    AzadCypress
        5
    AzadCypress  
       2018-12-11 13:49:12 +08:00
    func main() {
    http.HandleFunc("/", func_b)
    http.ListenAndServe(":8000", nil)
    }
    func func_b(w http.ResponseWriter, r *http.Request){
    w.Write([]byte("hello world"))
    }
    写成这样应该能看明白,参数哪里来的你得去看 http.HandleFunc 的实现
    wsseo
        6
    wsseo  
    OP
       2018-12-11 14:04:48 +08:00
    @liuxey 大概知道什么意思了
    tiedan
        7
    tiedan  
       2018-12-11 17:49:04 +08:00
    参数在 HandleFunc 里面传进去的啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2874 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:48 · PVG 21:48 · LAX 06:48 · JFK 09:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.