首页 > 解决方案 > 我如何在 go lang 中导出变量/属性

问题描述

我正在尝试在不使用任何框架的情况下在 golang 中创建一个 MVC Web 应用程序。我打算如何实现它是使用 http.NewServeMux() 创建一个 http.Server {} 的实例,因为它的处理程序如下所示:

 sm := http.NewServeMux()
    sm.Handle("/route1", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/front-office/index.html")
    }))
    sm.Handle("/route2", handleSomething())
    sm.Handle("/route3", handleSomething())
    sm.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))


    frontEndUIServer := http.Server{
        Addr:    ":9000",
        Handler:  sm,
    }
    go frontEndUIServer.ListenAndServe()

然后使属性sm可导出,以便任何其他 go 文件可以导入它并在其上创建处理程序,从而实现我的控制器。由于我是 goLang 的新手,我现在的问题是如何使属性sm可导出?

标签: gopackagewebserver

解决方案


当您问“我如何使属性 sm 可导出”时,我假设您的意思是节点意义上的?如果是这样,您正在寻找的概念是“包”。

https://www.golang-book.com/books/intro/11

这允许使用“导入”在其他包中引用一个包中的功能。请注意,您要访问的函数的名称必须以大写字母与小写字母开头,只能在包中引用。

通常,Web 服务器是在“主”函数/包中创建的,控制器附加到您定义的路由。

这是一个很好的基本示例:https ://astaxie.gitbooks.io/build-web-application-with-golang/en/03.2.html


推荐阅读