• 请不要在回答技术问题时复制粘贴 AI 生成的内容
wsseo
V2EX  ›  程序员

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

  •  
  •   wsseo · Dec 11, 2018 · 2488 views
    This topic created in 2739 days ago, the information mentioned may be changed or developed.
    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 replies    2018-12-11 17:49:04 +08:00
    auin
        1
    auin  
       Dec 11, 2018
    实际参数不是 r 吗?我觉得楼主基础知识有点缺,看不懂你的问题
    wsseo
        2
    wsseo  
    OP
       Dec 11, 2018
    @liuxey 我也觉得。我理解的是 r 是形式参数,函数不是一般需要传递实际参数吗?像这样调用的时候传递实参 func_b(r)
    akiakiseofficial
        3
    akiakiseofficial  
       Dec 11, 2018 via iPhone
    @wsseo 就跟 Java EE 中 servlet 的参数一样,实参是容器在调用处理方法时传进去的。具体到这个例子,匿名函数的实参是在请求 / 时 http 包内部在回调匿名函数时传进去的,实际应用中我们不需要关心。个人理解。
    auin
        4
    auin  
       Dec 11, 2018   ❤️ 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  
       Dec 11, 2018
    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
       Dec 11, 2018
    @liuxey 大概知道什么意思了
    tiedan
        7
    tiedan  
       Dec 11, 2018
    参数在 HandleFunc 里面传进去的啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5441 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 07:52 · PVG 15:52 · LAX 00:52 · JFK 03:52
    ♥ Do have faith in what you're doing.