关于HandleFileList的返回类型

来源:8-3 服务器统一出错处理

慕瓜9466948

2020-01-13

func HandleFileList(writer http.ResponseWriter, request *http.Request) error {
	path := request.URL.Path[1:]
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()
	//读取文件
	all, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}
	writer.Write(all)
	return nil
}

这个函数的返回类型写的是error为什么调用后返回的却是 func(http.ResponseWriter, *http.Request) error 一个函数的类型麻烦老师帮我解答一下,谢谢

写回答

1回答

ccmouse

2020-01-19

https://git.imooc.com/coding-180/coding-180/src/master/lang/errhandling/filelistingserver/web.go#L67  处

http.HandleFunc("/", errWrapper(filelisting.HandleFileList))

这里filelisting.HandleFileList后面没有括号,这不是一个函数调用,是把这个函数本身作为参数传递给errWrapper函数。

errWrapper函数的参数就是:

type appHandler func(writer http.ResponseWriter, request *http.Request) error

func errWrapper(handler appHandler) func(http.ResponseWriter, *http.Request)

我们看到这个HandleFileList正是满足了appHandler的定义。

0
0

Google资深工程师深度讲解Go语言 由浅入深掌握Go语言

语法+分布式爬虫实战 为转型工程师量身打造

5995 学习 · 1909 问题

查看课程