webfonts

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2021 License: MIT Imports: 25 Imported by: 1

README

webfonts Go Package

Package webfonts provides a client for retrieving Google Webfonts.

Example

A basic Go example:

// _example/example.go
package main

import (
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path"
	"time"

	"github.com/kenshaw/diskcache"
	"github.com/kenshaw/httplog"
	"github.com/kenshaw/webfonts"
)

func main() {
	verbose := flag.Bool("v", false, "verbose")
	addr := flag.String("l", ":9090", "listen")
	key := flag.String("k", "", "webfonts key")
	prefix := flag.String("prefix", "/_/", "prefix")
	flag.Parse()
	if err := run(context.Background(), *verbose, *addr, *key, *prefix); err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
}

func run(ctx context.Context, verbose bool, addr, key, prefix string) error {
	// create cache transport
	cache, err := buildCache(verbose)
	if err != nil {
		return err
	}
	// retrieve all font faces
	fonts, err := webfonts.AllFontFaces(
		ctx,
		"Roboto",
		webfonts.WithTransport(cache),
		webfonts.WithKey(key),
	)
	if err != nil {
		return err
	}
	// create server and build routes
	s := newServer(prefix)
	if err := webfonts.BuildRoutes(prefix, fonts, s.build(ctx, cache)); err != nil {
		return err
	}
	// listen and serve
	l, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr)
	if err != nil {
		return err
	}
	return http.Serve(l, s)
}

// buildCache creates a disk cache transport.
func buildCache(verbose bool) (*diskcache.Cache, error) {
	opts := []diskcache.Option{
		diskcache.WithAppCacheDir("webfonts"),
		diskcache.WithTTL(24 * time.Hour),
		diskcache.WithHeaderWhitelist("Date", "Set-Cookie", "Content-Type", "Location"),
		diskcache.WithErrorTruncator(),
		diskcache.WithGzipCompression(),
	}
	if verbose {
		opts = append(opts, diskcache.WithTransport(
			httplog.NewPrefixedRoundTripLogger(
				http.DefaultTransport,
				fmt.Printf,
				httplog.WithReqResBody(false, false),
			),
		))
	}
	return diskcache.New(opts...)
}

type Server struct {
	*http.ServeMux
	prefix string
}

// newServer creates the server.
func newServer(prefix string) *Server {
	return &Server{
		ServeMux: http.NewServeMux(),
		prefix:   prefix,
	}
}

// build builds server routes.
func (s *Server) build(ctx context.Context, transport http.RoundTripper) func(string, []byte, []webfonts.Route) error {
	return func(family string, buf []byte, routes []webfonts.Route) error {
		// routes
		for _, route := range routes {
			// retrieve
			contentType, buf, err := get(ctx, route.URL, transport)
			if err != nil {
				return err
			}
			s.HandleFunc(path.Join(s.prefix, route.Path), func(res http.ResponseWriter, req *http.Request) {
				res.Header().Set("Content-Type", contentType)
				_, _ = res.Write(buf)
			})
		}
		// stylesheet
		stylesheetPath := path.Join(s.prefix, family) + ".css"
		s.HandleFunc(stylesheetPath, func(res http.ResponseWriter, req *http.Request) {
			res.Header().Set("Content-Type", "text/css")
			_, _ = res.Write(buf)
		})
		// index
		index := []byte(fmt.Sprintf(indexTemplate, stylesheetPath, family))
		s.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
			_, _ = res.Write(index)
		})
		return nil
	}
}

// get retrieves the url using the transport.
func get(ctx context.Context, urlstr string, transport http.RoundTripper) (string, []byte, error) {
	// request
	req, err := http.NewRequest("GET", urlstr, nil)
	if err != nil {
		return "", nil, err
	}
	cl := &http.Client{
		Transport: transport,
	}
	// execute
	res, err := cl.Do(req.WithContext(ctx))
	if err != nil {
		return "", nil, err
	}
	defer res.Body.Close()
	buf, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", nil, err
	}
	return res.Header.Get("Content-Type"), buf, nil
}

const indexTemplate = `<html>
<head>
<link rel="stylesheet" href="%s">
</head>
<body>
<div style="font-family: %s">
lorem ipsum dolor
</div>
</body>
</html>`

Documentation

Overview

Package webfonts provides client for the google webfonts helper and a way to easily retrieve and serve webfonts.

Index

Constants

This section is empty.

Variables

View Source
var DefaultTransport = http.DefaultTransport

DefaultTransport is the default http transport.

Functions

func Available

func Available(ctx context.Context, opts ...ClientOption) ([]*gfonts.Webfont, error)

Available retrieves all available webfonts.

func BuildRoutes

func BuildRoutes(prefix string, fonts []FontFace, h func(string, []byte, []Route) error) error

BuildRoutes builds routes for the provided font faces.

Types

type Client

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

Client is a webfonts client.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new webfonts client.

func (*Client) AllFontFaces

func (cl *Client) AllFontFaces(ctx context.Context, family string, opts ...QueryOption) ([]FontFace, error)

AllFontFaces retrieves all font faces for the specified family by using multiple user agents.

func (*Client) Available

func (cl *Client) Available(ctx context.Context) ([]*gfonts.Webfont, error)

Available retrieves all available webfonts.

func (*Client) FontFaces

func (cl *Client) FontFaces(ctx context.Context, family string, opts ...QueryOption) ([]FontFace, error)

FontFaces retrieves the font faces for the specified family.

type ClientOption

type ClientOption func(*Client)

ClientOption is a webfonts client option.

func WithAppCacheDir

func WithAppCacheDir(appCacheDir string) ClientOption

WithAppCacheDir is a webfonts client option to set the app cache dir.

func WithClientOption

func WithClientOption(opt option.ClientOption) ClientOption

WithClientOption is a webfonts client option to set underlying client options.

func WithKey

func WithKey(key string) ClientOption

WithKey is a webfonts client option to set the webfonts api key.

func WithLogf

func WithLogf(logf interface{}, opts ...httplog.Option) ClientOption

WithLogf is a webfonts client option to set a log handler for http requests and responses.

func WithTokenSource

func WithTokenSource(source oauth2.TokenSource) ClientOption

WithTokenSource is a webfonts client option to set the token source.

func WithTransport

func WithTransport(transport http.RoundTripper) ClientOption

WithTransport is a webfonts client option to set the http transport.

type FontFace

type FontFace struct {
	Subset string   `json:"subset,omitempty"`
	Family string   `json:"font-family,omitempty"`
	Style  string   `json:"font-style,omitempty"`
	Weight string   `json:"font-weight,omitempty"`
	Src    string   `json:"src,omitempty"`
	Format string   `json:"format,omitempty"`
	Range  []string `json:"unicode-range,omitempty"`
}

FontFace describes a font face.

func AllFontFaces

func AllFontFaces(ctx context.Context, family string, opts ...ClientOption) ([]FontFace, error)

AllFontFaces retrieves all font faces for the specified family by using multiple user agents.

func FontFaces

func FontFaces(ctx context.Context, family string, opts ...ClientOption) ([]FontFace, error)

FontFaces retrieves the font faces for the specified family.

func FontFacesFromStylesheetReader

func FontFacesFromStylesheetReader(r io.Reader) ([]FontFace, error)

FontFacesFromStylesheetReader parses stylesheet from the passed reader, returning any encountered font face.

type Query

type Query struct {
	Family    string
	UserAgent string
	Variants  []string
	Subsets   []string
	Styles    []string
	Effects   []string
}

Query wraps a font request.

func NewQuery

func NewQuery(family string, opts ...QueryOption) *Query

NewQuery builds a new webfont query.

func (*Query) String

func (q *Query) String() string

String satisfies the fmt.Stringer interface.

Returns the URL for the request.

func (*Query) Values

func (q *Query) Values() url.Values

Values returns the url values for the request.

type QueryOption

type QueryOption func(*Query)

QueryOption is a webfonts query option.

func WithEffects

func WithEffects(effects ...string) QueryOption

WithEffects is a query option to set effects.

func WithStyles

func WithStyles(styles ...string) QueryOption

WithStyles is a query option to set styles.

func WithSubsets

func WithSubsets(subsets ...string) QueryOption

WithSubsets is a query option to set subsets.

func WithUserAgent

func WithUserAgent(userAgent string) QueryOption

WithUserAgent is a query option to set the user agent.

func WithVariants

func WithVariants(variants ...string) QueryOption

WithVariants is a query option to set variants.

type Route

type Route struct {
	Path string
	URL  string
}

Route wraps information about a route. Used for callbacks passed to BuildRoutes.

Directories

Path Synopsis
_example/example.go
_example/example.go

Jump to

Keyboard shortcuts

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