小编jca*_*o94的帖子

在Golang中使用Http处理程序的全局变量

我知道有一些关于这个问题的问题和帖子/文章,但从我的新手观点来看,并不完全正确.问题是,我有一个主程序监听端口并将调用重定向到特定的处理程序.典型结构:

func main() {
    http.HandleFunc("/something", specificHandler)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

处理程序是这样的:

func specificHandler(w http.ResponseWriter, r *http.Request) {
    somepackage.foo()
}
Run Code Online (Sandbox Code Playgroud)

然后somepackage包含函数foo,它有一些全局变量,主要是因为它们需要共享函数(例如,当使用一个用容器/堆实现的优先级队列时,它将获得交换函数中的优先级.全球距离矩阵,当然是可变的).还有很多其他的例子.总之,全局变量......

正如您可能看到的,问题是这些变量在对处理程序的所有调用之间共享.这很糟糕.

我怎么能真正解决这个问题?必须有一个容易实现的方法,我还没有,因为它看起来像这么平常......

提前致谢.


编辑

使它更清楚.例如,在我的A*包中,我有以下全局变量:

var openVerticesAS PriorityQueueAStar

// which vertices are closed
var closedVertices map[int]bool

// which vertices are currently open
var openVertices map[int]bool

// cost from start to node
var gScore map[int]float64

// cost from start to end, passing by node i (g+h)
var fScore map[int]float64
Run Code Online (Sandbox Code Playgroud)

然后,PriorityQueueAStar实现如下:

type PriorityQueueAStar []int // rel id …
Run Code Online (Sandbox Code Playgroud)

global-variables httphandler go

9
推荐指数
1
解决办法
4349
查看次数

标签 统计

global-variables ×1

go ×1

httphandler ×1