我通过创建一个简单的http服务器开始学习golang
func main() {
f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
fmt.Println("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
http.HandleFunc("/", defaultHandler)
http.HandleFunc("/check", checkHandler)
serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port
if serverErr != nil {
log.Println("Error starting server")
} else {
fmt.Println("Started server on - 127.0.0.1:8080" )
}
}
上面的代码将在 8080 上启动一个本地服务器,我可以通过浏览器访问路由。一切都很好!
但是,现在我想运行一个单独的 go 例程,它会监视一个文件 -
func initWatch() string{
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if ( event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename ) {
fmt.Println("file removed - ", event.Name)
}
case err := <-watcher.Errors:
fmt.Println("error:", err)
}
}
}()
err = watcher.Add("sampledata.txt")
if err != nil {
fmt.Println(err)
}
<-done
}
现在,如果我调用函数 initWatch() BEFORE http.ListenAndServe("127.0.0.1:8080", nil)然后我无法通过浏览器访问服务器路由(例如 - 本地主机:8080),因为服务器尚未生成。
例如-
initWatch()
serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port
如果我调用函数 initWatch() AFTER http.ListenAndServe("127.0.0.1:8080", nil) 然后文件观察器功能不工作。
例如-
serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port
initWatch()
如何同时运行 initWatch()(文件观察器)和 http 服务器?
感谢您的帮助。
最佳答案
您可以在单独的 goroutine 中启动 watcher。服务器结束后 - 您向观察者发送退出信号。喜欢:
done := initWatch()
serverErr := http.ListenAndServe("127.0.0.1:8080", nil)
done <- true
接下来稍微修改 watcher - 返回通知停止工作的 channel 。同时工作的 goroutine 监听退出信号。
func initWatch() chan bool {
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if ( event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename ) {
fmt.Println("file removed - ", event.Name)
}
case err := <-watcher.Errors:
fmt.Println("error:", err)
// listen exit signal
case <- done:
break
}
}
}()
err = watcher.Add("sampledata.txt")
if err != nil {
fmt.Println(err)
}
return done
}
关于http - golang 在 http.ListenAndServe 之后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778600/
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只