Attualmente sto scrivendo del software in Go che interagisce con un'API REST. L'endpoint dell'API REST che sto tentando di eseguire query restituisce un reindirizzamento HTTP 302 insieme a un'intestazione Location HTTP, che punta a un URI di risorsa.Come posso rendere il client HTTP Go NON seguire i reindirizzamenti automaticamente?
Sto provando a utilizzare il mio script Go per acquisire l'intestazione della posizione HTTP per l'elaborazione successiva.
Ecco quello che sto facendo attualmente per ottenere questa funzionalità attualmente:
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.stormpath.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"
func noRedirect(req *http.Request, via []*http.Request) error {
return errors.New("Don't redirect!")
}
func main() {
client := &http.Client{
CheckRedirect: noRedirect
}
req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
req.SetBasicAuth(STORMPATH_API_KEY_ID, STORMPATH_API_KEY_SECRET)
resp, err := client.Do(req)
// If we get here, it means one of two things: either this http request
// actually failed, or we got an http redirect response, and should process it.
if err != nil {
if resp.StatusCode == 302 {
fmt.Println("got redirect")
} else {
panic("HTTP request failed.")
}
}
defer resp.Body.Close()
}
Questo si sente come un po 'di hack per me. Sovrascrivendo la funzione CheckRedirect
di , sono essenzialmente obbligato a trattare i reindirizzamenti HTTP come errori (che non sono).
Ho visto molti altri posti che suggeriscono di usare un trasporto HTTP invece di un client HTTP - ma non sono sicuro di come farlo funzionare poiché ho bisogno del client HTTP perché ho bisogno di usare l'autenticazione di base HTTP per comunicare con questa API REST.
Qualcuno di voi può dirmi un modo per effettuare richieste HTTP con l'autenticazione di base - pur non seguendo i reindirizzamenti - che non comporta errori di lancio e gestione degli errori?
Grazie.
Guardando la [fonte] (http://golang.org/src/pkg/net/http/client.go) non sembra. L'intestazione 'Location' viene richiamata * dopo * la chiamata' CheckRedirect' e non si ha accesso alla risposta provvisoria. –
Credo che tu abbia ragione @DmitriGoldring - facendomi impazzire. Deve esserci un modo per farlo funzionare - Non posso immaginare che non ci sia un buon modo per farlo>< – rdegges