登录
首页 >  Golang >  Go问答

处理程序的运作原理是什么?

来源:stackoverflow

时间:2024-02-26 20:24:27 442浏览 收藏

本篇文章向大家介绍《处理程序的运作原理是什么?》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我正在看这个例子

var name string

type helloworldresponse struct {
    message string `json:"message"`
}

type helloworldrequest struct {
    name string `json:"name"`
}

func main() {
    port := 8080

    handler := newvalidationhandler(newhelloworldhandler())
    http.handle("/helloworld", handler)
    log.printf("server starting on port %v\n", port)
    log.fatal(http.listenandserve(fmt.sprintf(":%v", port), nil))
}

type validationhandler struct {
    next http.handler
}

func newvalidationhandler(next http.handler) http.handler {
    return validationhandler{next: next}
}

func (h validationhandler) servehttp(rw http.responsewriter, r *http.request) {
    var request helloworldrequest
    decoder := json.newdecoder(r.body)

    err := decoder.decode(&request)
    if err != nil {
        http.error(rw, "bad request", http.statusbadrequest)
        return
    }

    name = request.name
    h.next.servehttp(rw, r)
}

type helloworldhandler struct{}

func newhelloworldhandler() http.handler {
    return helloworldhandler{}
}

func (h helloworldhandler) servehttp(rw http.responsewriter, r *http.request) {
    response := helloworldresponse{message: "hello " + name}

    encoder := json.newencoder(rw)
    encoder.encode(response)
}

代码的作者解释说我们是 将处理程序链接在一起,第一个处理程序,这是我们的验证处理程序, 需要引用链中的下一个,因为它有责任调用 servehttp 或返回响应。我是 go 新手,我不明白这一行

return validationHandler{next: next}

next:next 代表哪种数据结构?


解决方案


type validationHandler struct {
    next http.Handler // 1
}

func newValidationHandler(next /* 2 */ http.Handler) http.Handler { 
    return validationHandler{next: next} 
    //                         1     2
}

next 号 1 是 validationhandler 结构中的字段(上面几行)。另一个 next 是方法的参数(来自签名)。总而言之,这只是在结构中设置一个字段。没有魔法。

next:next 代表哪种数据结构?

不是数据结构。这是结构初始化语法。在此处查看更多示例:https://gobyexample.com/structs

今天关于《处理程序的运作原理是什么?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>