我已将 Github 和 Google 身份验证系统添加到我的 Web 应用程序中。在这两种情况下,我都希望获得用户电子邮件。我尝试制作一个可以发出 API 请求并获取电子邮件的函数。当Google 返回一个 JSON 对象并在 Github 上返回一个 JSON 数组作为响应
时,我遇到了一个问题。 我无法弄清楚如何避免两次调用 JSON 解码器,因为我不能为它们两个使用相同的类型变量。
// Sends a request to the API and
// authorizes it by setting HTTP header "Authorization" to authHeader value
func getUserEmail(endpoint, authHeader, provider string) (string, error) {
var email string // Store user email here
var client http.Client // Create client so we can modify request headers
// Create a GET request to the endpoint
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return "", err
}
// Authorize the request by using the HTTP header
req.Header.Add("Authorization", authHeader)
// Give the data back as JSON
req.Header.Add("accept", "application/json")
// Send the request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Internet connection or client policy error")
return "", err
}
defer resp.Body.Close()
if provider == "google" {
var response map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
fmt.Println("Error occured during decoding access token response")
return "", err
}
email = response["email"].(string)
} else if provider == "github" {
var response []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
fmt.Println("Error occured during decoding access token response")
return "", err
}
email = response[0]["email"].(string)
} else {
return "", errors.New("invalid provider")
}
return email, nil
}
饮歌长啸
相关分类