dongxing4643 2016-07-27 02:30
浏览 39
已采纳

无法从Golang http请求获取位置标头

I'm trying to port over something I had written in Node, the request looks like this in Node(JS):

function _initialConnection(user, pass, callback) {
  let opts = {
    url: config.loginURL,
    headers: {
      "User-Agent": "niantic"
    }
  };

  request.get(opts, (err, resp, body) => {
    if (err) return callback(err, null);

    console.log(resp.headers);

    let data;
    try {
      data = JSON.parse(body);
    } catch(err) {
      return callback(err, null);
    }
    return callback(null, user, pass, data);
  });
}

function _postConnection(user, pass, data, callback) {
  let opts = {
    url: config.loginURL,
    form: {
      'lt': data.lt,
      'execution': data.execution,
      '_eventId': 'submit',
      'username': user,
      'password': pass
    },
    headers: {
      'User-Agent': 'niantic'
    }
  };


  request.post(opts, (err, resp, body) => {
    if (err) return callback(err, null);

    let parsedBody;
    if (body) {
      try {
        parsedBody = JSON.parse(body)
        if (('errors' in parsedBody) && parsedBody.errors.length > 0) {
          return callback(
            new Error('Error Logging In: ' + paredBody.errors[0]),
            null
          )
    }
      } catch(err) {
        return callback(err, null);
      }
    }

    console.log(resp.headers)

    let ticket = resp.headers['location'].split('ticket=')[1];

    callback(null, ticket);
  });
}

If I console.log(resp.headers) I can see a location header.

I have tried to recreate this in Go the best way I could which I ended up with:

// Initiate HTTP Client / Cookie JAR

jar, err := cookiejar.New(nil)
if err != nil {
    return "", fmt.Errorf("Failed to create new cookiejar for client")
}
newClient := &http.Client{Jar: jar, Timeout: 5 * time.Second}

// First Request

req, err := http.NewRequest("GET", loginURL, nil)
if err != nil {
    return "", fmt.Errorf("Failed to authenticate with Google
 Details: 

 Username: %s
 Password: %s
 AuthType: %s
", details.Username, details.Password, details.AuthType)
}
req.Header.Set("User-Agent", "niantic")
resp, err := newClient.Do(req)
if err != nil {
    return "", fmt.Errorf("Failed to send intial handshake: %v", err)
}
respJSON := make(map[string]string)
err = json.NewDecoder(resp.Body).Decode(&respJSON)
if err != nil {
    return "", fmt.Errorf("Failed to decode JSON Body: %v", err)
}

resp.Body.Close()

// Second Request

form := url.Values{}
form.Add("lt", respJSON["lt"])
form.Add("execution", respJSON["execution"])
form.Add("_eventId", "submit")
form.Add("username", details.Username)
form.Add("password", details.Password)
req, err = http.NewRequest("POST", loginURL, strings.NewReader(form.Encode()))
if err != nil {
    return "", fmt.Errorf("Failed to send second request authing with PTC: %v", err)
}
req.Header.Set("User-Agent", "niantic")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err = newClient.Do(req)
if err != nil {
    return "", fmt.Errorf("Failed to send second request authing with PTC: %v", err)
}
log.Println(resp.Location())
ticket := resp.Header.Get("Location")

if strings.Contains(ticket, "ticket") {
    ticket = strings.Split(ticket, "ticket=")[1]
} else {
    return "", fmt.Errorf("Failed could not get the Ticket from the second request
")
}
resp.Body.Close()

But when I log.Println(resp.Location()) I get <nil>

I'm really not sure what the differences are here (I've tried with and without the Content-Type header but for some reason I just can NOT get the Location header that I'm looking for.

I really can't see a discrepancy between the Node request, vs the Go request but any help would be great as I have been beating my head off the wall for the last day. Thanks.

  • 写回答

1条回答 默认 最新

  • dqls67891 2016-07-27 03:12
    关注

    You can get that url by checking resp.Request.URL after the resp, err = newClient.Do(req). There isn't a really simple way to ignore redirects, you can do a manual call through a http.RoundTripper, or you can set a CheckRedirect function on the client, but it's not ideal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的