没有从Golang http请求获取Location标头

时间:2016-07-27 02:30:10

标签: go

我试图移植我在Node中编写的内容,请求在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);
  });
}

如果我console.log(resp.headers)我可以看到位置标题。

我试图以最好的方式重新创建这个,我最终得到了:

// 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\n Details: \n\n Username: %s\n Password: %s\n AuthType: %s\n", 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\n")
}
resp.Body.Close()

但是当我log.Println(resp.Location())时,我得到<nil>

我真的不确定这里的差异是什么(我已尝试使用和不使用Content-Type标题,但出于某种原因,我无法获得我所在的位置标题。我正在寻找。

我真的无法看到Node请求与Go请求之间的差异,但任何帮助都会很棒,因为我在最后一天一直在打破我的头。感谢。

1 个答案:

答案 0 :(得分:1)

您可以在resp.Request.URL之后查看resp, err = newClient.Do(req)来获取该网址。没有非常简单的方法可以忽略重定向,您可以通过http.RoundTripper进行手动调用,也可以在客户端设置CheckRedirect功能,但这并不理想