我正在编写一个需要登录网站以获取一些数据的 go 程序。登录过程已完成,但现在我遇到的问题是我无法使用从登录表单获得的 cookie 访问 protected 页面。在检查它们并与我的浏览器获得的那些进行比较后,我注意到我的程序获得带有“空”时间戳的 cookie。有人可以指出,我如何获得具有正确时间戳的 cookie?那太棒了。
这是我的代码:
package main
import (
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
"time"
)
var CookieJar *cookiejar.Jar
var httpClient *http.Client
func dbgPrintCurCookies(CurCookies []*http.Cookie) {
var cookieNum int = len(CurCookies)
log.Printf("cookieNum=%d", cookieNum)
for i := 0; i < cookieNum; i++ {
var curCk *http.Cookie = CurCookies[i]
//log.Printf("curCk.Raw=%s", curCk.Raw)
log.Printf("Cookie [%d]", i)
log.Printf("Name\t=%s", curCk.Name)
log.Printf("Value\t=%s", curCk.Value)
log.Printf("Path\t=%s", curCk.Path)
log.Printf("Domain\t=%s", curCk.Domain)
log.Printf("Expires\t=%s", curCk.Expires)
log.Printf("RawExpires=%s", curCk.RawExpires)
log.Printf("MaxAge\t=%d", curCk.MaxAge)
log.Printf("Secure\t=%t", curCk.Secure)
log.Printf("HttpOnly=%t", curCk.HttpOnly)
log.Printf("Raw\t=%s", curCk.Raw)
log.Printf("Unparsed=%s", curCk.Unparsed)
}
}
func main() {
CookieJar, _ = cookiejar.New(nil)
httpClient := &http.Client{
Jar: CookieJar,
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}}
LSFRedirURL := ""
pw := "
us := ""
LoginURL := "login website ?j_password=" + pw + "&j_username=" + us
GetFinalCookieURL := ""
//get first cookie
nextURL := LSFRedirURL
for i := 0; i < 10; i++ {
resp, _ := httpClient.Get(nextURL)
// fmt.Println("StatusCode:", resp.StatusCode)
// fmt.Println(resp.Request.URL)
if resp.StatusCode == 200 {
// fmt.Println("Done!")
break
} else {
nextURL = resp.Header.Get("Location")
}
}
//safe first cookie
url1, _ := url.Parse("first cookie website")
firstCookie := CookieJar.Cookies(url1)[0]
fmt.Println("First Cookie :\\)")
//getting second cookie and params
// var cam []string
var resp *http.Response
nextURL = LoginURL
for i := 0; i < 10; i++ {
resp, _ = httpClient.Post(nextURL, "", nil)
// fmt.Println("StatusCode:", resp.StatusCode)
// fmt.Println(resp.Request.URL)
// cam = append(cam, nextURL)
if resp.StatusCode == 200 {
fmt.Println("Done!")
break
} else {
nextURL = resp.Header.Get("Location")
}
}
//second cookie
url2, _ := url.Parse("website second cookie is from")
secondCookie := CookieJar.Cookies(url2)[0]
fmt.Println("Second Cookie :\\)")
//params
defer resp.Body.Close()
c, _ := ioutil.ReadAll(resp.Body)
data := html.UnescapeString(string(c))
//fmt.Println(data)
getvalue := regexp.MustCompile("value=\".*\"")
values := getvalue.FindAllStringSubmatch(data, -1)
values[0][0] = strings.TrimSuffix(values[0][0], "\"")
values[0][0] = strings.TrimPrefix(values[0][0], "value=\"")
values[1][0] = strings.TrimSuffix(values[1][0], "\"")
values[1][0] = strings.TrimPrefix(values[1][0], "value=\"")
v := url.Values{
"SAMLResponse": {values[1][0]},
"RelayState": {values[0][0]},
}
body := strings.NewReader(v.Encode())
fmt.Println("Values :\\)")
//adding values and cookies to request
req, _ := http.NewRequest("POST", GetFinalCookieURL, body)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(firstCookie)
req.AddCookie(secondCookie)
resp, _ = httpClient.Do(req)
//we got the real cookie
url3, _ := url.Parse("website i get the cookies for")
dbgPrintCurCookies(CookieJar.Cookies(url3))
finalCookie := CookieJar.Cookies(url3)[0]
finalCookie2 := CookieJar.Cookies(url3)[1]
fmt.Println("StatusCode:", resp.StatusCode)
fmt.Println(resp.Request.URL)
nextURL = resp.Header.Get("Location")
fmt.Println(nextURL)
nextURL = "website i need the cookies for"
req, _ = http.NewRequest("GET", nextURL, nil)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(finalCookie)
req.AddCookie(finalCookie2)
resp, _ = httpClient.Do(req)
url3, _ = url.Parse("final cookie website")
dbgPrintCurCookies(CookieJar.Cookies(url3))
fmt.Println(resp.StatusCode)
fmt.Println(resp.Request.URL)
defer resp.Body.Close()
data3, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(data3))
}
这是我得到的 cookie 的示例:
2018/02/10 01:55:48 cookieNum=2
2018/02/10 01:55:48 Cookie [0]
2018/02/10 01:55:48 Name =JSESSIONID
2018/02/10 01:55:48 Value =86E2C361905167A1F64FC45C400649F2.stupo1
2018/02/10 01:55:48 Path =
2018/02/10 01:55:48 Domain =
2018/02/10 01:55:48 Expires =0001-01-01 00:00:00 +0000 UTC
2018/02/10 01:55:48 RawExpires=
2018/02/10 01:55:48 MaxAge =0
2018/02/10 01:55:48 Secure =false
2018/02/10 01:55:48 HttpOnly=false
2018/02/10 01:55:48 Raw =
2018/02/10 01:55:48 Unparsed=[]
编辑:添加了完整的代码。这是浏览器中的 cookie: Cookie in Browser
最佳答案
Cookie 有两种形式:一种是在 Set-Cookie header 中接收,另一种是在 Cookie header 中发送。只有 Set-Cookie header cookie 有过期时间和各种字段,而 Cookie header type cookie 是纯名称,值元组。这就是 cookiejar 返回的内容,因为它包含在 Cookie header 中。
stdlib 的默认 cookie jar 实现不提供提取除名称和值之外的所有 cookie 或字段的机制。如果您需要该信息,请使用任何其他开源 cookie jar 实现。
(请注意,stdlib cookie jar 实现的全部目的是透明地处理 cookie,即使是通过重定向。它不是收集有关传入的 Set-Cookie header 和其中发送的各种值的信息的解决方案。)
关于Golang cookie 的时间戳为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716283/
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查
这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时
因为我现在正在做一些时间测量,我想知道是否可以在不使用Benchmark类或命令行实用程序time的情况下测量用户时间或系统时间。使用Time类只显示挂钟时间,而不显示系统和用户时间,但是我正在寻找具有相同灵active的解决方案,例如time=TimeUtility.now#somecodeuser,system,real=TimeUtility.now-time原因是我有点不喜欢Benchmark,因为它不能只返回数字(编辑:我错了-它可以。请参阅下面的答案。)。当然,我可以解析输出,但感觉不对。*NIX系统的time实用程序也应该可以解决我的问题,但我想知道是否已经在Ruby中实
在Ruby中,以毫秒为单位获取自纪元(1970)以来的当前系统时间的正确方法是什么?我试过了Time.now.to_i,好像不是我想要的结果。我需要结果显示毫秒并且使用long类型,而不是float或double。 最佳答案 (Time.now.to_f*1000).to_iTime.now.to_f显示包含十进制数字的时间。要获得毫秒数,只需将时间乘以1000。 关于ruby-以毫秒为单位获取当前系统时间,我们在StackOverflow上找到一个类似的问题:
我想知道我应该如何着手这个项目。我需要每周向人们发送一次电子邮件。但是,这必须在每周的特定时间自动生成并发送。编码有多难?我需要知道是否有任何书籍可以提供帮助,或者你们中的任何人是否可以指导我。它必须使用rubyonrails进行编程。因此有一个网络服务和数据库集成。干杯 最佳答案 为什么这么复杂?您只需安排工作。您可以使用Delayed::Job例如。Delayed::Job让您可以使用run_at符号在特定时间安排作业,如下所示:Delayed::Job.enqueue(SendEmailJob.new(...),:run_
我在ruby1.9.3p0上运行rails3.2.1和rspec2.8.1,在运行我的测试时它显示负时间值。这很烦人,因为我正在尝试优化我的测试。Running:spec/models/transaction_spec.rb................................................Finishedin-7603162.49414seconds我已经尝试将rspec更新到2.9.0,但这没有帮助。 最佳答案 你在使用timecopgem吗?确保在卡住后Timecop.return。或者你在某处
在我的场景中,Logstash收到的系统日志行的“时间戳”是UTC,我们在Elasticsearch输出中使用事件“时间戳”:output{elasticsearch{embedded=>falsehost=>localhostport=>9200protocol=>httpcluster=>'elasticsearch'index=>"syslog-%{+YYYY.MM.dd}"}}我的问题是,在UTC午夜,Logstash在外时区(GMT-4=>America/Montreal)结束前将日志发送到不同的索引,并且索引在20小时(晚上8点)之后没有日志,因为“时间戳”是UTC。我们已