• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2016 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package gensupport
6
7import (
8	"errors"
9	"net/http"
10
11	"golang.org/x/net/context"
12	"golang.org/x/net/context/ctxhttp"
13)
14
15// Hook is the type of a function that is called once before each HTTP request
16// that is sent by a generated API.  It returns a function that is called after
17// the request returns.
18// Hooks are not called if the context is nil.
19type Hook func(ctx context.Context, req *http.Request) func(resp *http.Response)
20
21var hooks []Hook
22
23// RegisterHook registers a Hook to be called before each HTTP request by a
24// generated API.  Hooks are called in the order they are registered.  Each
25// hook can return a function; if it is non-nil, it is called after the HTTP
26// request returns.  These functions are called in the reverse order.
27// RegisterHook should not be called concurrently with itself or SendRequest.
28func RegisterHook(h Hook) {
29	hooks = append(hooks, h)
30}
31
32// SendRequest sends a single HTTP request using the given client.
33// If ctx is non-nil, it calls all hooks, then sends the request with
34// ctxhttp.Do, then calls any functions returned by the hooks in reverse order.
35func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
36	// Disallow Accept-Encoding because it interferes with the automatic gzip handling
37	// done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219.
38	if _, ok := req.Header["Accept-Encoding"]; ok {
39		return nil, errors.New("google api: custom Accept-Encoding headers not allowed")
40	}
41	if ctx == nil {
42		return client.Do(req)
43	}
44	// Call hooks in order of registration, store returned funcs.
45	post := make([]func(resp *http.Response), len(hooks))
46	for i, h := range hooks {
47		fn := h(ctx, req)
48		post[i] = fn
49	}
50
51	// Send request.
52	resp, err := ctxhttp.Do(ctx, client, req)
53
54	// Call returned funcs in reverse order.
55	for i := len(post) - 1; i >= 0; i-- {
56		if fn := post[i]; fn != nil {
57			fn(resp)
58		}
59	}
60	return resp, err
61}
62