我对使用 golang 进行编码还很陌生,并且正在为错误的 url 请求而在 panic/recover 过程中苦苦挣扎。下面是一个查询 URL 列表并输出响应的脚本。偶尔会输入错误的 url 或服务器关闭,HTTP 请求失败,从而导致 panic 。我不清楚如何从中恢复并继续。我希望程序从 panic 中恢复,记录错误的 url 和错误,并继续向下输出失败的 url 和错误的 url 列表以及其余的正常 url 响应数据。
package main
import (
"fmt"
"net/http"
)
var urls = []string{
"http://www.google.com", //good url, 200
"http://www.googlegoogle.com/", //bad url
"http://www.zoogle.com", //500 example
}
//CONCURRENT HTTP REQUESTS -------------------------------------------
func MakeRequest(url string, ch chan<- string) {
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error Triggered", err)
ch <- fmt.Sprintf("err: %s", err)
}
ch <- fmt.Sprintf("url: %s, status: %s ", url, resp.Status) // put response into a channel
resp.Body.Close()
}
func main() {
output := make([][]string, 0) //define an array to hold responses
//PANIC RECOVER------------------------------
defer func() { //catch or finally
if r := recover(); r != nil { //catch
fmt.Println("Recover Triggered: ", r)
}
}()
//MAKE URL REQUESTS----------------------------------------------
for _, url := range urls {
ch := make(chan string) //create a channel for each request
go MakeRequest(url, ch) //make concurrent http request
output = append(output, []string{<-ch}) //append output to an array
}
//PRINT OUTPUT ----------------------
for _, value := range output {
fmt.Println(value)
}
}
我正在寻找类似于以下内容的输出:
[网址:http://www.google.com , 状态: 200 OK ]
[网址:http://www.googlegoogle.com , 错误:没有这样的主机]
[网址:http://www.zoogle.com ,状态:500 内部服务器错误]
最佳答案
谢谢 Jim B。我假设 panic 是由请求触发的,但这是尝试对失败的请求使用“resp.Status”,因为它不存在。我修改了我的错误处理,如果没有错误,只在“ch”中放置一个 resp.Status。在出现错误的情况下,我用错误值将不同的响应替换为“ch”。无需恢复,因为没有触发 panic 。
func MakeRequest(url string, ch chan<- string) {
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprintf("url: %s, err: %s ", url, err)
} else {
ch <- fmt.Sprintf("url: %s, status: %s ", url, resp.Status) // put response into a channel
defer resp.Body.Close()
}
}
现在的输出是:
[网址:http://www.google.com , 状态: 200 OK ]
[网址:http://www.googlegoogle.com/ ,错误:获取http://www.googlegoogle.com/ : dial tcp: lookup www.googlegoogle.com: 没有这样的主机]
[网址:http://www.zoogle.com ,状态:500 内部服务器错误]
关于http - golang http请求错误panic recover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272888/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
是的,我知道最好使用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
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa