What's the equivalent of Flask's @before_first_request in golang?

huangapple go评论89阅读模式
英文:

What's the equivalent of Flask's @before_first_request in golang?

问题

我们正在出于性能原因将一个 Flask 应用切换到 Golang。在 Flask 中,有一个名为 "before_first_request" 的装饰器,用于指定在应用启动时运行的函数。这个函数只会运行一次。我已经阅读了文档,但在 Golang 中找不到类似的功能...它存在吗?(我想它可能不需要是 net/http 包的一部分)

我们的 Flask 代码示例:

@before_first_request
def before(*args, **kwargs):
    ....
    return

请注意,我只会返回翻译好的内容,不会回答关于翻译的问题。

英文:

We are switching a flask app to golang for performance reasons. In flask, there is "before_first_request" which indicates a function to be run when the app gets started. This function gets run once and only once. I've been reading through the docs but can't find any equivalent in golang....does it exist? (I imagine it doesn't have to be part of the net/http package)

Our flask:

@before_first_request
def before(*args, **kwargs):
    ....
    return

答案1

得分: 4

一种方法是将函数逻辑放在模块的 func init() { ... } 方法中。

另外,你可以使用 sync.Once

package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	onceBody := func() {
		fmt.Println("只执行一次")
	}
	done := make(chan bool)
	for i := 0; i < 10; i++ {
		go func() {
			once.Do(onceBody)
			done <- true
		}()
	}
	for i := 0; i < 10; i++ {
		<-done
	}
}
英文:

one way to do it is to put your function logic inside the func init() { ... } method of your module.

Otherwise you could use sync.Once

http://play.golang.org/p/SEJxEEDnxt

package main

import (
	&quot;fmt&quot;
	&quot;sync&quot;
)

func main() {
	var once sync.Once
	onceBody := func() {
		fmt.Println(&quot;Only once&quot;)
	}
	done := make(chan bool)
	for i := 0; i &lt; 10; i++ {
		go func() {
			once.Do(onceBody)
			done &lt;- true
		}()
	}
	for i := 0; i &lt; 10; i++ {
		&lt;-done
	}
}

huangapple
  • 本文由 发表于 2014年8月26日 04:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/25494103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定