【问题标题】:How do i export a variable/property in go lang我如何在 go lang 中导出变量/属性
【发布时间】:2019-10-02 00:03:01
【问题描述】:

我正在尝试在不使用任何框架的情况下在 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 可导出?

【问题讨论】:

标签: go package webserver


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

    您可以像这样在mywebapp 包中定义您的网络应用程序:

    package mywebapp
    
    import "net/http"
    
    var SM *http.ServeMux
    
    func init() {
        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()
    }
    

    服务器使用的ServeMux 被导出,以便其他包可以添加处理程序。导入包后服务器立即启动。

    【讨论】:

      猜你喜欢
      • 2016-01-03
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2013-03-27
      • 2021-03-20
      相关资源
      最近更新 更多