imgix

package module
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2020 License: BSD-2-Clause Imports: 11 Imported by: 0

README

imgix logo

imgix-go is a client library for generating image URLs with imgix.

Version Build Status Godoc License


Installation

go get github.com/imgix/imgix-go

Usage

To begin creating imgix URLs, import the imgix library and create a URL builder. The URL builder can be reused to create URLs for any images on the domain it is provided.

package main

import (
    "fmt"
    "net/url"
    "github.com/imgix/imgix-go"
)

func main() {
    ub := NewURLBuilder("demo.imgix.net", WithLibParam(false))
    ixUrl := ub.CreateURL("path/to/image.jpg")
    // ixUrl == "https://demo.imgix.net/path/to/image.jpg"
}
ub := NewURLBuilder("demo.imgix.net", WithLibParam(false))
ixURL := ub.CreateURL("path/to/image.jpg", Param("w", "320"), Param("auto", "format", "compress"))
// https://demo.imgix.net/path/to/image.jpg?auto=format%2Ccompress&w=320

HTTPS support is enabled by default. HTTP can be toggled on by setting useHTTPS to false. This can be done in one of two ways:

// Either by specifying an option at time of construction:
ub := NewURLBuilder("demo.imgix.net", WithHTTPS(false))
// Or by using the SetUseHTTPS method.
ub := NewURLBuilder("demo.imgix.net")
ub.SetUseHTTPS(false)
ub.CreateURL("path/to/image.jpg")
// "http://demo.imgix.net/path/to/image.jpg"

Secure and Sign URLs

To produce a secure URL, you must enable Secure URLs on your source and then provide your token to the URL builder. The builder will use this token to sign your URL––thus securing the URL against tampering or alterations made by anyone without access to your token.

Note that due to the way signing secures URLs by "locking" them in their generated state, it's required that a URL be re-signed and secured after any modifications (e.g. updating parameters, path, etc.). Fortunately, our SDK will handle re-signing automatically.

First, be sure to keep your token a secret.

.env

IX_TOKEN="token"

main.go

package main

import (
	"log"
	"net/url"
	"os"

	"github.com/joho/godotenv"
	"github.com/imgix/imgix-go"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	ixToken := os.Getenv("IX_TOKEN")
	ub := NewURLBuilder("demo.imgix.net", WithToken(ixToken), WithLibParam(false))

	expected := "https://demo.imgix.net/path/to/image.jpg?s=5dde0b0e48067925082d670d0e987fcb"
	actual := ub.CreateURL("path/to/image.jpg")
}

Srcset Generation

The imgix-go package allows for generation of custom srcset attributes, which can be invoked through the CreateSrcset method. By default, the generated srcset will allow for responsive size switching by building a list of image-width mappings.

ub := NewURLBuilder("demos.imgix.net", WithToken(token))
srcset := ub.CreateSrcset("image.png", []IxParam{})

The above will produce the following srcset attribute value, which can then be served to the client:

https://demos.imgix.net/image.png?w=100&s=9abb0d0db5a4901fcb6420a1a37efe5d 100w,
https://demos.imgix.net/image.png?w=116&s=cfea3b9598400fdb5dd273c50a666116 116w,
https://demos.imgix.net/image.png?w=135&s=e749702260debafa9aa71e55524b39ee 135w,
https://demos.imgix.net/image.png?w=156&s=0fb6a5f27dfece682320b73c466e1e39 156w,
...
https://demos.imgix.net/image.png?w=7401&s=3b2fbb6aa880a260ba650dc773d47216 7401w,
https://demos.imgix.net/image.png?w=8192&s=1288314bbb33a4f441100b899dd67a00 8192w

Fixed-Width Images

In cases where enough information is provided about an image's dimensions, CreateSrcset will build a srcset that will allow for an image to be served at different resolutions. The parameters taken into consideration when determining if an image is fixed-width are w, h, and ar.

By invoking CreateSrcset with either a width or the height and aspect ratio in the parameters, a fixed-width srcset will be generated. Wherein, the image width is fixed, but the pixel density varies.

ub := NewURLBuilder("demo.imgix.net", WithLibParam(false))
params := []IxParam{Param("h", "800"), Param("ar", "4:3")}
ub.CreateSrcset("image.png", params)

Will produce the following attribute value:

https://demo.imgix.net/image.png?ar=4%3A3&dpr=1&h=800&q=75 1x
https://demo.imgix.net/image.png?ar=4%3A3&dpr=2&h=800&q=50 2x
https://demo.imgix.net/image.png?ar=4%3A3&dpr=3&h=800&q=35 3x
https://demo.imgix.net/image.png?ar=4%3A3&dpr=4&h=800&q=23 4x
https://demo.imgix.net/image.png?ar=4%3A3&dpr=5&h=800&q=20 5x

For more information to better understand srcset, we highly recommend Eric Portis' "Srcset and sizes" article which goes into depth about the subject.

Variable Quality

This library will automatically append a variable q parameter mapped to each dpr parameter when generating a fixed-width image srcset. This technique is commonly used to compensate for the increased file size of high-DPR images.

Since high-DPR images are displayed at a higher pixel density on devices, image quality can be lowered to reduce overall file size without sacrificing perceived visual quality. For more information and examples of this technique in action, see this blog post.

This behavior will respect any overriding q value passed in as a parameter. Additionally, it can be disabled by passing the WithVariableQuality(false) SrcsetOption.

ub := NewURLBuilder("test.imgix.net")

params := []IxParam{Param("h", "800"), Param("ar", "4:3"), Param("q", "99")}
ub.CreateSrcset("image.png", params, WithVariableQuality(false))
https://test.imgix.net/image.png?ar=4%3A3&dpr=1&h=800&q=99 1x,
https://test.imgix.net/image.png?ar=4%3A3&dpr=2&h=800&q=99 2x,
https://test.imgix.net/image.png?ar=4%3A3&dpr=3&h=800&q=99 3x,
https://test.imgix.net/image.png?ar=4%3A3&dpr=4&h=800&q=99 4x,
https://test.imgix.net/image.png?ar=4%3A3&dpr=5&h=800&q=99 5x"

Fluid-Width Images

Custom Widths

In situations where specific widths are desired when generating srcset pairs, a user can specify them by passing an array of positive integers to CreateSrcsetFromWidths:

ub := NewURLBuilder("demo.imgix.net")
ixParams = []IxParam{Param("mask", "ellipse")}
srcset := ub.CreateSrcsetFromWidths("image.jpg", ixParams, []int{100, 200, 300, 400})
https://demo.imgix.net/image.jpg?mask=ellipse&w=100 100w,
https://demo.imgix.net/image.jpg?mask=ellipse&w=200 200w,
https://demo.imgix.net/image.jpg?mask=ellipse&w=300 300w,
https://demo.imgix.net/image.jpg?mask=ellipse&w=400 400w
Width Ranges

In certain circumstances, you may want to limit the minimum or maximum value of the non-fixed srcset generated by the CreateSrcset method. To do this, you can specify the minWidth and maxWidth by including each as a SrcsetOption:

ub := NewURLBuilder("demo.imgix.net", WithLibParam(false))

srcset := ub.CreateSrcset(
	"image.png",
	[]IxParam{},
	WithMinWidth(100),
	WithMaxWidth(380))
https://demo.imgix.net/image.png?w=100 100w,
https://demo.imgix.net/image.png?w=116 116w,
https://demo.imgix.net/image.png?w=135 135w,
https://demo.imgix.net/image.png?w=156 156w,
https://demo.imgix.net/image.png?w=181 181w,
https://demo.imgix.net/image.png?w=210 210w,
https://demo.imgix.net/image.png?w=244 244w,
https://demo.imgix.net/image.png?w=283 283w,
https://demo.imgix.net/image.png?w=328 328w,
https://demo.imgix.net/image.png?w=380 380w
Width Tolerance

The srcset width tolerance (tol) dictates the maximum tolerated difference between an image's downloaded size and its rendered size.

For example, setting this value to 0.10 means that an image will not render more than 10% larger or smaller than its native size. In practice, the image URLs generated for a width-based srcset attribute will grow by twice this rate.

A lower tolerance means images will render closer to their native size (thereby increasing perceived image quality), but a large srcset list will be generated and consequently users may experience lower rates of cache-hit for pre-rendered images on your site.

By default, srcset width tolerance is set to 0.08 (8 percent), which we consider to be the ideal rate for maximizing cache hits without sacrificing visual quality. Users can specify their own width tolerance by providing a positive scalar value as width tolerance.

In this case, the width tolerance is set to 20 percent:

srcsetOptions := []SrcsetOption{
	WithMinWidth(100),
	WithMaxWidth(384),
	WithTolerance(0.20),
}

srcset := ub.CreateSrcset("image.png", []IxParam{}, srcsetOptions...)
https://demo.imgix.net/image.jpg?w=100 100w,
https://demo.imgix.net/image.jpg?w=140 140w,
https://demo.imgix.net/image.jpg?w=196 196w,
https://demo.imgix.net/image.jpg?w=274 274w,
https://demo.imgix.net/image.jpg?w=384 384w
Explore Target Widths

The TargetWidths function is used internally to generate lists of target widths to be used in calls to CreateSrcset.

It is a way to generate, play with, and explore different target widths separately from srcset attributes. We've already seen how to generate srcset attributes when the minWidth, maxWidth, and tolerance values are known.

Another approach is to use TargetWidths to determine which combination of values for minWidth, maxWidth, and tolerance works best.

// Create
widths := TargetWidths(300, 3000, 0.13)

// Explore
sm := widths[:3]
expectedSm := []int{300, 378, 476}
assert.Equal(t, expectedSm, sm)

md := widths[3:7]
expectedMd := []int{600, 756, 953, 1200}
assert.Equal(t, expectedMd, md)

lg := widths[7:]
expectedLg := []int{1513, 1906, 2401, 3000}
assert.Equal(t, expectedLg, lg)

// Serve
ub := NewURLBuilder("demos.imgix.net")
srcset := ub.CreateSrcsetFromWidths("image.png", []IxParam{}, sm)
// "https://demos.imgix.net/image.png?w=300 300w,\nhttps://demos.imgix.net/image.png?w=378 378w,\nhttps://demos.imgix.net/image.png?w=476 476w"

The ixlib Parameter

For security and diagnostic purposes, we sign all requests with the language and version of library used to generate the URL.

The ixlib parameter can be toggled off by setting useLibParam via SetUseLibParam:

ub := NewURLBuilder("demo.imgix.net")
ub.SetUseLibParam(false)

Or by passing the WithLibParam(false) option at time of construction:

ub := NewURLBuilder("demo.imgix.net", WithLibParam(false))

Testing

You can go test this code with:

$ go test

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultWidths = []int{
	100, 116, 135, 156,
	181, 210, 244, 283,
	328, 380, 441, 512,
	594, 689, 799, 927,
	1075, 1247, 1446, 1678,
	1946, 2257, 2619, 3038,
	3524, 4087, 4741, 5500,
	6380, 7401, 8192}

DefaultWidths is an array of image widths generated by calling TargetWidths(100, 8192, 0.08). These defaults are quite good, cover a wide range of widths, and are easy to start with.

Functions

func TargetWidths

func TargetWidths(minWidth int, maxWidth int, tolerance float64) []int

TargetWidths creates an array of integer image widths. The image widths begin at the minWidth value and end at the maxWidth value––with a defaultTolerance amount of tolerable image width-variance between them.

Types

type BuilderOption

type BuilderOption func(b *URLBuilder)

BuilderOption provides a convenient interface for supplying URLBuilder options to the NewURLBuilder constructor. See WithToken, WithHTTPS, etc. for more details.

func WithHTTPS

func WithHTTPS(useHTTPS bool) BuilderOption

WithHTTPS returns a BuilderOption that NewURLBuilder consumes. The constructor uses this closure to set the URLBuilder's useHTTPS attribute.

func WithLibParam

func WithLibParam(useLibParam bool) BuilderOption

WithLibParam returns a BuilderOption that NewURLBuilder consumes. The constructor uses this closure to set the URLBuilder's useLibParam attribute.

func WithToken

func WithToken(token string) BuilderOption

WithToken returns a BuilderOption that NewURLBuilder consumes. The constructor uses this closure to set the URLBuilder's token attribute.

type IxParam

type IxParam func(u *url.Values)

IxParam seeks to improve the ergonomics of setting url.Values. For instance, without IxParam, caller's would need to write: url.Values{"w": []string{"480"}, "auto": []string{"format", "compress"}} However, by employing this functional type we can write: []IxParam{Param("w", "480"), Param("auto", "format", "compress")}

func Param

func Param(k string, v ...string) IxParam

Param accepts a key and a variable number of values. It returns a closure as an IxParam that, once called, will populate the url.Values structure. Note that values aren't added to the query parameters (url.Values) until this function is applied (e.g. in CreateURL).

type SrcsetOption

type SrcsetOption func(opt *SrcsetOpts)

func WithMaxWidth

func WithMaxWidth(maxWidth int) SrcsetOption

func WithMinWidth

func WithMinWidth(minWidth int) SrcsetOption

func WithTolerance

func WithTolerance(tolerance float64) SrcsetOption

func WithVariableQuality

func WithVariableQuality(variableQuality bool) SrcsetOption

type SrcsetOpts

type SrcsetOpts struct {
	// contains filtered or unexported fields
}

type URLBuilder

type URLBuilder struct {
	// contains filtered or unexported fields
}

URLBuilder facilitates the building of imgix URLs.

func NewURLBuilder

func NewURLBuilder(domain string, options ...BuilderOption) URLBuilder

NewURLBuilder creates a new URLBuilder with the given domain, with HTTPS enabled.

func (*URLBuilder) CreateSrcset

func (b *URLBuilder) CreateSrcset(
	path string,
	params []IxParam,
	options ...SrcsetOption) string

CreateSrcset creates a srcset attribute string. Given a path, set of IxParam parameters, and a set of SrcsetOptions, this function infers which kind of srcset attribute to create.

If the params contain a width parameter or both height and aspect ratio parameters, a fixed-width srcset attribute will be created. This fixed-width srcset attribute will be dpr-based and have variable quality enabled by default. Variable quality can be disabled by passing WithVariableQuality(false).

Otherwise if no explicit width, height, or aspect ratio were found this function will create a fluid-width srcset attribute wherein each URL (or image candidate string) is described by a width in the specified width-range.

func (*URLBuilder) CreateSrcsetFromWidths

func (b *URLBuilder) CreateSrcsetFromWidths(path string, params []IxParam, widths []int) string

CreateSrcsetFromWidths takes a path, a set of params, and an array of widths to create a srcset attribute with width-described URLs (image candidate strings).

func (*URLBuilder) CreateURL

func (b *URLBuilder) CreateURL(path string, params ...IxParam) string

CreateURL creates a URL string given a path and a set of params.

func (*URLBuilder) Domain

func (b *URLBuilder) Domain() string

Domain gets the builder's domain string.

func (*URLBuilder) Scheme

func (b *URLBuilder) Scheme() string

Scheme gets the URL scheme to use, either "http" or "https" (the scheme uses HTTPS by default).

func (*URLBuilder) SetToken

func (b *URLBuilder) SetToken(token string)

SetToken sets the token for this builder. This value will be used to sign URLs created through the builder.

func (*URLBuilder) SetUseHTTPS

func (b *URLBuilder) SetUseHTTPS(useHTTPS bool)

SetUseHTTPS sets a builder's useHTTPS field to true or false. Setting useHTTPS to false forces the builder to use HTTP.

func (*URLBuilder) SetUseLibParam

func (b *URLBuilder) SetUseLibParam(useLibParam bool)

SetUseLibParam toggles the library param on and off. If useLibParam is set to true, the ixlib param will be toggled on. Otherwise, if useLibParam is set to false, the ixlib param will be toggled off and will not appear in the final URL.

func (*URLBuilder) UseHTTPS

func (b *URLBuilder) UseHTTPS() bool

UseHTTPS returns whether HTTPS or HTTP should be used.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL