food

package module
v0.0.0-...-f9122b7 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

food

The food tables the selfhostit apps share.

CI Go Reference

A small Go module that reads the food and product tables used by Troye (a calorie tracker) and Shoppa (a shopping list), and helps search them. It has no database code: each app stores the foods its own way and ranks search results by what matters to it.

  • Open Food Facts: reads the monthly export for a few countries (Belgium and the Netherlands for the apps), with names in English, Dutch and French, brand, package size, categories, a small photo and the nutrients when the product has them. Looks barcodes up live in Open Food Facts, Open Products Facts and Open Beauty Facts.
  • USDA FoodData Central: about 8,000 generic foods, bundled in data/.
  • NEVO: reads the RIVM download (CSV, Excel or the zip), which you download yourself.
  • Search helpers: accent-insensitive normalizing ("Pâté" finds "pate"), plural stemming in English, Dutch and French, and name scoring.
import "github.com/selfhostit/food"

c := food.Client{UserAgent: "Shoppa/1.0 (self-hosted shopping list)"}
p, err := c.Product(ctx, food.OpenFoodFacts, "5410000000001")

body, err := c.Export(ctx, food.OFFExportURL)
defer body.Close()
err = food.ReadExport(body, food.BelgiumNetherlands, func(p food.Food) error { … })

Open Food Facts asks every app to send a User-Agent that names it; set yours in Client.

Credits

Show these where the data is used:

  • Open Food Facts data: food.OFFAttribution (Open Database Licence); product photos: food.OFFPhotoAttribution (CC BY-SA 3.0)
  • USDA: food.USDAAttribution (public domain)
  • NEVO: food.NEVOAttribution. NEVO is free to use but can't be redistributed, so it is never bundled.

To rebuild the bundled USDA table from the FoodData Central CSV downloads:

go run ./cmd/usda FoodData_Central_sr_legacy_food_csv_2018-04.zip FoodData_Central_foundation_food_csv_2025-04-24.zip

Development

gofmt, go vet ./... and go test ./... must pass before every commit. A change here reaches an app when the app bumps the version in its go.mod; tag releases v0.x.y.

License

MIT. The bundled USDA data is in the public domain.

Documentation

Overview

Package food reads the food tables the selfhostit apps share, and helps search them:

  • Open Food Facts products: the monthly export, read for a few countries, and live barcode lookups (also in Open Products Facts and Open Beauty Facts, for things that aren't food)
  • USDA FoodData Central (SR Legacy and Foundation Foods), bundled, in the public domain
  • NEVO (RIVM, Netherlands), read from the download the owner uploads

It holds no database code: each app stores the foods its own way, and ranks search results by what matters to it.

Index

Constants

View Source
const (
	OFFAttribution      = "Open Food Facts, https://world.openfoodfacts.org (Open Database Licence)"
	OFFPhotoAttribution = "Product photos: Open Food Facts contributors, CC BY-SA 3.0"
)

The Open Food Facts credits. The data is under the Open Database Licence, the product photos under Creative Commons Attribution-ShareAlike.

View Source
const (
	OpenFoodFacts     = "https://world.openfoodfacts.org"
	OpenProductsFacts = "https://world.openproductsfacts.org"
	OpenBeautyFacts   = "https://world.openbeautyfacts.org"
)

The sites a barcode can be looked up in. They share one API: Open Food Facts has food, Open Products Facts other household products and Open Beauty Facts cosmetics.

View Source
const NEVOAttribution = "NEVO-online version 2025/9.0, RIVM, Bilthoven"

NEVOAttribution is the citation RIVM asks for wherever NEVO data is used.

View Source
const OFFExportURL = "https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz"

OFFExportURL is the monthly export of every Open Food Facts product, about a gigabyte compressed.

View Source
const USDAAttribution = "U.S. Department of Agriculture, Agricultural Research Service. FoodData Central. https://fdc.nal.usda.gov/ (public domain)"

USDAAttribution is shown with the USDA foods. The data is in the public domain; USDA asks to be cited.

Variables

View Source
var BarcodePattern = regexp.MustCompile(`^\d{6,14}$`)

BarcodePattern matches the barcodes products are kept by: 6 to 14 digits.

View Source
var BelgiumNetherlands = []string{"en:belgium", "en:netherlands"}

BelgiumNetherlands are the countries the selfhostit apps keep products for.

View Source
var ErrUnknownProduct = errors.New("unknown product")

ErrUnknownProduct means the site doesn't have the barcode, or has it without a name.

Functions

func CoversAll

func CoversAll(text string, words []string) bool

CoversAll reports whether every word of the normalized text is one of the words, or its plural: "rice" for "white rice", "apples" for "apple".

func FieldScore

func FieldScore(text string, words []string) float64

FieldScore rates how well one normalized name matches the words: each word found counts, more at the start of a word and more again as a whole word; a name that starts with the first word or holds every word counts extra.

func HasOtherWord

func HasOtherWord(name string, these, asked []string) bool

HasOtherWord reports whether the normalized name holds one of these words that wasn't asked for.

func Normalize

func Normalize(s string) string

Normalize lowercases s, drops accents and turns everything but letters and digits into single spaces, so "Pâté, de campagne" becomes "pate de campagne".

func Plausible

func Plausible(f Food) bool

Plausible leaves out foods whose values can't be right, which happens in a crowd-sourced database: more energy than pure fat, or more than 100 g of macronutrients in 100 g.

func ReadExport

func ReadExport(r io.Reader, countries []string, add func(Food) error) error

ReadExport reads the tab-separated export and hands add each product sold in one of the countries ("en:belgium") that has a barcode and a name. Those without nutrition come too, with Nutrition false; Plausible tells the products whose values can't be right.

func Stemmed

func Stemmed(words []string) []string

Stemmed drops common plural endings from the words, so "apples", "pommes" and "eieren" find "apple", "pomme" and "eier". It returns nil when no word had one.

func Words

func Words(q string) []string

Words splits a search into its normalized words, at most six.

Types

type Client

type Client struct {
	UserAgent string
	// HTTP makes the requests; nil means one with a 10 second timeout for
	// lookups, and no timeout for the export, which is read as it streams.
	HTTP *http.Client
}

Client asks Open Food Facts and its sister sites for products. UserAgent says which app is asking, as they ask apps to: "Troye/1.2 (self-hosted calorie tracker)".

func (Client) Export

func (c Client) Export(ctx context.Context, url string) (io.ReadCloser, error)

Export downloads the Open Food Facts export from url (usually OFFExportURL) and returns it uncompressed, to read as it streams in.

func (Client) Product

func (c Client) Product(ctx context.Context, site, code string) (Food, error)

Product looks a barcode up on one of the sites, such as OpenFoodFacts.

type Food

type Food struct {
	SourceID string `json:"id"`
	Name     string `json:"name"`
	NameNL   string `json:"name_nl,omitempty"`
	NameFR   string `json:"name_fr,omitempty"`
	Aliases  string `json:"aliases,omitempty"`
	Group    string `json:"group,omitempty"`
	Brand    string `json:"brand,omitempty"`
	Barcode  string `json:"barcode,omitempty"`

	// Products only: the package size ("1 L", "6 x 33 cl"), Open Food Facts'
	// category tags joined by commas, and the URL of a small photo of the
	// front, about 200 pixels high.
	Quantity   string `json:"quantity,omitempty"`
	Categories string `json:"categories,omitempty"`
	ImageURL   string `json:"image_url,omitempty"`

	// Nutrition is false for a product that gives no energy value, in which
	// case the values below are all zero.
	Nutrition bool    `json:"-"`
	Kcal      float64 `json:"kcal"`
	Protein   float64 `json:"protein"`
	Carbs     float64 `json:"carbs"`
	Fat       float64 `json:"fat"`
	Fiber     float64 `json:"fiber"`
	Sugar     float64 `json:"sugar"`
	Salt      float64 `json:"salt"`

	ServingG     float64 `json:"serving_g,omitempty"`
	ServingLabel string  `json:"serving_label,omitempty"`
}

Food is one food from a table, with its values per 100 g.

func USDARenamed

func USDARenamed(t Table) []Food

USDARenamed returns the foods of the table that the module renames, so an app can update them in a table it stored before they had those names.

type FormatError

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

FormatError means a file isn't the table it should be.

func (FormatError) Error

func (e FormatError) Error() string

type Table

type Table struct {
	Version string `json:"version"`
	Foods   []Food `json:"foods"`
}

Table is a food table: its edition and its foods.

func BundledUSDA

func BundledUSDA() (Table, error)

BundledUSDA reads the USDA table that ships with the module.

func ReadNEVO

func ReadNEVO(filename string, data []byte) (Table, error)

ReadNEVO reads the NEVO table from a CSV (any common delimiter), an Excel file, or a zip with either.

func ReadUSDA

func ReadUSDA(zipPaths ...string) (Table, error)

ReadUSDA reads FoodData Central CSV downloads (the SR Legacy and Foundation Foods zips): food.csv, food_nutrient.csv, food_category.csv and, for serving sizes, food_portion.csv. Foods without energy are left out. A food in more than one zip keeps the first.

Directories

Path Synopsis
cmd
usda command
Command usda turns the FoodData Central CSV downloads from fdc.nal.usda.gov (SR Legacy and Foundation Foods) into the table that ships with the module, data/usda.json.gz.
Command usda turns the FoodData Central CSV downloads from fdc.nal.usda.gov (SR Legacy and Foundation Foods) into the table that ships with the module, data/usda.json.gz.

Jump to

Keyboard shortcuts

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