ileap

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: MIT Imports: 17 Imported by: 1

README

iLEAP Go

PkgGoDev GoReportCard CI

A Go SDK for logistics emissions data compatible with the iLEAP Technical Specifications.

SDK

Features
Installing
$ go get github.com/way-platform/ileap-go@latest
Using
client := ileap.NewClient(
    ileap.WithBaseURL(os.Getenv("BASE_URL")),
    ileap.WithOAuth2(os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")),
)
footprint, err := client.GetFootprint(context.Background(), &ileap.GetFootprintRequest{
    ID: "91715e5e-fd0b-4d1c-8fab-76290c46e6ed",
})
if err != nil {
    // TODO: Handle error.
}
fmt.Println(footprint)
Developing
Build project

The project is built using Mage, see magefile.go.

$ go tool mage build

For all available build tasks, see:

$ go tool mage

CLI tool

Installing
go install github.com/way-platform/ileap-go/cmd/ileap@latest

Prebuilt binaries for Linux, Windows, and Mac are available from the Releases.

Using

The following example logs in to the SINE Foundation's demo API.

$ ileap auth login \
  --base-url https://ileap.wayplatform.com \
  --client-id hello \
  --client-secret pathfinder

Logged in to https://api.ileap.sine.dev.
$ ileap footprint 91715e5e-fd0b-4d1c-8fab-76290c46e6ed
{
  "data": {
    "id": "91715e5e-fd0b-4d1c-8fab-76290c46e6ed",
    "specVersion": "2.0.0",
    "version": 1,
    "created": "2022-03-01T09:32:20Z",
    "status": "Active",
    "validityPeriodStart": "2022-03-01T09:32:20Z",
    "validityPeriodEnd": "2024-12-31T00:00:00Z",
    "companyName": "My Corp",
    "companyIds": [
      "urn:uuid:69585GB6-56T9-6958-E526-6FDGZJHU1326",
      "urn:epc:id:sgln:562958.00000.4"
    ],
    "productDescription": "Bio-Ethanol 98%, corn feedstock (bulk - no packaging)",
    "..."
}

Documentation

Index

Examples

Constants

View Source
const DemoBaseURL = "https://api.ileap.sine.dev"

DemoBaseURL is the base URL for the SINE Foundation's demo iLEAP API.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client is an iLEAP API client.

Example
client := ileap.NewClient(
	ileap.WithBaseURL(ileap.DemoBaseURL),
	ileap.WithOAuth2(os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")),
)
footprint, err := client.GetFootprint(context.Background(), &ileap.GetFootprintRequest{
	ID: "123",
})
if err != nil {
	// TODO: Handle error.
}
fmt.Println(footprint)

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new Client with the given base URL and options.

func (*Client) GetFootprint

func (c *Client) GetFootprint(ctx context.Context, request *GetFootprintRequest) (_ *ileapv0.ProductFootprintForILeapType, err error)

GetFootprint fetches a product carbon footprint by ID.

func (*Client) ListFootprints

func (c *Client) ListFootprints(ctx context.Context, request *ListFootprintsRequest) (_ *ListFootprintsResponse, err error)

ListFootprints fetches a list of product carbon footprints.

func (*Client) ListTADs

func (c *Client) ListTADs(ctx context.Context, request *ListTADsRequest) (_ *ListTADsResponse, err error)

ListTADs lists transport activity data.

type ClientConfig

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

ClientConfig is the configuration for a Client.

type ClientCredentials

type ClientCredentials struct {
	// Token is the bearer token for the authenticated client.
	AccessToken string `json:"access_token"`
	// TokenType is the type of token.
	TokenType string `json:"token_type"`
	// ExpireTime is the time when the token expires.
	ExpireTime time.Time `json:"expires_in,omitzero"`
}

ClientCredentials for an authenticated iLEAP API client.

type ClientError added in v0.4.0

type ClientError struct {
	// Method is the HTTP method used to make the request.
	Method string `json:"method"`
	// URL is the URL of the request.
	URL string `json:"url"`
	// Status is the HTTP status.
	Status string `json:"status"`
	// StatusCode is the HTTP status code.
	StatusCode int `json:"statusCode"`
	// Body is the error body.
	Body error `json:"error"`
}

ClientError is an HTTP response error received by an iLEAP client.

func (*ClientError) Error added in v0.4.0

func (e *ClientError) Error() string

Error implements the error interface.

type ClientOption

type ClientOption func(*ClientConfig)

ClientOption is an option that configures a Client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the API base URL for the Client.

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger sets the Logger for the Client.

func WithOAuth2

func WithOAuth2(clientID string, clientSecret string) ClientOption

WithOAuth authenticates requests using OAuth 2.0.

func WithRetryCount

func WithRetryCount(retryCount int) ClientOption

WithRetryCount sets the maximum number of times to retry a request.

func WithReuseTokenAuth

func WithReuseTokenAuth(credentials ClientCredentials) ClientOption

WithReuseTokenAuth authenticates requests by re-using existing ClientCredentials.

type Error

type Error struct {
	// Code is the error code identifier. Required.
	Code ErrorCode `json:"code"`
	// Message is a human readable error message. Required.
	Message string `json:"message"`
}

Error is an error response body returned by a PACT-compliant server.

See: https://docs.carbon-transparency.org/tr/data-exchange-protocol/latest/#error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type ErrorCode added in v0.4.0

type ErrorCode string

ErrorCode is an error code identifier.

const (
	ErrorCodeBadRequest      ErrorCode = "BadRequest"
	ErrorCodeAccessDenied    ErrorCode = "AccessDenied"
	ErrorCodeTokenExpired    ErrorCode = "TokenExpired"
	ErrorCodeNotFound        ErrorCode = "NotFound"
	ErrorCodeInternalError   ErrorCode = "InternalError"
	ErrorCodeNotImplemented  ErrorCode = "NotImplemented"
	ErrorCodeNoSuchFootprint ErrorCode = "NoSuchFootprint"
)

Known PACT error codes.

type Event added in v0.6.0

type Event struct {
	// Type is the type of the event.
	Type EventType `json:"type"`
	// Specversion is the version of the CloudEvents specification that the event uses.
	Specversion string `json:"specversion"`
	// Id is a unique identifier for the event.
	Id string `json:"id"`
	// Source is the source of the event.
	Source string `json:"source"`
	// Time is the time the event occurred.
	Time time.Time `json:"time"`
	// Data is the event data as raw JSON.
	Data json.RawMessage `json:"data"`
}

Event is a PACT event.

See: https://docs.carbon-transparency.org/tr/data-exchange-protocol/latest/#action-events See: https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/bindings/http-protocol-binding.md#32-structured-content-mode

type EventType added in v0.6.0

type EventType string

EventType is the type of the event.

const (
	EventTypeRequestCreatedV3   EventType = "org.wbcsd.pact.ProductFootprint.RequestCreatedEvent.3"
	EventTypeRequestFulfilledV3 EventType = "org.wbcsd.pact.ProductFootprint.RequestFulfilledEvent.3"
	EventTypeRequestRejectedV3  EventType = "org.wbcsd.pact.ProductFootprint.RequestRejectedEvent.3"
	EventTypePublishedV3        EventType = "org.wbcsd.pact.ProductFootprint.PublishedEvent.3"

	EventTypeRequestCreatedV1   EventType = "org.wbcsd.pathfinder.ProductFootprintRequest.Created.v1"
	EventTypePublishedV1        EventType = "org.wbcsd.pathfinder.ProductFootprint.Published.v1"
	EventTypeRequestFulfilledV1 EventType = "org.wbcsd.pathfinder.ProductFootprintRequest.Fulfilled.v1"
	EventTypeRequestRejectedV1  EventType = "org.wbcsd.pathfinder.ProductFootprintRequest.Rejected.v1"
)

Known event types.

type FilterPredicateV2 added in v0.7.0

type FilterPredicateV2 struct {
	LHS string `json:"lhs"`
	// Operator is the operator of the predicate.
	Operator string `json:"operator"`
	// RHS is the right hand side of the predicate.
	RHS string `json:"rhs"`
}

FilterPredicateV2 is a single filter predicate.

func (*FilterPredicateV2) MatchesFootprint added in v0.7.0

func (f *FilterPredicateV2) MatchesFootprint(footprint *ileapv0.ProductFootprintForILeapType) bool

MatchesFootprint returns true if the predicate matches the provided footprint.

func (*FilterPredicateV2) UnmarshalString added in v0.7.0

func (f *FilterPredicateV2) UnmarshalString(predicate string) error

UnmarshalString unmarshals a filter predicate from a string.

type FilterV2 added in v0.7.0

type FilterV2 struct {
	// Conjuctions are multiple filter predicates that are ANDed together.
	Conjuctions []FilterPredicateV2 `json:"conjuctions"`
}

FilterV2 is a limited implementation of PACT v2 filters.

func (*FilterV2) MatchesFootprint added in v0.7.0

func (f *FilterV2) MatchesFootprint(footprint *ileapv0.ProductFootprintForILeapType) bool

MatchesFootprint returns true if all predicates in the filter match the provided footprint.

func (*FilterV2) UnmarshalString added in v0.7.0

func (f *FilterV2) UnmarshalString(filter string) error

UnmarshalString unmarshals a filter from a string.

type GetFootprintRequest

type GetFootprintRequest struct {
	// ID is the ID of the footprint to get.
	ID string
}

GetFootprintRequest is the request for the Client.GetFootprint method.

type ListFootprintsRequest

type ListFootprintsRequest struct {
	// Limit is the maximum number of footprints to return.
	Limit int `json:"limit,omitempty"`
	// Filter is the OData filter to apply to the request.
	Filter string `json:"$filter,omitempty"`
}

ListFootprintsRequest is the request for the Client.ListFootprints method.

type ListFootprintsResponse

type ListFootprintsResponse struct {
	// Footprints is the list of footprints in the current page.
	Footprints []ileapv0.ProductFootprintForILeapType `json:"footprints"`
}

ListFootprintsResponse is the response for the Client.ListFootprints method.

type ListTADsRequest

type ListTADsRequest struct {
	// Limit is the maximum number of TADs to return.
	Limit int `json:"limit,omitempty"`
}

ListTADsRequest is the request for the Client.ListTADs method.

type ListTADsResponse

type ListTADsResponse struct {
	// TADs is the list of transport activity data in the current page.
	TADs []ileapv0.TAD `json:"tads"`
}

ListTADsResponse is the response for the Client.ListTADs method.

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Warn(msg string, keysAndValues ...any)
	Error(msg string, keysAndValues ...any)
}

Logger is a leveled logger interface.

type OAuthError added in v0.5.0

type OAuthError struct {
	// Code is the OAuth 2.0 error code identifier.
	Code OAuthErrorCode `json:"error"`
	// Description is a human readable description of the error.
	Description string `json:"error_description,omitempty"`
}

OAuthError is an OAuth 2.0 error response body returned by a PACT-compliant server.

See: https://datatracker.ietf.org/doc/html/rfc6749#section-5.2

func (*OAuthError) Error added in v0.5.0

func (e *OAuthError) Error() string

Error implements the error interface.

type OAuthErrorCode added in v0.5.0

type OAuthErrorCode string

OAuthErrorCode is an OAuth 2.0 error code identifier.

const (
	// OAuthErrorCodeInvalidRequest means the request is missing a required parameter,
	// includes an invalid parameter value, includes a parameter more than once,
	// or is otherwise malformed.
	OAuthErrorCodeInvalidRequest OAuthErrorCode = "invalid_request"

	// OAuthErrorCodeUnauthorizedClient means the client is not authorized to request an access
	// token using this method.
	OAuthErrorCodeUnauthorizedClient OAuthErrorCode = "unauthorized_client"

	// OAuthErrorCodeAccessDenied means the resource owner or authorization server denied the request.
	OAuthErrorCodeAccessDenied OAuthErrorCode = "access_denied"

	// OAuthErrorCodeUnsupportedResponseType means the authorization server does not support
	// obtaining an access token using this method.
	OAuthErrorCodeUnsupportedResponseType OAuthErrorCode = "unsupported_response_type"

	// OAuthErrorCodeInvalidScope means the requested scope is invalid, unknown, or malformed.
	OAuthErrorCodeInvalidScope OAuthErrorCode = "invalid_scope"

	// OAuthErrorCodeServerError means the authorization server encountered an unexpected condition
	// that prevented it from fulfilling the request.
	OAuthErrorCodeServerError OAuthErrorCode = "server_error"

	// OAuthErrorCodeTemporarilyUnavailable means the authorization server is currently unable
	// to handle the request due to a temporary overloading or maintenance of the server.
	OAuthErrorCodeTemporarilyUnavailable OAuthErrorCode = "temporarily_unavailable"

	// OAuthErrorCodeUnsupportedGrantType means the authorization server does not support
	// the authorization grant type used.
	OAuthErrorCodeUnsupportedGrantType OAuthErrorCode = "unsupported_grant_type"
)

type TokenAuthenticator

type TokenAuthenticator interface {
	// Authenticate the client and return a set of [TokenCredentials].
	Authenticate(ctx context.Context) (ClientCredentials, error)
}

TokenAuthenticator is a pluggable interface for authenticating requests to an iLEAP API.

func NewOAuth2TokenAuthenticator

func NewOAuth2TokenAuthenticator(clientID, clientSecret, baseURL string) TokenAuthenticator

Directories

Path Synopsis
cmd
demo-server command
ileap module
openapi
ileapv0
Package ileapv0 provides primitives to interact with the openapi HTTP API.
Package ileapv0 provides primitives to interact with the openapi HTTP API.
pactv3
Package pactv3 provides primitives to interact with the openapi HTTP API.
Package pactv3 provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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