我是 Go 的新手,正在尝试向多个 http/https 服务器生成多个请求,以检查每个 Web 服务器的响应时间和状态。
我将 URL 存储在一个文本文件中,之后我决定在我的代码中添加一个自动收报机,它将在一定时间后继续在每个 URL 上生成这些请求(时间量以秒为单位,在每个 URL 旁边键入并用制表符隔开)。
当我开始扫描文件中的时间时,一切都变得复杂起来,我无法找到我的错误。这是我的 Go 代码:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
func get_resp_time(url string) { //Get time for each URL
time_start := time.Now()
fmt.Println("Start time", time_start, " URL ", url)
resp, err := http.Get(url)
//fmt.Printf("resp : %#v \n", resp)
if err != nil {
log.Printf("Error fetching: %v", err)
}
defer resp.Body.Close()
fmt.Println(time.Since(time_start), url, " Status: ", resp.Status)
}
func main() {
content, _ := ioutil.ReadFile("url_list.txt")
lines := strings.Split(string(content), "\t")
//fields := strings.Split(string(content), "\t")
//fmt.Println(lines[1])
//fmt.Println(strconv.Atoi(lines[0]))
const workers = 25
var nb int
wg := new(sync.WaitGroup)
in := make(chan string, 2*workers)
if _, err := strconv.Atoi(lines[1]); err == nil {
nb, err = strconv.Atoi(lines[1])
}
ticker := time.NewTicker(time.Second * time.Duration(nb))
for t := range ticker.C {
fmt.Println("Time of origin: ", time.Now())
for i := 0; i < len(lines)-1; i++ {
wg.Add(1)
go func() {
defer wg.Done()
//for j := 0; j < len(in); j++ {
if _, err := strconv.Atoi(lines[i]); err == nil {
nb, err = strconv.Atoi(lines[i])
//get_resp_time(url)
} else {
get_resp_time(lines[i])
}
//}
}()
}
for _, url := range lines {
if url != "" {
in <- url
}
}
fmt.Println("Tick at ", t)
}
close(in)
wg.Wait()
}
和文本文件:
http://google.com 5
http://nike.com 10
这是我得到的错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x2752]
goroutine 9 [running]:
panic(0x313180, 0xc82000a0d0)
/usr/local/go/src/runtime/panic.go:464 +0x3e6
main.get_resp_time(0xc82006e195, 0x14)
/Users/Elliott/Desktop/GoTutorial/url-time-response.go:26 +0x712
main.main.func1(0xc820070dc0, 0xc82006e1e0, 0xc8200a0090, 0x9, 0x9, 0xc820070da8)
/Users/Elliott/Desktop/GoTutorial/url-time-response.go:61 +0x13f
created by main.main
/Users/Elliott/Desktop/GoTutorial/url-time-response.go:65 +0x4a6
exit status 2
编辑:好吧,我只是将文件更改为只有一个持续时间,因为显然具有多个持续时间非常复杂(根据我的项目顾问)。感谢您的帮助!
最佳答案
您似乎没有正确解析您的文件。您应该首先在 \n 上拆分,然后在 \t 上拆分。此外,验证您的文本文件确实包含 \t 而不是空格。
您可能应该使用 fmt.Println 遍历您的解析值,以验证您的解析结果是否符合预期。
它应该看起来像 this .
关于go - HTTP 定时请求 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595002/
是的,我知道最好使用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的路径中定义。这
rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送
我目前正在使用以下方法获取页面的源代码: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
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba
我正在使用Heroku(heroku.com)来部署我的Rails应用程序,并且正在构建一个iPhone客户端来与之交互。我的目的是将手机的唯一设备标识符作为HTTPheader传递给应用程序以进行身份验证。当我在本地测试时,我的header通过得很好,但在Heroku上它似乎去掉了我的自定义header。我用ruby脚本验证:url=URI.parse('http://#{myapp}.heroku.com/')#url=URI.parse('http://localhost:3000/')req=Net::HTTP::Post.new(url.path)#boguspara
我试图在我的网站上实现使用Facebook登录功能,但在尝试从Facebook取回访问token时遇到障碍。这是我的代码:ifparams[:error_reason]=="user_denied"thenflash[:error]="TologinwithFacebook,youmustclick'Allow'toletthesiteaccessyourinformation"redirect_to:loginelsifparams[:code]thentoken_uri=URI.parse("https://graph.facebook.com/oauth/access_token
我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)
我正在尝试解析网页,但有时会收到404错误。这是我用来获取网页的代码:result=Net::HTTP::getURI.parse(URI.escape(url))如何测试result是否为404错误代码? 最佳答案 像这样重写你的代码:uri=URI.parse(url)result=Net::HTTP.start(uri.host,uri.port){|http|http.get(uri.path)}putsresult.codeputsresult.body这将打印状态码和正文。