openfoodfacts-go: github.com/openfoodfacts/openfoodfacts-go Index | Examples | Files

package openfoodfacts

import "github.com/openfoodfacts/openfoodfacts-go"

This is a go library used to access the OpenFoodFacts.org database for food product, ingredients and nutritional data from within your go application.

The main method of using this library is to create a DataOperator and call methods on it.

Create a DataOperator to retrieve and modify database items. HttpApi is a DataOperator that interacts with the official HTTP API from openfoodfacts.org.

Code:

NewHttpApiOperator("world", "", "")

Index

Examples

Package Files

data_operator.go epoch_time.go http_api.go ingredient.go nutrient_level.go nutriment.go product.go product_result.go url_string.go

Variables

var (
    // ProductRetrievalError is an error returned by DataOperator.GetProduct when the product could not be
    // retrieved successfully, it is not a transient error, the product does not exist.
    ProductRetrievalError = errors.New("Product retrieval failure")

    // AnonymousUserError is an error returned by DataOperator methods that require a valid user account, but none
    // was provided when the operator was instantiated.
    AnonymousUserError = errors.New("Action requires user account")
)

type DataOperator Uses

type DataOperator interface {
    // GetProduct will return a pointer to a Product, given a item code.
    GetProduct(code string) (*Product, error)
}

A DataOperator is capable of retrieving details of food items from a database and modifying them. Typically this will be either from the official OpenFoodFacts API, a local database, or may be some form of caching layer above one of these other methods.

HttpApi is an example of a DataOperator that uses the OpenFoodFacts web API.

func NewHttpApiOperator Uses

func NewHttpApiOperator(locale, username, password string) DataOperator

NewHttpApiOperator returns a DataOperator that is capable of talking to the official OpenFoodFacts database via the HTTP API, or the dev server if live is false.

The locale should be one of "world" or the country level code for the locale you wish to use.

The username and password should be set to your OpenFoodFacts credentials if you need WRITE access, else provide them both as empty strings for anonymous access.

Sandbox mode

If you are testing your application, you should use the test server in order to use the sandbox environment instead of the live servers. See the Sandbox() method for more detail and an example.

type EpochTime Uses

type EpochTime struct {
    time.Time
}

EpochTime allows the proper un/marshaling of a seconds-since-epoch value from JSON.

func (*EpochTime) IsSet Uses

func (t *EpochTime) IsSet() bool

IsSet allows testing if the value was set. If it is empty, it will return false.

func (*EpochTime) MarshalJSON Uses

func (t *EpochTime) MarshalJSON() ([]byte, error)

func (*EpochTime) UnmarshalJSON Uses

func (t *EpochTime) UnmarshalJSON(b []byte) (err error)

type HttpApi Uses

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

HttpApi is a DataOperator that uses the official API for it's data source.

func (*HttpApi) GetProduct Uses

func (h *HttpApi) GetProduct(code string) (*Product, error)

GetProduct returns a new Product for the given code, retrieved from the server.

It will return an error on a failed retrieval, if the retrieval is successful but the API result status is not 1, then will return a "ProductRetrievalError" error. This indicates the product is not available.

You can use the GetProduct method to retrieve a Product by barcode.

Code:

api := NewHttpApiOperator("world", "", "")
product, err := api.GetProduct("5201051001076")
if err != nil {
    fmt.Printf("%+v\n", product)
}

func (*HttpApi) Sandbox Uses

func (h *HttpApi) Sandbox()

Sandbox configures this operator to use the sandbox server at http://world.openfoodfacts.net instead of the live server. This is used for testing purposes instead of operating on the live server.

This will enable test mode and connect you to the sandbox server.

Code:

api := NewHttpApiOperator("world", "", "")
api.(*HttpApi).Sandbox() // Enable test mode

type Ingredient Uses

type Ingredient struct {
    ID   string `json:"id"`
    Rank int    `json:"rank,omitempty"`
    Text string `json:"text"`
}

type NutrientLevel Uses

type NutrientLevel struct {
    Sugars       string `json:"sugars"`
    SaturatedFat string `json:"saturated-fat"`
    Fat          string `json:"fat"`
    Salt         string `json:"salt"`
}

type Nutriment Uses

type Nutriment struct {
    Carbohydrates        json.Number `json:"carbohydrates"`
    Carbohydrates100G    json.Number `json:"carbohydrates_100g"`
    CarbohydratesServing json.Number `json:"carbohydrates_serving"`
    CarbohydratesUnit    string      `json:"carbohydrates_unit"`
    Energy               json.Number `json:"energy"`
    Energy100G           json.Number `json:"energy_100g"`
    EnergyServing        json.Number `json:"energy_serving"`
    EnergyUnit           string      `json:"energy_unit"`
    Fat                  json.Number `json:"fat"`
    Fat100G              json.Number `json:"fat_100g"`
    FatServing           json.Number `json:"fat_serving"`
    FatUnit              string      `json:"fat_unit"`
    Fiber                json.Number `json:"fiber"`
    Fiber100G            json.Number `json:"fiber_100g"`
    FiberServing         json.Number `json:"fiber_serving"`
    FiberUnit            string      `json:"fiber_unit"`
    Proteins             json.Number `json:"proteins"`
    Proteins100G         json.Number `json:"proteins_100g"`
    ProteinsServing      json.Number `json:"proteins_serving"`
    ProteinsUnit         string      `json:"proteins_unit"`
    Salt                 json.Number `json:"salt"`
    Salt100G             json.Number `json:"salt_100g"`
    SaltServing          json.Number `json:"salt_serving"`
    SaturatedFat         json.Number `json:"saturated-fat"`
    SaturatedFat100G     json.Number `json:"saturated-fat_100g"`
    SaturatedFatServing  json.Number `json:"saturated-fat_serving"`
    SaturatedFatUnit     string      `json:"saturated-fat_unit"`
    Sodium               json.Number `json:"sodium"`
    Sodium100G           json.Number `json:"sodium_100g"`
    SodiumServing        json.Number `json:"sodium_serving"`
    SodiumUnit           string      `json:"sodium_unit"`
    Sugars               json.Number `json:"sugars"`
    Sugars100G           json.Number `json:"sugars_100g"`
    SugarsServing        json.Number `json:"sugars_serving"`
    SugarsUnit           string      `json:"sugars_unit"`
    NutritionScoreFr     json.Number `json:"nutrition-score-fr"`
    NutritionScoreFr100G json.Number `json:"nutrition-score-fr_100g"`
    NutritionScoreUk     json.Number `json:"nutrition-score-uk"`
    NutritionScoreUk100G json.Number `json:"nutrition-score-uk_100g"`
}

type Product Uses

type Product struct {
    Id                                          string         `json:"id"`
    Code                                        string         `json:"code"`
    Brands                                      string         `json:"brands"`
    BrandsTags                                  []string       `json:"brands_tags"`
    GenericName                                 string         `json:"generic_name"`
    GenericNameEn                               string         `json:"generic_name_en"`
    CreatedTime                                 EpochTime      `json:"created_t"`
    LastImageTime                               EpochTime      `json:"last_image_t"`
    LastModifiedTime                            EpochTime      `json:"last_modified_t"`
    CompletedTime                               EpochTime      `json:"completed_t"`
    ImageFrontSmallURL                          UrlString      `json:"image_front_smallURL"`
    ImageFrontThumbURL                          UrlString      `json:"image_front_thumb_url"`
    ImageFrontURL                               UrlString      `json:"image_front_url"`
    ImageIngredientsSmallURL                    UrlString      `json:"image_ingredients_small_url"`
    ImageIngredientsThumbURL                    UrlString      `json:"image_ingredients_thumb_url"`
    ImageIngredientsURL                         UrlString      `json:"image_ingredients_url"`
    ImageNutritionSmallURL                      UrlString      `json:"image_nutrition_small_url"`
    ImageNutritionThumbURL                      UrlString      `json:"image_nutrition_thumb_url"`
    ImageNutritionURL                           UrlString      `json:"image_nutrition_url"`
    ImageSmallURL                               UrlString      `json:"image_small_url"`
    ImageThumbURL                               UrlString      `json:"image_thumb_url"`
    ImageURL                                    UrlString      `json:"image_url"`
    Creator                                     string         `json:"creator"`
    Checkers                                    []interface{}  `json:"checkers"`
    CheckersTags                                []interface{}  `json:"checkers_tags"`
    Editors                                     []string       `json:"editors"`
    EditorsTags                                 []string       `json:"editors_tags"`
    Correctors                                  []string       `json:"correctors"`
    CorrectorsTags                              []string       `json:"correctors_tags"`
    Informers                                   []string       `json:"informers"`
    InformersTags                               []string       `json:"informers_tags"`
    Photographers                               []string       `json:"photographers"`
    PhotographersTags                           []string       `json:"photographers_tags"`
    LastEditDatesTags                           []string       `json:"last_edit_dates_tags"`
    LastEditor                                  string         `json:"last_editor"`
    LastImageDatesTags                          []string       `json:"last_image_dates_tags"`
    LastModifiedBy                              string         `json:"last_modified_by"`
    Additives                                   string         `json:"additives"`
    AdditivesDebugTags                          []interface{}  `json:"additives_debug_tags"`
    AdditivesNumber                             int            `json:"additives_n"`
    AdditivesOldNumber                          int            `json:"additives_old_n"`
    AdditivesOldTags                            []string       `json:"additives_old_tags"`
    AdditivesPrev                               string         `json:"additives_prev"`
    AdditivesPrevNumber                         int            `json:"additives_prev_n"`
    AdditivesPrevTags                           []string       `json:"additives_prev_tags"`
    AdditivesTags                               []string       `json:"additives_tags"`
    AdditivesTagsNumber                         interface{}    `json:"additives_tags_n"`
    Allergens                                   string         `json:"allergens"`
    AllergensHierarchy                          []interface{}  `json:"allergens_hierarchy"`
    AllergensTags                               []interface{}  `json:"allergens_tags"`
    Categories                                  string         `json:"categories"`
    CategoriesDebugTags                         []interface{}  `json:"categories_debug_tags"`
    CategoriesHierarchy                         []string       `json:"categories_hierarchy"`
    CategoriesPrevHierarchy                     []string       `json:"categories_prev_hierarchy"`
    CategoriesPrevTags                          []string       `json:"categories_prev_tags"`
    CategoriesTags                              []string       `json:"categories_tags"`
    CitiesTags                                  []interface{}  `json:"cities_tags"`
    CodesTags                                   []string       `json:"codes_tags"`
    Complete                                    int            `json:"complete"`
    Countries                                   string         `json:"countries"`
    CountriesHierarchy                          []string       `json:"countries_hierarchy"`
    CountriesTags                               []string       `json:"countries_tags"`
    EmbCodes                                    string         `json:"emb_codes"`
    EmbCodes20141016                            string         `json:"emb_codes_20141016"`
    EmbCodesOrig                                string         `json:"emb_codes_orig"`
    EmbCodesTags                                []interface{}  `json:"emb_codes_tags"`
    EntryDatesTags                              []string       `json:"entry_dates_tags"`
    ExpirationDate                              string         `json:"expiration_date"`
    FruitsVegetablesNuts100GEstimate            json.Number    `json:"fruits-vegetables-nuts_100g_estimate"`
    Ingredients                                 []Ingredient   `json:"ingredients"`
    IngredientsDebug                            []interface{}  `json:"ingredients_debug"`
    IngredientsFromOrThatMayBeFromPalmOilNumber int            `json:"ingredients_from_or_that_may_be_from_palm_oil_n"`
    IngredientsFromPalmOilNumber                int            `json:"ingredients_from_palm_oil_n"`
    IngredientsFromPalmOilTags                  []interface{}  `json:"ingredients_from_palm_oil_tags"`
    IngredientsIdsDebug                         []string       `json:"ingredients_ids_debug"`
    IngredientsN                                string         `json:"ingredients_n"`
    IngredientsNTags                            []string       `json:"ingredients_n_tags"`
    IngredientsTags                             []string       `json:"ingredients_tags"`
    IngredientsText                             string         `json:"ingredients_text"`
    IngredientsTextDebug                        string         `json:"ingredients_text_debug"`
    IngredientsTextEn                           string         `json:"ingredients_text_en"`
    IngredientsTextWithAllergens                string         `json:"ingredients_text_with_allergens"`
    IngredientsTextWithAllergensEn              string         `json:"ingredients_text_with_allergens_en"`
    IngredientsThatMayBeFromPalmOilNumber       int            `json:"ingredients_that_may_be_from_palm_oil_n"`
    IngredientsThatMayBeFromPalmOilTags         []interface{}  `json:"ingredients_that_may_be_from_palm_oil_tags"`
    InterfaceVersionCreated                     string         `json:"interface_version_created"`
    InterfaceVersionModified                    string         `json:"interface_version_modified"`
    Keywords                                    []string       `json:"_keywords"`
    Labels                                      string         `json:"labels"`
    LabelsDebugTags                             []interface{}  `json:"labels_debug_tags"`
    LabelsHierarchy                             []string       `json:"labels_hierarchy"`
    LabelsPrevHierarchy                         []string       `json:"labels_prev_hierarchy"`
    LabelsPrevTags                              []string       `json:"labels_prev_tags"`
    LabelsTags                                  []string       `json:"labels_tags"`
    Lang                                        string         `json:"lang"`
    Languages                                   map[string]int `json:"languages"`
    LanguagesCodes                              map[string]int `json:"languages_codes"`
    LanguagesHierarchy                          []string       `json:"languages_hierarchy"`
    LanguagesTags                               []string       `json:"languages_tags"`
    Locale                                      string         `json:"lc"`
    MaxImgId                                    string         `json:"max_imgid"`
    NewAdditivesNumber                          int            `json:"new_additives_n"`
    NoNutritionData                             interface{}    `json:"no_nutrition_data"`
    NutrientLevels                              NutrientLevel  `json:"nutrient_levels"`
    NutrientLevelsTags                          []string       `json:"nutrient_levels_tags"`
    Nutriments                                  Nutriment      `json:"nutriments"`
    NutritionDataPer                            string         `json:"nutrition_data_per"`
    NutritionGradeFr                            string         `json:"nutrition_grade_fr"`
    NutritionGrades                             string         `json:"nutrition_grades"`
    NutritionGradesTags                         []string       `json:"nutrition_grades_tags"`
    NutritionScoreDebug                         string         `json:"nutrition_score_debug"`
    OriginTags                                  []string       `json:"origins_tags"`
    Origins                                     string         `json:"origins"`
    Packaging                                   string         `json:"packaging"`
    PackagingTags                               []string       `json:"packaging_tags"`
    PnnsGroups1                                 string         `json:"pnns_groups_1"`
    PnnsGroups1Tags                             []string       `json:"pnns_groups_1_tags"`
    PnnsGroups2                                 string         `json:"pnns_groups_2"`
    PnnsGroups2Tags                             []string       `json:"pnns_groups_2_tags"`
    ProductName                                 string         `json:"product_name"`
    ProductNameEn                               string         `json:"product_name_en"`
    PurchasePlaces                              string         `json:"purchase_places"`
    PurchasePlacesTags                          []interface{}  `json:"purchase_places_tags"`
    Quantity                                    string         `json:"quantity"`
    Rev                                         int            `json:"rev"`
    ScansNumber                                 int            `json:"scans_n"`
    ServingQuantity                             json.Number    `json:"serving_quantity"`
    ServingSize                                 string         `json:"serving_size"`
    SortKey                                     int            `json:"sortkey"`
    States                                      string         `json:"states"`
    StatesHierarchy                             []string       `json:"states_hierarchy"`
    StatesTags                                  []string       `json:"states_tags"`
    Stores                                      string         `json:"stores"`
    StoresTags                                  []interface{}  `json:"stores_tags"`
    Traces                                      string         `json:"traces"`
    TracesHierarchy                             []string       `json:"traces_hierarchy"`
    TracesTags                                  []string       `json:"traces_tags"`
    UniqueScansNumber                           int            `json:"unique_scans_n"`
    UnknownNutrientsTags                        []interface{}  `json:"unknown_nutrients_tags"`
    UpdateKey                                   string         `json:"update_key"`
}

type ProductResult Uses

type ProductResult struct {
    StatusVerbose string   `json:"status_verbose"`
    Status        int      `json:"status"`
    Code          string   `json:"code"`
    Product       *Product `json:"product"`
}

type UrlString Uses

type UrlString struct {
    url.URL
}

UrlString allows URL to be properly un/marshaled from a JSON string.

func (*UrlString) MarshalJSON Uses

func (u *UrlString) MarshalJSON() ([]byte, error)

func (*UrlString) UnmarshalJSON Uses

func (u *UrlString) UnmarshalJSON(b []byte) error

Package openfoodfacts imports 9 packages (graph). Updated 2018-02-14. Refresh now. Tools for package owners.