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.

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

报告相同问题?

悬赏问题

  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀
  • ¥15 mifare plus卡认证
  • ¥30 LSTM预测结果是一条直线
  • ¥15 stnodeeditor自定义控件
  • ¥15 SDO如何更改STM32的波特率