go - 我如何在 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
可导出?
解决方案
当您问“我如何使属性 sm 可导出”时,我假设您的意思是节点意义上的?如果是这样,您正在寻找的概念是“包”。
https://www.golang-book.com/books/intro/11
这允许使用“导入”在其他包中引用一个包中的功能。请注意,您要访问的函数的名称必须以大写字母与小写字母开头,只能在包中引用。
通常,Web 服务器是在“主”函数/包中创建的,控制器附加到您定义的路由。
这是一个很好的基本示例:https ://astaxie.gitbooks.io/build-web-application-with-golang/en/03.2.html
推荐阅读
- coinbase-api - React Native 中的 Coinbase API 密钥认证
- python - sys.args[1] 命令的“IndexError: list index out of range”
- mongodb - MongoDB的移位列
- php - WooCommerce 在 foreach 中获取所有订单
- java - 通过键将 GroupFlux 收集到 Hashmap 中
- php - PHP 将字符串从 ASCII 转换为 UTF-8 / WINDOWS-1255
- android-studio - Androidstudio 项目中的 Project.xml。这是源代码控制的一部分吗?
- ruby-on-rails - 在rails中创建belongs_to关联时1:整数的未定义方法`build_part'
- python - python pd.DataFrame({'Dokuman': docs, 'Sinif': classes}) 中的熊猫数据框问题
- git - git的文件写入(在工作目录中)是原子的吗?