contentful

package module
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 17 Imported by: 4

README

GitHub Release GitHub stars Go Report Card GoDoc

foomo/contentful

contentful-go

GoLang SDK for Contentful's Content Delivery, Preview and Management API's.

About

Contentful provides a content infrastructure for digital teams to power content in websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enable developers and content creators to ship digital products faster.

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Install

go get github.com/foomo/contentful

Getting started

Import into your Go project or library

import (
	"github.com/foomo/contentful"
)

Create a API client in order to interact with the Contentful's API endpoints.

token := "your-cma-token" // observe your CMA token from Contentful's web page
cma := contentful.NewCMA(token)
Organization

If your Contentful account is part of an organization, you can setup your API client as so. When you set your organization id for the SDK client, every api request will have X-Contentful-Organization: <your-organization-id> header automatically.

cma.SetOrganization("your-organization-id")
Debug mode

When debug mode is activated, sdk client starts to work in verbose mode and try to print as much informatin as possible. In debug mode, all outgoing http requests are printed nicely in the form of curl command so that you can easly drop into your command line to debug specific request.

cma.Debug = true

Using the SDK

Working with resource services

Currently, SDK exposes the following resource services:

  • Spaces
  • APIKeys
  • Assets
  • ContentTypes
  • Entries
  • Locales
  • Webhooks

Every resource service has at least the following interface:

List(ctx) *Collection
Get(ctx, spaceID, resourceID string) <Resource>, error
Upsert(ctx, spaceID string, resourceID *Resource) error
Delete(ctx, spaceID string, resourceID *Resource) error
Example
space, err := cma.Spaces.Get(ctx, "space-id")
if err != nil {
  log.Fatal(err)
}

collection := cma.ContentTypes.List(ctx, space.Sys.ID)
collection, err := collection.Next()
if err != nil {
  log.Fatal(err)
}

for _, contentType := range collection.ToContentType() {
  fmt.Println(contentType.Name, contentType.Description)
}

Working with collections

All the endpoints which return an array of objects are wrapped around Collection struct. The main features of Collection are pagination and type assertion.

Pagination

WIP

Type assertion

Collection struct exposes the necessary converters (type assertion) such as ToSpace(). The following example gets all spaces for the given account:

Example
collection := cma.Spaces.List() // returns a collection
collection, err := collection.Next() // makes the actual api call
if err != nil {
  log.Fatal(err)
}

spaces := collection.ToSpace() // make the type assertion
for _, space := range spaces {
  fmt.Println(space.Name)
  fmt.Println(space.Sys.ID)
}

// In order to access collection metadata
fmt.Println(col.Total)
fmt.Println(col.Skip)
fmt.Println(col.Limit)

Testing

$> go test

To enable higher verbose mode

$> go test -v -race

Documentation/References

Contentful

Content Delivery API Content Management API Content Preview API

GoLang

Effective Go

Support

This is a project created for demo purposes and not officially supported, so if you find issues or have questions, you can let us know via the issue page.

How to Contribute

Contributions are welcome! Please read the contributing guide.

Contributors

License

Distributed under MIT License, please see the license file for more details.

Made with ♥ foomo by bestbytes

Documentation

Index

Examples

Constants

View Source
const (
	// FieldTypeSymbol content type field type for short textual data
	FieldTypeSymbol = "Symbol"

	// FieldTypeText content type field type for text data
	FieldTypeText = "Text"

	// FieldTypeArray content type field type for array data
	FieldTypeArray = "Array"

	// FieldTypeLink content type field type for link data
	FieldTypeLink = "Link"

	// FieldTypeInteger content type field type for integer data
	FieldTypeInteger = "Integer"

	// FieldTypeLocation content type field type for location data
	FieldTypeLocation = "Location"

	// FieldTypeBoolean content type field type for boolean data
	FieldTypeBoolean = "Boolean"

	// FieldTypeDate content type field type for date data
	FieldTypeDate = "Date"

	// FieldTypeObject content type field type for object data
	FieldTypeObject = "Object"
)
View Source
const (
	// MimeTypeAttachment mime type validation for content type field
	MimeTypeAttachment = "attachment"

	// MimeTypePlainText mime type validation for content type field
	MimeTypePlainText = "plaintext"

	// MimeTypeImage mime type validation for content type field
	MimeTypeImage = "image"

	// MimeTypeAudio mime type validation for content type field
	MimeTypeAudio = "audio"

	// MimeTypeVideo mime type validation for content type field
	MimeTypeVideo = "video"

	// MimeTypeRichText mime type validation for content type field
	MimeTypeRichText = "richtext"

	// MimeTypePresentation mime type validation for content type field
	MimeTypePresentation = "presentation"

	// MimeTypeSpreadSheet mime type validation for content type field
	MimeTypeSpreadSheet = "spreadsheet"

	// MimeTypePDF mime type validation for content type field
	MimeTypePDF = "pdfdocument"

	// MimeTypeArchive mime type validation for content type field
	MimeTypeArchive = "archive"

	// MimeTypeCode mime type validation for content type field
	MimeTypeCode = "code"

	// MimeTypeMarkup mime type validation for content type field
	MimeTypeMarkup = "markup"
)
View Source
const (
	// FieldValidationRegexPatternEmail email validation
	FieldValidationRegexPatternEmail = `^\w[\w.-]*@([\w-]+\.)+[\w-]+$`

	// FieldValidationRegexPatternURL url validation
	FieldValidationRegexPatternURL = `^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$`

	// FieldValidationRegexPatternUSDate us date validation
	FieldValidationRegexPatternUSDate = `^(0?[1-9]|[12][0-9]|3[01])[- \/.](0?[1-9]|1[012])[- \/.](19|20)?\d\d$`

	// FieldValidationRegexPatternEuropeanDate european date validation
	FieldValidationRegexPatternEuropeanDate = `^(0?[1-9]|[12][0-9]|3[01])[- \/.](0?[1-9]|1[012])[- \/.](19|20)?\d\d$`

	// FieldValidationRegexPattern12HourTime 12-hour time validation
	FieldValidationRegexPattern12HourTime = `^(0?[1-9]|1[012]):[0-5][0-9](:[0-5][0-9])?\s*[aApP][mM]$`

	// FieldValidationRegexPattern24HourTime 24-hour time validation
	FieldValidationRegexPattern24HourTime = `^(0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$`

	// FieldValidationRegexPatternUSPhoneNumber us phone number validation
	FieldValidationRegexPatternUSPhoneNumber = `^\d[ -.]?\(?\d\d\d\)?[ -.]?\d\d\d[ -.]?\d\d\d\d$`

	// FieldValidationRegexPatternUSZipCode us zip code validation
	FieldValidationRegexPatternUSZipCode = `^\d{5}$|^\d{5}-\d{4}$}`
)

Variables

View Source
var Version = "0.3.1"

Version for SDK Version

Functions

func Buffer

func Buffer() (*bytes.Buffer, func())

Buffer returns a new buffer and a function to return the buffer to the pool.

func Decode

func Decode[T any](buf *bytes.Buffer, v *T) error

Decode decodes the JSON-encoded data from buf into v.

func DeepCopy

func DeepCopy[S, T any](dst *T, src S) error

DeepCopy performs a deep copy from src to dst by serializing and deserializing using a buffer. Returns an error if the encoding or decoding processes fail.

func Encode

func Encode[S any](buf *bytes.Buffer, v S) error

Encode encodes v into JSON and writes the result to buf.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal returns the JSON encoding of v.

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.

Types

type APIError

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

APIError model

type APIKey

type APIKey struct {
	Sys           *Sys            `json:"sys,omitempty"`
	Name          string          `json:"name,omitempty"`
	Description   string          `json:"description,omitempty"`
	AccessToken   string          `json:"accessToken,omitempty"`
	Policies      []*APIKeyPolicy `json:"policies,omitempty"`
	PreviewAPIKey *PreviewAPIKey  `json:"preview_api_key,omitempty"`
}

APIKey model

func (*APIKey) GetVersion

func (apiKey *APIKey) GetVersion() int

GetVersion returns entity version

func (*APIKey) MarshalJSON

func (apiKey *APIKey) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

type APIKeyPolicy

type APIKeyPolicy struct {
	Effect  string `json:"effect,omitempty"`
	Actions string `json:"actions,omitempty"`
}

APIKeyPolicy model

type APIKeyService

type APIKeyService service

APIKeyService service

func (*APIKeyService) Delete

func (service *APIKeyService) Delete(ctx context.Context, spaceID string, apiKey *APIKey) error

Delete deletes a sinlge api key entity

func (*APIKeyService) Get

func (service *APIKeyService) Get(ctx context.Context, spaceID, apiKeyID string) (*APIKey, error)

Get returns a single api key entity

func (*APIKeyService) List

func (service *APIKeyService) List(ctx context.Context, spaceID string) *Collection[APIKey]

List returns all api keys collection

func (*APIKeyService) Upsert

func (service *APIKeyService) Upsert(ctx context.Context, spaceID string, apiKey *APIKey) error

Upsert updates or creates a new api key entity

type AccessDeniedError

type AccessDeniedError struct{}

AccessDeniedError error model for access denied responses

type AccessTokenInvalidError

type AccessTokenInvalidError struct {
	APIError
}

AccessTokenInvalidError for 401 errors

func (AccessTokenInvalidError) Error

func (e AccessTokenInvalidError) Error() string

type Asset

type Asset struct {
	Metadata *Metadata   `json:"metadata,omitempty"`
	Sys      *Sys        `json:"sys"`
	Fields   *FileFields `json:"fields"`
}

Asset model

func (*Asset) GetLocalized

func (asset *Asset) GetLocalized() *AssetNoLocale

GetLocalized returns the asset with fields without localization map

func (*Asset) GetVersion

func (asset *Asset) GetVersion() int

GetVersion returns entity version

type AssetNoLocale

type AssetNoLocale struct {
	Sys    *Sys                `json:"sys"`
	Fields *FileFieldsNoLocale `json:"fields"`
}

AssetNoLocale model

type AssetsService

type AssetsService service

AssetsService service

func (*AssetsService) Delete

func (service *AssetsService) Delete(ctx context.Context, spaceID string, asset *Asset) error

Delete sends delete request

func (*AssetsService) Get

func (service *AssetsService) Get(ctx context.Context, spaceID, assetID string, locale ...string) (*Asset, error)

Get returns a single asset entity

func (*AssetsService) List

func (service *AssetsService) List(ctx context.Context, spaceID string) *Collection[Asset]

List returns asset collection

func (*AssetsService) Process

func (service *AssetsService) Process(ctx context.Context, spaceID string, asset *Asset) error

Process the asset

func (*AssetsService) Publish

func (service *AssetsService) Publish(ctx context.Context, spaceID string, asset *Asset) error

Publish publishes the asset

func (*AssetsService) Unpublish

func (service *AssetsService) Unpublish(ctx context.Context, spaceID string, asset *Asset) error

Unpublish unpublishes the asset

func (*AssetsService) Upsert

func (service *AssetsService) Upsert(ctx context.Context, spaceID string, asset *Asset) error

Upsert updates or creates a new asset entity

type BadRequestError

type BadRequestError struct{}

BadRequestError error model for bad request responses

type Collection

type Collection[T any] struct {
	Query

	Sys         *Sys                   `json:"sys"`
	Total       int                    `json:"total"`
	Skip        int                    `json:"skip"`
	Limit       uint16                 `json:"limit"`
	Items       []T                    `json:"items"`
	Includes    map[string]interface{} `json:"includes"`
	NextSyncURL string                 `json:"nextSyncUrl"`
	NextPageURL string                 `json:"nextPageUrl"`
	SyncToken   string                 `json:"syncToken"`
	// Errors which occur in the contentful structure. They are not checked in
	// this source code. Please do it yourself as you might still want to parse
	// the result despite the error.
	Errors []Error `json:"errors"`
	// Details might also get set in case of errors.
	Details *ErrorDetails `json:"details"`
	// contains filtered or unexported fields
}

Collection model with generic type parameter for Items

func NewCollection

func NewCollection[T any](options *CollectionOptions) *Collection[T]

NewCollection initializes a new generic collection

func (*Collection[T]) Get

func (col *Collection[T]) Get() (*Collection[T], error)

Get makes the col.req with no automatic pagination

func (*Collection[T]) GetAll

func (col *Collection[T]) GetAll() (*Collection[T], error)

GetAll paginates and returns all items - beware of memory usage!

func (*Collection[T]) Next

func (col *Collection[T]) Next() (*Collection[T], error)

Next makes the col.req

func (*Collection[T]) ToIncludesAsset

func (col *Collection[T]) ToIncludesAsset() ([]*IncludeAsset, error)

ToIncludesAsset cast includesAsset to Asset model

func (*Collection[T]) ToIncludesAssetMap

func (col *Collection[T]) ToIncludesAssetMap() (map[string]*IncludeAsset, error)

ToIncludesAssetMap returns a map of Asset's from the Includes

func (*Collection[T]) ToIncludesEntry

func (col *Collection[T]) ToIncludesEntry() ([]*Entry, error)

ToIncludesEntry cast includesEntry to Entry model

func (*Collection[T]) ToIncludesEntryMap

func (col *Collection[T]) ToIncludesEntryMap() (map[string]*Entry, error)

ToIncludesEntryMap returns a map of Entry's from the Includes

func (*Collection[T]) ToIncludesLocalizedAssetMap

func (col *Collection[T]) ToIncludesLocalizedAssetMap() (map[string]*Asset, error)

ToIncludesLocalizedAssetMap returns a map of Asset's from the Includes

type CollectionOptions

type CollectionOptions struct {
	Limit uint16
}

CollectionOptions holds init options

type ContentType

type ContentType struct {
	Sys          *Sys     `json:"sys"`
	Name         string   `json:"name,omitempty"`
	Description  string   `json:"description,omitempty"`
	Fields       []*Field `json:"fields,omitempty"`
	DisplayField string   `json:"displayField,omitempty"`
}

ContentType model

func (*ContentType) GetVersion

func (ct *ContentType) GetVersion() int

GetVersion returns entity version

type ContentTypeService

type ContentTypeService[T any] service

ContentTypeService servıce

func NewContentTypeService

func NewContentTypeService[T any](c *Contentful) *ContentTypeService[T]

func (*ContentTypeService[T]) Archive

func (service *ContentTypeService[T]) Archive(ctx context.Context, spaceID string, entry *T) error

Publish the entry

func (*ContentTypeService[T]) Delete

func (service *ContentTypeService[T]) Delete(ctx context.Context, spaceID string, entryID string) error

Delete the entry

func (*ContentTypeService[T]) Get

func (service *ContentTypeService[T]) Get(ctx context.Context, spaceID, entryID string, locale ...string) (T, error)

Get returns a single entry

func (*ContentTypeService[T]) GetEntryKey

func (service *ContentTypeService[T]) GetEntryKey(ctx context.Context, entry *T, key string) (*EntryField, error)

GetEntryKey returns the entry's keys

func (*ContentTypeService[T]) List

func (service *ContentTypeService[T]) List(ctx context.Context, spaceID string) *Collection[T]

List returns entries collection

func (*ContentTypeService[T]) Publish

func (service *ContentTypeService[T]) Publish(ctx context.Context, spaceID string, entry *T) error

Publish the entry

func (*ContentTypeService[T]) Sync

func (service *ContentTypeService[T]) Sync(ctx context.Context, spaceID string, initial bool, syncToken ...string) *Collection[T]

Sync returns entries collection

func (*ContentTypeService[T]) Unpublish

func (service *ContentTypeService[T]) Unpublish(ctx context.Context, spaceID string, entry *T) error

Unpublish the entry

func (*ContentTypeService[T]) Upsert

func (service *ContentTypeService[T]) Upsert(ctx context.Context, spaceID string, entry *T) error

Upsert updates or creates a new entry

type ContentTypesService

type ContentTypesService service

ContentTypesService service

func (*ContentTypesService) Activate

func (service *ContentTypesService) Activate(ctx context.Context, spaceID string, ct *ContentType) error

Activate the contenttype, a.k.a publish

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.TODO(), "space-id", "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Activate(context.TODO(), "space-id", contentType)
if err != nil {
	log.Fatal(err)
}

func (*ContentTypesService) Deactivate

func (service *ContentTypesService) Deactivate(ctx context.Context, spaceID string, ct *ContentType) error

Deactivate the contenttype, a.k.a unpublish

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.TODO(), "space-id", "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Deactivate(context.TODO(), "space-id", contentType)
if err != nil {
	log.Fatal(err)
}

func (*ContentTypesService) Delete

func (service *ContentTypesService) Delete(ctx context.Context, spaceID string, ct *ContentType) error

Delete the content_type

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.TODO(), "space-id", "content-type-id")
if err != nil {
	log.Fatal(err)
}

err = cma.ContentTypes.Delete(context.TODO(), "space-id", contentType)
if err != nil {
	log.Fatal(err)
}
Example (AllDrafts)
cma := NewCMA("cma-token")

collection, err := cma.ContentTypes.List(context.TODO(), "space-id").Next()
if err != nil {
	log.Fatal(err)
}

for _, contentType := range collection.Items {
	if contentType.Sys.PublishedAt == "" {
		err := cma.ContentTypes.Delete(context.TODO(), "space-id", &contentType)
		if err != nil {
			log.Fatal(err)
		}
	}
}

func (*ContentTypesService) Get

func (service *ContentTypesService) Get(ctx context.Context, spaceID, contentTypeID string) (*ContentType, error)

Get fetched a content type specified by `contentTypeID`

Example
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.TODO(), "space-id", "content-type-id")
if err != nil {
	log.Fatal(err)
}

fmt.Println(contentType.Name)

func (*ContentTypesService) List

func (service *ContentTypesService) List(ctx context.Context, spaceID string) *Collection[ContentType]

List return a content type collection

Example
cma := NewCMA("cma-token")

collection, err := cma.ContentTypes.List(context.TODO(), "space-id").Next()
if err != nil {
	log.Fatal(err)
}

for _, contentType := range collection.Items {
	fmt.Println(contentType.Sys.ID, contentType.Sys.PublishedAt)
}

func (*ContentTypesService) Upsert

func (service *ContentTypesService) Upsert(ctx context.Context, spaceID string, ct *ContentType) error

Upsert updates or creates a new content type

Example (Create)
cma := NewCMA("cma-token")

contentType := &ContentType{
	Name:         "test content type",
	DisplayField: "field1_id",
	Description:  "content type description",
	Fields: []*Field{
		{
			ID:       "field1_id",
			Name:     "field1",
			Type:     "Symbol",
			Required: false,
			Disabled: false,
		},
		{
			ID:       "field2_id",
			Name:     "field2",
			Type:     "Symbol",
			Required: false,
			Disabled: true,
		},
	},
}

err := cma.ContentTypes.Upsert(context.TODO(), "space-id", contentType)
if err != nil {
	log.Fatal(err)
}
Example (Update)
cma := NewCMA("cma-token")

contentType, err := cma.ContentTypes.Get(context.TODO(), "space-id", "content-type-id")
if err != nil {
	log.Fatal(err)
}

contentType.Name = "modified content type name"

err = cma.ContentTypes.Upsert(context.TODO(), "space-id", contentType)
if err != nil {
	log.Fatal(err)
}

type Contentful

type Contentful struct {
	Debug       bool
	QueryParams map[string]string
	Headers     map[string]string
	BaseURL     string
	UploadURL   string
	Environment string

	Spaces       *SpacesService
	APIKeys      *APIKeyService
	Assets       *AssetsService
	ContentTypes *ContentTypesService
	Entries      *EntriesService
	Locales      *LocalesService
	Tags         *TagsService
	Upload       *UploadService
	Webhooks     *WebhooksService
	// contains filtered or unexported fields
}

Contentful model

func NewCDA

func NewCDA(token string) *Contentful

NewCDA returns a CDA client

func NewCMA

func NewCMA(token string) *Contentful

NewCMA returns a CMA client

func NewCPA

func NewCPA(token string) *Contentful

NewCPA returns a CPA client

func (*Contentful) SetBaseURL

func (c *Contentful) SetBaseURL(baseURL string) *Contentful

SetBaseURL provides an option to change the BaseURL of the client

func (*Contentful) SetHTTPClient

func (c *Contentful) SetHTTPClient(client *http.Client) *Contentful

SetHTTPClient sets the underlying http.Client used to make requests.

func (*Contentful) SetHTTPTransport

func (c *Contentful) SetHTTPTransport(t http.RoundTripper) *Contentful

SetHTTPTransport creates a new http.Client and sets a custom Roundtripper.

func (*Contentful) SetOrganization

func (c *Contentful) SetOrganization(organizationID string) *Contentful

SetOrganization sets the given organization id

type DateMinMax

type DateMinMax struct {
	Min time.Time `json:"min,omitempty"`
	Max time.Time `json:"max,omitempty"`
}

DateMinMax model

type EntriesService

type EntriesService service

EntriesService servıce

func (*EntriesService) Archive

func (service *EntriesService) Archive(ctx context.Context, spaceID string, entry *Entry) error

Publish the entry

func (*EntriesService) Delete

func (service *EntriesService) Delete(ctx context.Context, spaceID string, entryID string) error

Delete the entry

func (*EntriesService) Get

func (service *EntriesService) Get(ctx context.Context, spaceID, entryID string, locale ...string) (*Entry, error)

Get returns a single entry

func (*EntriesService) GetEntryKey

func (service *EntriesService) GetEntryKey(ctx context.Context, entry *Entry, key string) (*EntryField, error)

GetEntryKey returns the entry's keys

func (*EntriesService) List

func (service *EntriesService) List(ctx context.Context, spaceID string) *Collection[Entry]

List returns entries collection

func (*EntriesService) Publish

func (service *EntriesService) Publish(ctx context.Context, spaceID string, entry *Entry) error

Publish the entry

func (*EntriesService) Sync

func (service *EntriesService) Sync(ctx context.Context, spaceID string, initial bool, syncToken ...string) *Collection[Entry]

Sync returns entries collection

func (*EntriesService) Unpublish

func (service *EntriesService) Unpublish(ctx context.Context, spaceID string, entry *Entry) error

Unpublish the entry

func (*EntriesService) Upsert

func (service *EntriesService) Upsert(ctx context.Context, spaceID string, entry *Entry) error

Upsert updates or creates a new entry

Example (Create)
cma := NewCMA("cma-token")

entry := &Entry{
	Sys: &Sys{
		ID: "MyEntry",
		ContentType: &ContentType{
			Sys: &Sys{
				ID: "MyContentType",
			},
		},
	},
	Fields: map[string]interface{}{
		"Description": map[string]string{
			"en-US": "Some example content...",
		},
	},
}

err := cma.Entries.Upsert(context.TODO(), "space-id", entry)
if err != nil {
	log.Fatal(err)
}
Example (Update)
cma := NewCMA("cma-token")

entry, err := cma.Entries.Get(context.TODO(), "space-id", "entry-id")
if err != nil {
	log.Fatal(err)
}

entry.Fields["Description"] = map[string]interface{}{
	"en-US": "modified entry content",
}

err = cma.Entries.Upsert(context.TODO(), "space-id", entry)
if err != nil {
	log.Fatal(err)
}

type Entry

type Entry struct {
	Metadata *Metadata              `json:"metadata,omitempty"`
	Sys      *Sys                   `json:"sys"`
	Fields   map[string]interface{} `json:"fields,omitempty"`
}

Entry model

func (*Entry) GetVersion

func (entry *Entry) GetVersion() int

GetVersion returns entity version

type EntryField

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

EntryField model

func (*EntryField) Array

func (ef *EntryField) Array() []string

Array converts interface to slice

func (*EntryField) Asset

func (ef *EntryField) Asset() *Asset

Asset returns the linked asset

func (*EntryField) Entry

func (ef *EntryField) Entry() *Entry

Entry returns the linked entry

func (*EntryField) Integer

func (ef *EntryField) Integer() int

Integer converts interface to integer

func (*EntryField) LArray

func (ef *EntryField) LArray(locale string) []string

LArray converts interface to slice

func (*EntryField) LAsset

func (ef *EntryField) LAsset(locale string) *Asset

LAsset returns the linked asset

func (*EntryField) LEntry

func (ef *EntryField) LEntry(locale string) *Entry

LEntry returns the linked entry

func (*EntryField) LInteger

func (ef *EntryField) LInteger(locale string) int

LInteger converts interface to integer

func (*EntryField) LLinkID

func (ef *EntryField) LLinkID(locale string) string

LLinkID returns link model

func (*EntryField) LLinkType

func (ef *EntryField) LLinkType(locale string) string

LLinkType returns link model

func (*EntryField) LString

func (ef *EntryField) LString(locale string) string

LString returns the given lovale

func (*EntryField) LinkID

func (ef *EntryField) LinkID() string

LinkID returns link model

func (*EntryField) LinkType

func (ef *EntryField) LinkType() string

LinkType returns link model

func (*EntryField) String

func (ef *EntryField) String() string

String converts interface to string

type Error

type Error struct {
	Sys     *Sys
	Details map[string]string
}

Error defines an internal contentful data model error when e.g. an assets can be resolved. The structure gets returned while this error is set too. The programmer can decide how to handle the response by checking the Collection.Errors field.

type ErrorDetail

type ErrorDetail struct {
	ID      string      `json:"id,omitempty"`
	Name    string      `json:"name,omitempty"`
	Path    interface{} `json:"path,omitempty"`
	Details string      `json:"details,omitempty"`
	Value   interface{} `json:"value,omitempty"`
}

ErrorDetail model

type ErrorDetails

type ErrorDetails struct {
	Errors []*ErrorDetail `json:"errors,omitempty"`
}

ErrorDetails model

type ErrorResponse

type ErrorResponse struct {
	Sys       *Sys          `json:"sys"`
	Message   string        `json:"message,omitempty"`
	RequestID string        `json:"requestId,omitempty"`
	Details   *ErrorDetails `json:"details,omitempty"`
}

ErrorResponse model

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

type Field

type Field struct {
	ID          string              `json:"id,omitempty"`
	Name        string              `json:"name"`
	Type        string              `json:"type"`
	LinkType    string              `json:"linkType,omitempty"`
	Items       *FieldTypeArrayItem `json:"items,omitempty"`
	Required    bool                `json:"required,omitempty"`
	Localized   bool                `json:"localized,omitempty"`
	Disabled    bool                `json:"disabled,omitempty"`
	Omitted     bool                `json:"omitted,omitempty"`
	Validations []FieldValidation   `json:"validations,omitempty"`
}

Field model

func (*Field) UnmarshalJSON

func (field *Field) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldTypeArrayItem

type FieldTypeArrayItem struct {
	Type        string            `json:"type,omitempty"`
	Validations []FieldValidation `json:"validations,omitempty"`
	LinkType    string            `json:"linkType,omitempty"`
}

FieldTypeArrayItem model

func (*FieldTypeArrayItem) UnmarshalJSON

func (item *FieldTypeArrayItem) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldValidation

type FieldValidation interface{}

FieldValidation interface

func ParseValidations

func ParseValidations(data []interface{}) ([]FieldValidation, error)

ParseValidations converts json representation to go struct

type FieldValidationDate

type FieldValidationDate struct {
	Range        *DateMinMax `json:"dateRange,omitempty"`
	ErrorMessage string      `json:"message,omitempty"`
}

FieldValidationDate model

func (*FieldValidationDate) MarshalJSON

func (v *FieldValidationDate) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

func (*FieldValidationDate) UnmarshalJSON

func (v *FieldValidationDate) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldValidationDimension

type FieldValidationDimension struct {
	Width        *MinMax `json:"width,omitempty"`
	Height       *MinMax `json:"height,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationDimension model

func (*FieldValidationDimension) MarshalJSON

func (v *FieldValidationDimension) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

func (*FieldValidationDimension) UnmarshalJSON

func (v *FieldValidationDimension) UnmarshalJSON(data []byte) error

UnmarshalJSON for custom json unmarshaling

type FieldValidationFileSize

type FieldValidationFileSize struct {
	Size         *MinMax `json:"assetFileSize,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationFileSize model

type FieldValidationLink struct {
	LinkContentType []string `json:"linkContentType,omitempty"`
}

FieldValidationLink model

type FieldValidationMimeType

type FieldValidationMimeType struct {
	MimeTypes []string `json:"linkMimetypeGroup,omitempty"`
}

FieldValidationMimeType model

type FieldValidationPredefinedValues

type FieldValidationPredefinedValues struct {
	In           []interface{} `json:"in,omitempty"`
	ErrorMessage string        `json:"message"`
}

FieldValidationPredefinedValues model

type FieldValidationRange

type FieldValidationRange struct {
	Range        *MinMax `json:"range,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationRange model

type FieldValidationRegex

type FieldValidationRegex struct {
	Regex        *Regex `json:"regexp,omitempty"`
	ErrorMessage string `json:"message,omitempty"`
}

FieldValidationRegex model

type FieldValidationSize

type FieldValidationSize struct {
	Size         *MinMax `json:"size,omitempty"`
	ErrorMessage string  `json:"message,omitempty"`
}

FieldValidationSize model

type FieldValidationUnique

type FieldValidationUnique struct {
	Unique bool `json:"unique"`
}

FieldValidationUnique model

type File

type File struct {
	Name        string      `json:"fileName,omitempty"`
	ContentType string      `json:"contentType,omitempty"`
	URL         string      `json:"url,omitempty"`
	UploadURL   string      `json:"upload,omitempty"`
	UploadFrom  *Upload     `json:"uploadFrom,omitempty"`
	Detail      *FileDetail `json:"details,omitempty"`
}

File model

type FileDetail

type FileDetail struct {
	Size  int        `json:"size,omitempty"`
	Image *FileImage `json:"image,omitempty"`
}

FileDetail model

type FileFields

type FileFields struct {
	Title       map[string]string `json:"title,omitempty"`
	Description map[string]string `json:"description,omitempty"`
	File        map[string]*File  `json:"file,omitempty"`
}

FileFields model

type FileFieldsNoLocale

type FileFieldsNoLocale struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	File        *File  `json:"file,omitempty"`
}

FileFieldsNoLocale model

type FileImage

type FileImage struct {
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

FileImage model

type IncludeAsset

type IncludeAsset struct {
	Fields *IncludeFileFields `json:"fields"`
	Sys    *Sys               `json:"sys"`
}

IncludeAsset model

type IncludeEntry

type IncludeEntry struct {
	Fields map[string]interface{} `json:"fields,omitempty"`
	Sys    *Sys                   `json:"sys"`
}

IncludeEntry model

type IncludeFileFields

type IncludeFileFields struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	File        *File  `json:"file,omitempty"`
}

IncludeFileFields model

type Includes

type Includes struct {
	Entry map[string]interface{} `json:"Entry"`
	Asset map[string]interface{} `json:"Asset"`
}

Includes model

type InvalidQueryError

type InvalidQueryError struct{}

InvalidQueryError error model for invalid query responses

type Locale

type Locale struct {
	Sys *Sys `json:"sys,omitempty"`

	// Locale name
	Name string `json:"name,omitempty"`

	// Language code
	Code string `json:"code,omitempty"`

	// If no content is provided for the locale, the Delivery API will return content in a locale specified below:
	FallbackCode string `json:"fallbackCode,omitempty"`

	// Make the locale as default locale for your account
	Default bool `json:"default,omitempty"`

	// Entries with required fields can still be published if locale is empty.
	Optional bool `json:"optional,omitempty"`

	// Includes locale in the Delivery API response.
	CDA bool `json:"contentDeliveryApi"`

	// Displays locale to editors and enables it in Management API.
	CMA bool `json:"contentManagementApi"`
}

Locale model

func (*Locale) GetVersion

func (locale *Locale) GetVersion() int

GetVersion returns entity version

type LocalesService

type LocalesService service

LocalesService service

func (*LocalesService) Delete

func (service *LocalesService) Delete(ctx context.Context, spaceID string, locale *Locale) error

Delete the locale

func (*LocalesService) Get

func (service *LocalesService) Get(ctx context.Context, spaceID, localeID string) (*Locale, error)

Get returns a single locale entity

func (*LocalesService) List

func (service *LocalesService) List(ctx context.Context, spaceID string) *Collection[Locale]

List returns a locales collection

func (*LocalesService) Upsert

func (service *LocalesService) Upsert(ctx context.Context, spaceID string, locale *Locale) error

Upsert updates or creates a new locale entity

type Metadata

type Metadata struct {
	Tags []Tag `json:"tags"`
}

type MinMax

type MinMax struct {
	Min float64 `json:"min,omitempty"`
	Max float64 `json:"max,omitempty"`
}

MinMax model

type NotFoundError

type NotFoundError struct {
	APIError
}

NotFoundError for 404 errors

func (NotFoundError) Error

func (e NotFoundError) Error() string

type PreviewAPIKey

type PreviewAPIKey struct {
	Sys *Sys `json:"sys,omitempty"`
}

PreviewAPIKey model

type Query

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

Query model

func NewQuery

func NewQuery() *Query

NewQuery initilazies a new query

func (*Query) All

func (q *Query) All(field string, value []string) *Query

All [all] query

func (*Query) ContentType

func (q *Query) ContentType(ct string) *Query

ContentType query

func (*Query) Equal

func (q *Query) Equal(field string, value interface{}) *Query

Equal equality query

func (*Query) Exists

func (q *Query) Exists(field string) *Query

Exists [exists] query

func (*Query) GreaterThan

func (q *Query) GreaterThan(field string, value interface{}) *Query

GreaterThan [gt] query

func (*Query) GreaterThanOrEqual

func (q *Query) GreaterThanOrEqual(field string, value interface{}) *Query

GreaterThanOrEqual [lte] query

func (*Query) In

func (q *Query) In(field string, value []string) *Query

In [in] query

func (*Query) Include

func (q *Query) Include(include uint16) *Query

Include query

func (*Query) Initial

func (q *Query) Initial(initial string) *Query

Initial query

func (*Query) LessThan

func (q *Query) LessThan(field string, value interface{}) *Query

LessThan [lt] query

func (*Query) LessThanOrEqual

func (q *Query) LessThanOrEqual(field string, value interface{}) *Query

LessThanOrEqual [lte] query

func (*Query) Limit

func (q *Query) Limit(limit uint16) *Query

Limit query

func (*Query) Locale

func (q *Query) Locale(locale string) *Query

Locale query

func (*Query) Match

func (q *Query) Match(field, match string) *Query

Match param

func (*Query) MimeType

func (q *Query) MimeType(mime string) *Query

MimeType query

func (*Query) Near

func (q *Query) Near(field string, lat, lon int16) *Query

Near param

func (*Query) NotEqual

func (q *Query) NotEqual(field string, value interface{}) *Query

NotEqual [ne] query

func (*Query) NotExists

func (q *Query) NotExists(field string) *Query

NotExists [exists] query

func (*Query) NotIn

func (q *Query) NotIn(field string, value []string) *Query

NotIn [nin] query

func (*Query) Order

func (q *Query) Order(field string, reverse bool) *Query

Order param

func (*Query) Query

func (q *Query) Query(qStr string) *Query

Query param

func (*Query) Select

func (q *Query) Select(fields []string) *Query

Select query

func (*Query) Skip

func (q *Query) Skip(skip uint16) *Query

Skip query

func (*Query) String

func (q *Query) String() string

func (*Query) SyncToken

func (q *Query) SyncToken(syncToken string) *Query

SyncToken query

func (*Query) SyncType

func (q *Query) SyncType(syncType string) *Query

SyncType query

func (*Query) SysID

func (q *Query) SysID(sid string) *Query

SysID query

func (*Query) Values

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

Values constructs url.Values

func (*Query) Within

func (q *Query) Within(field string, lat1, lon1, lat2, lon2 int16) *Query

Within param

func (*Query) WithinRadius

func (q *Query) WithinRadius(field string, lat1, lon1, radius int16) *Query

WithinRadius param

type RateLimitExceededError

type RateLimitExceededError struct {
	APIError
}

RateLimitExceededError for rate limit errors

func (RateLimitExceededError) Error

func (e RateLimitExceededError) Error() string

type Regex

type Regex struct {
	Pattern string `json:"pattern,omitempty"`
	Flags   string `json:"flags,omitempty"`
}

Regex model

type ServerError

type ServerError struct{}

ServerError error model for server error responses

type Space

type Space struct {
	Sys           *Sys   `json:"sys,omitempty"`
	Name          string `json:"name,omitempty"`
	DefaultLocale string `json:"defaultLocale,omitempty"`
}

Space model

func (*Space) GetVersion

func (space *Space) GetVersion() int

GetVersion returns entity version

func (*Space) MarshalJSON

func (space *Space) MarshalJSON() ([]byte, error)

MarshalJSON for custom json marshaling

type SpacesService

type SpacesService service

SpacesService model

func (*SpacesService) Delete

func (service *SpacesService) Delete(ctx context.Context, space *Space) error

Delete the given space

Example
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.TODO(), "space-id")
if err != nil {
	log.Fatal(err)
}

err = cma.Spaces.Delete(context.TODO(), space)
if err != nil {
	log.Fatal(err)
}
Example (All)
cma := NewCMA("cma-token")

collection, err := cma.Spaces.List(context.TODO()).Next()
if err != nil {
	log.Fatal(err)
}

for _, space := range collection.Items {
	err := cma.Spaces.Delete(context.TODO(), &space)
	if err != nil {
		log.Fatal(err)
	}
}

func (*SpacesService) Get

func (service *SpacesService) Get(ctx context.Context, spaceID string) (*Space, error)

Get returns a single space entity

Example
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.TODO(), "space-id")
if err != nil {
	log.Fatal(err)
}

fmt.Println(space.Name)

func (*SpacesService) List

func (service *SpacesService) List(ctx context.Context) *Collection[Space]

List creates a spaces collection

Example
cma := NewCMA("cma-token")
collection, err := cma.Spaces.List(context.TODO()).Next()
if err != nil {
	log.Fatal(err)
}

for _, space := range collection.Items {
	fmt.Println(space.Sys.ID, space.Name)
}

func (*SpacesService) Upsert

func (service *SpacesService) Upsert(ctx context.Context, space *Space) error

Upsert updates or creates a new space

Example (Create)
cma := NewCMA("cma-token")

space := &Space{
	Name:          "space-name",
	DefaultLocale: "en-US",
}

err := cma.Spaces.Upsert(context.TODO(), space)
if err != nil {
	log.Fatal(err)
}
Example (Update)
cma := NewCMA("cma-token")

space, err := cma.Spaces.Get(context.TODO(), "space-id")
if err != nil {
	log.Fatal(err)
}

space.Name = "modified"
err = cma.Spaces.Upsert(context.TODO(), space)
if err != nil {
	log.Fatal(err)
}

type Sys

type Sys struct {
	ID               string       `json:"id,omitempty"`
	Type             string       `json:"type,omitempty"`
	LinkType         string       `json:"linkType,omitempty"`
	CreatedAt        string       `json:"createdAt,omitempty"`
	UpdatedAt        string       `json:"updatedAt,omitempty"`
	UpdatedBy        *Sys         `json:"updatedBy,omitempty"`
	Version          int          `json:"version,omitempty"`
	ArchivedAt       string       `json:"archivedAt,omitempty"`
	ArchivedBy       *Sys         `json:"archivedBy,omitempty"`
	ArchivedVersion  int          `json:"archivedVersion,omitempty"`
	Revision         int          `json:"revision,omitempty"`
	ContentType      *ContentType `json:"contentType,omitempty"`
	Space            *Space       `json:"space,omitempty"`
	FirstPublishedAt string       `json:"firstPublishedAt,omitempty"`
	PublishedCounter int          `json:"publishedCounter,omitempty"`
	PublishedAt      string       `json:"publishedAt,omitempty"`
	PublishedBy      *Sys         `json:"publishedBy,omitempty"`
	PublishedVersion int          `json:"publishedVersion,omitempty"`
	Locale           string       `json:"locale,omitempty"`
}

Sys model

type Tag

type Tag struct {
	Sys  *Sys   `json:"sys"`
	Name string `json:"name,omitempty"`
}

Tag model

type TagsService

type TagsService service

TagsService servıce

func (*TagsService) Get

func (service *TagsService) Get(ctx context.Context, spaceID, tagID string, locale ...string) (*Tag, error)

Get returns a single entry

func (*TagsService) List

func (service *TagsService) List(ctx context.Context, spaceID string) *Collection[Tag]

List returns tags collection

type Upload

type Upload struct {
	Sys Sys `json:"sys"`
}

type UploadService

type UploadService service

UploadService service

func (*UploadService) Uploads

func (service *UploadService) Uploads(ctx context.Context, spaceID string, file io.Reader) (*Upload, error)

Uploads creates a new upload and returns a reference ID

type ValidationFailedError

type ValidationFailedError struct {
	APIError
}

ValidationFailedError model

func (ValidationFailedError) Error

func (e ValidationFailedError) Error() string

type VersionMismatchError

type VersionMismatchError struct {
	APIError
}

VersionMismatchError for 409 errors

func (VersionMismatchError) Error

func (e VersionMismatchError) Error() string

type Webhook

type Webhook struct {
	Sys               *Sys             `json:"sys,omitempty"`
	Name              string           `json:"name,omitempty"`
	URL               string           `json:"url,omitempty"`
	Topics            []string         `json:"topics,omitempty"`
	HTTPBasicUsername string           `json:"httpBasicUsername,omitempty"`
	HTTPBasicPassword string           `json:"httpBasicPassword,omitempty"`
	Headers           []*WebhookHeader `json:"headers,omitempty"`
}

Webhook model

func (*Webhook) GetVersion

func (webhook *Webhook) GetVersion() int

GetVersion returns entity version

type WebhookHeader

type WebhookHeader struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

WebhookHeader model

type WebhooksService

type WebhooksService service

WebhooksService service

func (*WebhooksService) Delete

func (service *WebhooksService) Delete(ctx context.Context, spaceID string, webhook *Webhook) error

Delete the webhook

func (*WebhooksService) Get

func (service *WebhooksService) Get(ctx context.Context, spaceID, webhookID string) (*Webhook, error)

Get returns a single webhook entity

func (*WebhooksService) List

func (service *WebhooksService) List(ctx context.Context, spaceID string) *Collection[Webhook]

List returns webhooks collection

func (*WebhooksService) Upsert

func (service *WebhooksService) Upsert(ctx context.Context, spaceID string, webhook *Webhook) error

Upsert updates or creates a new entity

Jump to

Keyboard shortcuts

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