代码之家  ›  专栏  ›  技术社区  ›  jenkelblankel

Go func调用混乱

go
  •  -3
  • jenkelblankel  · 技术社区  · 8 年前

    在这段代码中:

    handler := func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "<html><body>Hello World!</body></html>")
    

    }

    func 关键词在做什么?我一直在阅读围棋之旅,我对这里发生了什么感到困惑。

    已编辑:添加了导入列表和它所属的功能

    func ExampleResponseRecorder() {
    handler := func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "<html><body>Hello World!</body></html>")
    }
    
    req := httptest.NewRequest("GET", "http://example.com/foo", nil)
    w := httptest.NewRecorder()
    handler(w, req)
    
    resp := w.Result()
    body, _ := ioutil.ReadAll(resp.Body)
    
    fmt.Println(resp.StatusCode)
    fmt.Println(resp.Header.Get("Content-Type"))
    fmt.Println(string(body))
    
    // Output:
    // 200
    // text/html; charset=utf-8
    // <html><body>Hello World!</body></html>
     }
    
    import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/httptest"
    )
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Mureinik    8 年前

    func 定义 closure handler 是一个变量,其中包含对此函数的引用,稍后可以通过在括号中传递参数来调用该函数:

    handler(w, req)