doufu8887 2017-12-23 17:13
浏览 7

通话功能混乱

In this bit of code:

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

}

What is the func keyword doing? I've been reading through the Tour of Go and I'm confused as to what is going on here.

EDITED: Added import list and function that it was apart of

It's part of a function here:

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条回答 默认 最新

  • dousi1875 2017-12-23 17:20
    关注

    func defines a closure, an annonymous function. handler is a variable that holds a reference to this function, which you can later call by passing the arguments in parenthesis:

    handler(w, req)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图