Выполнение POST-запроса в Go с использованием formdata и аутентификации - PullRequest
0 голосов
/ 28 октября 2018

В настоящее время я пытаюсь взаимодействовать с API-интерфейсом OAuth с помощью команды curl curl -u {client_id}:{client_secret} -d grant_type=client_credentials https://us.battle.net/oauth/token. Мой текущий файл go:

package main

import (
    "bytes"
    "fmt"
    "mime/multipart"
    "net/http"
)

func checkErr(err error) bool {
    if err != nil {
        panic(err)
    }
    return true
}

func authcode(id string, secret string, cli http.Client) string {
    //un(trace("authcode"))
    var form bytes.Buffer
    w := multipart.NewWriter(&form)
    _, err := w.CreateFormField("grant_type=client_credentials")
    checkErr(err)
    req, err := http.NewRequest("POST", "https://us.battle.net/oauth/token", &form)
    checkErr(err)
    req.SetBasicAuth(id, secret)
    resp, err := cli.Do(req)
    checkErr(err)
    defer resp.Body.Close()
    json := make([]byte, 1024)
    _, err = resp.Body.Read(json)
    checkErr(err)
    return string(json)
}

func main() {
    //un(trace("main"))
    const apiID string = "user"
    const apiSecret string = "password"
    apiClient := &http.Client{}
    auth := authcode(apiID, apiSecret, *apiClient)
    fmt.Printf("%s", auth)
}

Когда я запускаю это, я получаю ответ {"error":"invalid_request","error_description":"Missing grant type"}

Для справки: состояние потока API:
«Чтобы запросить токены доступа, приложение должно сделать запрос POST со следующими данными многочастной формы к URI токена: grant_type = client_credentials

Приложение должно передать базовые учетные данные HTTP-аутентификации, используя client_id в качестве пользователя и client_secret в качестве пароля. "
ожидаемый ответ - строка json, содержащая токен доступа, тип токена, срок действия в секундах и объем функций, доступных с указанным токеном

1 Ответ

0 голосов
/ 28 октября 2018

Из руководства по скручиванию мы имеем:

       -d, --data <data>
          (HTTP)  Sends  the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and
          presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.   Compare  to
          -F, --form.

Обратите внимание на content-type application/x-www-form-urlencoded деталь.

вместо:

       -F, --form <name=content>
          (HTTP SMTP IMAP) For HTTP protocol family, this lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl  to
          POST data using the Content-Type multipart/form-data according to RFC 2388.

Следовательно, основываясь на вашем curl, mime/multipart, вероятно, не то, что вы ищете, и вы должны использовать Client.PostForm, из руководства которого у нас есть:

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...