Fonts is a package that provides helpers to access font details and easily retrive font bytes with ZERO dependencies

Fonts

Fonts is a package that provides helpers to access font details and easily retrieve font bytes.

This package has ZERO 3rd-party dependencies.

For now, Google Fonts is supported, but other fonts are planned.

Motivation

When working with images, PDFs or any other format that requires us to embed fonts, we can decide to download the fonts and embed them directly into our application.

However, if our application could use multiple different fonts which are decided at runtime, then there are a couple complications:

  1. There is no easy way to know what fonts are available and what variants they have. Google Fonts provides an API, but you can only receive a dump all FONT details.
  2. It becomes tedious to download the font bytes during runtime, and manage caching.

This package helps to simplify this process

Reference

See https://pkg.go.dev/github.com/go-swiss/fonts

How to use

Get Font Details

To get the details of a Google Font, use the GetFontDetails function:

package main 

import (
    "fmt"
    "context"

    "github.com/go-swiss/fonts/google"
)

func main() {
    ctx := context.Background()
    details, err := google.GetFontDetails(ctx, "Roboto")
    if err != nil {
        panic(err)
    }

    fmt.Printf("Family: %s\nVariants: %v", details.Family, details.Variants)
}
Family: Roboto
Variants: [100 100italic 300 300italic regular italic 500 500italic 700 700italic 900 900italic]

Get Font Bytes

To get the bytes of a font, use the GetFontBytes method. This will download the font bytes from the appropriate URL.

family := "Open Sans"
variant := "900"

fontBytes, err := google.GetFontBytes(ctx, family, variant, nil)
if errors.Is(err, fonts.ErrMissingVariant) {
    fontBytes, err = google.GetFontBytes(ctx, family, "regular", nil)
}

if err != nil {
    panic(err)
}

font, err := opentype.Parse(fontBytes)
if err != nil {
    panic(err)
}

// Do something with the font

Caching Responses

In our application it is possible that we need to frequetnly get fonts. To reduce duplicate requests, a fonts.Cache implementation can be passed as the 4th parameter to the GetFontBytes function.

Here is an example using https://github.com/ReneKroon/ttlcache

package main 

import (
    "time"

    "github.com/ReneKroon/ttlcache/v2"
)

type cache struct {
	c *ttlcache.Cache
}

func (c cache) Get(key string) ([]byte, bool) {
	fontInterface, err := c.c.Get(key)
	if err != nil {
		return nil, false
	}

	fontBytes, ok := fontInterface.([]byte)
	return fontBytes, ok
}

func (c cache) Set(key string, val []byte) {
	c.c.Set(key, val)
}

func main() {
	c := ttlcache.NewCache()
	c.SetTTL(time.Duration(20 * time.Second))
	c.SetCacheSizeLimit(64)

    fontBytes, err := google.GetFontBytes(config.Context, family, variant, cache{c})
    if err != nil {
        panic(err)
    }

    font, err := opentype.Parse(fontBytes)
    if err != nil {
        panic(err)
    }

    // Do something with the font
}

Contributing

Feature requests and Pull Requests are welcome!

If working locally, the google/all directory can be refreshed by running go generate. See generate/main.go for details.

Similar Resources

A CLI tool to display all dependencies or dependents of an object in a Kubernetes cluster.

kube-lineage A CLI tool to display all dependencies or dependents of an object in a Kubernetes cluster. Usage $ kube-lineage clusterrole system:metric

Jan 5, 2023

Godbolt console wrapper for easily execute local file without any security risk and compiler.

Godbolt CLI Godbolt console wrapper for easily execute local file without any security risk and compiler. Install Compile the source code and add to y

May 22, 2022

a Go language free and open-source document for learning from zero level

Go document a GO language free and open-source document for learning from zero level Please publish and collaborate OPEN-SOURCE Sections About go lang

Jan 8, 2023

A CLI Tool to easily generate your Terraform configuration

Tf Tf is a command line tool to easily generate your Terraform configuration with an interactive prompt. Inspiration Boredom in Covid-19 Installation

Sep 30, 2022

📝 Easily format yaml files on terminal or your editor

YAMLFMT A simple and extensible yaml formatter. Installation go install github.com/UltiRequiem/yamlfmt@latest Make sure your $PATH includes the $GOPAT

Oct 31, 2022

Easily manage your work via command line

Wo Easily manage your work via command line Introduction Wo, is cli that provides it easy to manage your workspace. Wo provides to manipulating workfl

Dec 11, 2021

Issue-mafia - An out-of-the-box CLI that helps you to easily synchronize Git hooks with a remote repository

issue-mafia is an out-of-the-box CLI that helps you to easily synchronize Git hooks with a remote repository.

Feb 14, 2022

Package osargs provides functions to parse command line arguments

osargs About Package osargs provides functions to parse command line arguments. It is published on https://github.com/vbsw/osargs and https://gitlab.c

May 8, 2022

CLI criada no curso Aprenda Golang do Zero! Desenvolva uma APLICAÇÃO COMPLETA!

go-cli CLI criada no curso Aprenda Golang do Zero! Desenvolva uma APLICAÇÃO COMPLETA! Este projeto utiliza o pacote Urfave CLI. Para utiliza-lo basta

Jan 10, 2022
Comments
  • BUG: invalid directory separator

    BUG: invalid directory separator

    In GetFontDetails and GetFontBytes, the font is being loaded by this code:

    jsonFile, err := all.ReadFile(filepath.Join("all", normalizedFamilyName+".json"))

    The problem here is that the all is an embed.FS which has hardcoded forward slash as directory separator. But filepath.Join will use the os.PathSeparator which will be backward slash on windows and that will result in file not found error.

    Due to this fact, this library does not work on Windows OS. The solution here is to simply use: jsonFile, err := all.ReadFile("all/" + normalizedFamilyName+".json")

    obrázok

    Ref: https://github.com/stephenafamo/goldmark-pdf/issues/3

Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.

dasel Dasel (short for data-selector) allows you to query and modify data structures using selector strings. Comparable to jq / yq, but supports JSON,

Jan 2, 2023
word2text - a tool is to convert word documents (DocX) to text on the CLI with zero dependencies for free
word2text - a tool is to convert word documents (DocX) to text on the CLI with zero dependencies for free

This tool is to convert word documents (DocX) to text on the CLI with zero dependencies for free. This tool has been tested on: - Linux 32bit and 64 bit - Windows 32 bit and 64 bit - OpenBSD 64 bit

Apr 19, 2021
yq lets you read YAML files easily on the terminal. You can find key/values easily
yq lets you read YAML files easily on the terminal. You can find key/values easily

yq yq lets you read YAML files easily on the terminal. You can find key/values easily. Motivation Reading yaml configurations for k8s file becomes ard

Nov 2, 2021
OTF font with vertical bars for one-line ASCII spectrum analyzers, graphs, etc
OTF font with vertical bars for one-line ASCII spectrum analyzers, graphs, etc

graph-bars-font OTF font with vertical bars for one-line ASCII spectrum analyzers, graphs, etc. I didn't find anything similar on the net so I decided

Jul 28, 2022
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Jan 1, 2023
Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.
Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.

asciigraph Go package to make lightweight ASCII line graphs ╭┈╯. Installation go get github.com/guptarohit/asciigraph Usage Basic graph package main

Jan 8, 2023
Clones dependencies from .resolved file of Swift Package Manager.

SPM-dep-cloner Clones dependencies from .resolved file of Swift Package Manager. Useful for setup of new project with dependencies in another repos. H

Nov 29, 2021
gomUP is a tool to keep track of outdated dependencies and upgrade them to the latest version
gomUP is a tool to keep track of outdated dependencies and upgrade them to the latest version

gomUP ?? gomUP is a tool to keep track of outdated dependencies and upgrade them to the latest version. Designed for monorepo Go projects and Go proje

Jul 26, 2022
An os/exec like interface for running a command in a container, and being able to easily interact with stdin, stdout, and other adjustments

dockerexec An "os/exec" like interface for running a command in a container, and being able to easily interact with stdin, stdout, and other adjustmen

Jul 14, 2022
gif effects CLI. single binary, no dependencies. linux, osx, windows.
gif effects CLI. single binary, no dependencies. linux, osx, windows.

yeetgif Composable GIF effects CLI, with reasonable defaults. Made for custom Slack/Discord emoji :) Get it Alternative 1: go get Alternative 2: just

Dec 11, 2022