Example #1
0
func main() {
	// Create a new client
	cli := gentleman.New()

	// Define a custom header
	cli.Use(headers.Set("Token", "s3cr3t"))

	// Create a request plugin to define the URL
	cli.Use(plugin.NewRequestPlugin(func(ctx *context.Context, h context.Handler) {
		u, _ := url.Parse("http://httpbin.org/headers")
		ctx.Request.URL = u
		h.Next(ctx)
	}))

	// Perform the request
	res, err := cli.Request().Send()
	if err != nil {
		fmt.Printf("Request error: %s\n", err)
		return
	}
	if !res.Ok {
		fmt.Printf("Invalid server response: %d\n", res.StatusCode)
		return
	}

	fmt.Printf("Status: %d\n", res.StatusCode)
	fmt.Printf("Body: %s", res.String())
}
Example #2
0
// SetMap sets a map of headers represented by key-value pair.
func SetMap(headers map[string]string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		for k, v := range headers {
			ctx.Request.Header.Set(k, v)
		}
		h.Next(ctx)
	})
}
Example #3
0
// Disable disables the authorization basic header in the outgoing request
func Disable() p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		// Assert http.Transport to work with the instance
		transport, ok := ctx.Client.Transport.(*http.Transport)
		if !ok {
			h.Next(ctx)
			return
		}

		// Override the http.Client transport
		transport.DisableCompression = true
		ctx.Client.Transport = transport

		h.Next(ctx)
	})
}
Example #4
0
// Basic defines an authorization basic header in the outgoing request
func Basic(username, password string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		ctx.Request.SetBasicAuth(username, password)
		h.Next(ctx)
	})
}
Example #5
0
// Custom defines a custom authorization header field in the outgoing request
func Custom(value string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		ctx.Request.Header.Set("Authorization", value)
		h.Next(ctx)
	})
}
Example #6
0
// Bearer defines an authorization bearer token header in the outgoing request
func Bearer(token string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		ctx.Request.Header.Set("Authorization", "Bearer "+token)
		h.Next(ctx)
	})
}
Example #7
0
// Set defines an authorization basic header in the outgoing request
func Set(name string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		defineType(name, ctx.Request)
		h.Next(ctx)
	})
}
Example #8
0
// Set sets the header entries associated with key to the single element value.
// It replaces any existing values associated with key.
func Set(key, value string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		ctx.Request.Header.Set(key, value)
		h.Next(ctx)
	})
}
Example #9
0
// Del deletes the header fields associated with key.
func Del(key string) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		ctx.Request.Header.Del(key)
		h.Next(ctx)
	})
}