本文整理汇总了Golang中net/http.Client.Do方法的典型用法代码示例。如果您正苦于以下问题:Golang Client.Do方法的具体用法?Golang Client.Do怎么用?Golang Client.Do使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Client
的用法示例。
在下文中一共展示了Client.Do方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: authenticateWithBackend
func authenticateWithBackend(req *http.Request) (bool, error) {
auth, authExists := req.Header["Authorization"]
if authExists && isCached(auth[0]) {
return true, nil
}
var r *http.Request
var err error
var resp *http.Response
r, err = http.NewRequest("GET", planio_url, nil)
if err != nil {
return false, err
}
r.Header["Authorization"] = auth
client := http.Client{}
resp, err = client.Do(r)
if err != nil {
return false, err
}
resp.Body.Close()
if resp.StatusCode == 200 {
if authExists {
addToCache(auth[0])
}
return true, nil
}
return false, nil
}
示例2: PostFile
// 通过HTTP上传文件
// 模拟<form ...><input name="file" type="file" />...</form>
// 参数说明
// url: 上传服务器URL
// form_name: 对应<input>标签中的name
// file_name: 为form表单中的文件名
// path: 为实际要上传的本地文件路径
func PostFile(url, form_name, file_name, path string) (res *http.Response, err error) {
buf := new(bytes.Buffer) // caveat IMO dont use this for large files, \
// create a tmpfile and assemble your multipart from there (not tested)
w := multipart.NewWriter(buf)
fw, err := w.CreateFormFile(form_name, file_name) //这里的file必须和服务器端的FormFile一致
if err != nil {
return
}
fd, err := os.Open(path)
if err != nil {
return
}
defer fd.Close()
// Write file field from file to upload
_, err = io.Copy(fw, fd)
if err != nil {
return
}
// Important if you do not close the multipart writer you will not have a
// terminating boundry
w.Close()
req, err := http.NewRequest("POST", url, buf)
if err != nil {
return
}
req.Header.Set("Content-Type", w.FormDataContentType())
var client http.Client
res, err = client.Do(req)
return
}
示例3: TestWatchHTTPAccept
func TestWatchHTTPAccept(t *testing.T) {
simpleStorage := &SimpleRESTStorage{}
handler := handle(map[string]rest.Storage{"simples": simpleStorage})
server := httptest.NewServer(handler)
defer server.Close()
client := http.Client{}
dest, _ := url.Parse(server.URL)
dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples"
dest.RawQuery = ""
request, err := http.NewRequest("GET", dest.String(), nil)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
request.Header.Set("Accept", "application/XYZ")
response, err := client.Do(request)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// TODO: once this is fixed, this test will change
if response.StatusCode != http.StatusNotAcceptable {
t.Errorf("Unexpected response %#v", response)
}
}
示例4: getUserInfo
func getUserInfo(target_name string) UserInfo {
bearer := getToken()
url := "https://api.twitter.com/1.1/users/show.json?screen_name=" + target_name
request, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearer))
client := new(http.Client)
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
util.Perror(err)
var user_info UserInfo
parse_err := json.Unmarshal(body, &user_info)
util.Perror(parse_err)
return user_info
}
示例5: normalGet
func normalGet(method string, c *http.Client, url *url.URL) {
if c == nil {
c = http.DefaultClient
}
if *verbose {
log.Printf("%s %s", method, url)
}
req, err := http.NewRequest(method, url.String(), nil)
if err != nil {
log.Fatal(err)
}
resp, err := c.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
if !(resp.StatusCode >= 200 && resp.StatusCode <= 399) {
log.Fatalf("Error: HTTP %d: %s.", resp.StatusCode, body)
}
fmt.Println(string(body))
}
示例6: ExpireTokens
func (g *Adaptor) ExpireTokens(userID int) error {
request := ExpireTokenRequest{Action: "all"}
gandalfUrl := fmt.Sprintf("http://%s:%d/expire/%d", g.GandalfHost, g.GandalfPort, userID)
client := http.Client{}
marshalledReq, err := json.Marshal(request)
if err != nil {
return err
}
req, err := http.NewRequest("POST", gandalfUrl, bytes.NewBuffer(marshalledReq))
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New("failed to expire tokens")
}
return nil
}
示例7: Do
// Do sends an HTTP request with the provided http.Client and returns an HTTP response.
// If the client is nil, http.DefaultClient is used.
// If the context is canceled or times out, ctx.Err() will be returned.
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
if client == nil {
client = http.DefaultClient
}
// Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
cancel := canceler(client, req)
type responseAndError struct {
resp *http.Response
err error
}
result := make(chan responseAndError, 1)
go func() {
resp, err := client.Do(req)
result <- responseAndError{resp, err}
}()
select {
case <-ctx.Done():
cancel()
return nil, ctx.Err()
case r := <-result:
return r.resp, r.err
}
}
示例8: main
func main() {
// Create a new request
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/account/who_am_i", domain), strings.NewReader(""))
if err != nil {
log.Fatalln(err.Error())
}
// Set authentication and add Accept header
req.SetBasicAuth(username, password)
req.Header.Add("Accept", "application/json")
// Perform the request
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err.Error())
}
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Fatalln(err.Error())
}
log.Println(string(body))
}
示例9: getBlockIndexesForServer
func getBlockIndexesForServer(t *testing.T, i int) []string {
var indexes []string
path := keepServers[i] + "/index"
client := http.Client{}
req, err := http.NewRequest("GET", path, nil)
req.Header.Add("Authorization", "OAuth2 "+arvadostest.DataManagerToken)
req.Header.Add("Content-Type", "application/octet-stream")
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
t.Fatalf("Error during %s %s", path, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error reading response from %s %s", path, err)
}
lines := strings.Split(string(body), "\n")
for _, line := range lines {
indexes = append(indexes, strings.Split(line, " ")...)
}
return indexes
}
示例10: get
// get take an http.Client pointer and URL and sends a GET request to the
// server.
func (c *Client) get(httpClient *http.Client, url string) (int, []byte, error) {
c.debugln("get(): Creating new request")
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 0, nil, err
}
if c.token != "" {
req.Header.Set("X-Cookie", "token="+c.token)
}
if c.accessKey != "" && c.secretKey != "" {
header := fmt.Sprintf("accessKey=%s; secretKey=%s;", c.accessKey, c.secretKey)
req.Header.Set("X-ApiKeys", header)
}
c.debugln("get(): Executing request")
resp, err := httpClient.Do(req)
if err != nil {
return resp.StatusCode, nil, err
}
defer resp.Body.Close()
c.debugln("get(): Reading body of response")
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, nil, err
}
return resp.StatusCode, body, err
}
示例11: postWithJSON
// postWithArgs takes an http.Client pointer, URL, and JSON byte array,
// sends a POST request to the server, and then returns the response body as a
// byte array with a nil error. Otherwise, the array will be nil and an error
// will be passed
func (c *Client) postWithJSON(httpClient *http.Client, url string, jsonStr []byte) (int, []byte, error) {
c.debugln("postWithJSON(): Creating new request")
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
return 0, nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.token != "" {
req.Header.Set("X-Cookie", "token="+c.token)
}
if c.accessKey != "" && c.secretKey != "" {
header := fmt.Sprintf("accessKey=%s; secretKey=%s;", c.accessKey, c.secretKey)
req.Header.Set("X-ApiKeys", header)
}
c.debugln("postWithJSON(): Executing request")
resp, err := httpClient.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
c.debugln("postWithJSON(): Reading body of response")
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, body, nil
}
示例12: HTTPComplexRequest
//HTTPComplexRequest allows more control over request options
func HTTPComplexRequest(c *HTTPRequestConfig) (*HTTPResponse, error) {
hresp := &HTTPResponse{}
req, err := http.NewRequest(c.Method, c.URL, c.Body)
if err != nil {
return hresp, err
}
for k, v := range c.Headers {
req.Header.Add(k, v)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: c.InsecureSkipTLSVerify},
}
hc := http.Client{
Transport: tr,
Timeout: time.Duration(c.TimeoutSeconds) * time.Second,
}
resp, err := hc.Do(req)
if err != nil {
return hresp, err
}
bs, bb, err := getRespBody(resp)
if err != nil {
return hresp, err
}
hresp.Body = bs
hresp.BodyBytes = bb
hresp.Resp = resp
if resp.StatusCode > 399 && c.FailOnError {
return hresp, fmt.Errorf("Server response indicates failure: %v %v", resp.StatusCode, bs)
}
return hresp, nil
}
示例13: user
// user queries the GitHub API for profile information using the provided client. The HTTP
// client is expected to be constructed by the golang.org/x/oauth2 package, which inserts
// a bearer token as part of the request.
func (c *githubConnector) user(ctx context.Context, client *http.Client) (user, error) {
var u user
req, err := http.NewRequest("GET", baseURL+"/user", nil)
if err != nil {
return u, fmt.Errorf("github: new req: %v", err)
}
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
return u, fmt.Errorf("github: get URL %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return u, fmt.Errorf("github: read body: %v", err)
}
return u, fmt.Errorf("%s: %s", resp.Status, body)
}
if err := json.NewDecoder(resp.Body).Decode(&u); err != nil {
return u, fmt.Errorf("failed to decode response: %v", err)
}
return u, nil
}
示例14: TestWatchHTTP
func TestWatchHTTP(t *testing.T) {
simpleStorage := &SimpleRESTStorage{}
handler := handle(map[string]rest.Storage{"simples": simpleStorage})
server := httptest.NewServer(handler)
defer server.Close()
client := http.Client{}
dest, _ := url.Parse(server.URL)
dest.Path = "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simples"
dest.RawQuery = ""
request, err := http.NewRequest("GET", dest.String(), nil)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := client.Do(request)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if response.StatusCode != http.StatusOK {
t.Errorf("Unexpected response %#v", response)
}
decoder := json.NewDecoder(response.Body)
for i, item := range watchTestTable {
// Send
simpleStorage.fakeWatch.Action(item.t, item.obj)
// Test receive
var got watchJSON
err := decoder.Decode(&got)
if err != nil {
t.Fatalf("%d: Unexpected error: %v", i, err)
}
if got.Type != item.t {
t.Errorf("%d: Unexpected type: %v", i, got.Type)
}
t.Logf("obj: %v", string(got.Object))
gotObj, err := codec.Decode(got.Object)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
t.Logf("obj: %#v", gotObj)
if _, err := api.GetReference(gotObj); err != nil {
t.Errorf("Unable to construct reference: %v", err)
}
if e, a := item.obj, gotObj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, got %#v", e, a)
}
}
simpleStorage.fakeWatch.Stop()
var got watchJSON
err = decoder.Decode(&got)
if err == nil {
t.Errorf("Unexpected non-error")
}
}
示例15: PublicKey
// PublicKey requests a shadowfax server's public key. An error is returned
// if the server URL is not https.
func PublicKey(serverURL string, client *http.Client) (*sf.PublicKey, error) {
u, err := url.Parse(serverURL)
if err != nil {
return nil, errgo.Mask(err, errgo.Any)
}
if u.Scheme != "https" {
return nil, errgo.Newf("public key must be requested with https")
}
if client == nil {
client = http.DefaultClient
}
req, err := http.NewRequest("GET", serverURL+"/publickey", nil)
if err != nil {
return nil, errgo.Mask(err)
}
resp, err := client.Do(req)
if err != nil {
return nil, errgo.Mask(err)
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var publicKeyResp wire.PublicKeyResponse
err = dec.Decode(&publicKeyResp)
if err != nil {
return nil, errgo.Mask(err)
}
publicKey, err := sf.DecodePublicKey(publicKeyResp.PublicKey)
if err != nil {
return nil, errgo.Mask(err)
}
return publicKey, nil
}