bunnystorage

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2023 License: MIT Imports: 21 Imported by: 0

README

bunnystorage-go

Go Documentation Go Report Card builds.sr.ht status

Package bunnystorage is a simple and easy-to-use package for interacting with the Bunny.net Edge Storage API. It provides a convenient way to manage files in your storage zones.

Installation

To install bunnystorage, run:

go get git.sr.ht/~jamesponddotco/bunnystorage-go

Usage

package main

import (
	"context"
	"log"
	"os"

	"git.sr.ht/~jamesponddotco/bunnystorage-go"
)

func main() {
	readOnlyKey, ok := os.LookupEnv("BUNNYNET_READ_API_KEY")
	if !ok {
		log.Fatal("missing env var: BUNNYNET_READ_API_KEY")
	}

	readWriteKey, ok := os.LookupEnv("BUNNYNET_WRITE_API_KEY")
	if !ok {
		log.Fatal("missing env var: BUNNYNET_WRITE_API_KEY")
	}

	// Create new Config to be initialize a Client.
	cfg := &bunnystorage.Config{
		Application: &bunnystorage.Application{
			Name:    "My Application",
			Version: "1.0.0",
			Contact: "contact@example.com",
		},
		StorageZone: "my-storage-zone",
		Key:         readWriteKey,
		ReadOnlyKey: readOnlyKey,
		Endpoint:    bunnystorage.EndpointFalkenstein,
	}

	// Create a new Client instance with the given Config.
	client, err := bunnystorage.NewClient(cfg)
	if err != nil {
		log.Fatal(err)
	}

	// List files in the storage zone.
	files, _, err := client.List(context.Background(), "/")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		log.Printf("File: %s, Size: %d\n", file.ObjectName, file.Length)
	}
}

For more examples and usage details, please check the Go reference documentation.

Contributing

Anyone can help make bunnystorage better. Check out the contribution guidelines for more information.

Resources

The following resources are available:


Released under the MIT License.

Documentation

Overview

Package bunnystorage provides an API client to the BunnyCDN Storage API.

Index

Constants

View Source
const (
	// ErrInvalidApplication is returned when an application is invalid.
	ErrInvalidApplication xerrors.Error = "invalid application"

	// ErrInvalidConfig is returned when Config is invalid.
	ErrInvalidConfig xerrors.Error = "invalid config"

	// ErrInvalidEndpoint is returned when an endpoint is invalid.
	ErrInvalidEndpoint xerrors.Error = "invalid endpoint"

	// ErrStorageZoneRequired is returned when a Config is created without a
	// storage zone.
	ErrStorageZoneRequired xerrors.Error = "storage zone required"

	// ErrStorageZoneNameRequired is returned when a storage zone is created
	// without a name.
	ErrStorageZoneNameRequired xerrors.Error = "storage zone name required"

	// ErrStorageZoneKeyRequired is returned when a storage zone is created
	// without an API key.
	ErrStorageZoneKeyRequired xerrors.Error = "storage zone key required"

	// ErrEndpointRequired is returned when a Config is created without an
	// endpoint.
	ErrEndpointRequired xerrors.Error = "endpoint required"

	// ErrApplicationRequired is returned when a Config is created without an
	// application.
	ErrApplicationRequired xerrors.Error = "application required"

	// ErrApplicationNameRequired is returned when an application is created
	// without a name.
	ErrApplicationNameRequired xerrors.Error = "application name required"

	// ErrApplicationVersionRequired is returned when an application is created
	// without a version.
	ErrApplicationVersionRequired xerrors.Error = "application version required"

	// ErrApplicationContactRequired is returned when an application is created
	// without contact information.
	ErrApplicationContactRequired xerrors.Error = "application contact required"

	// ErrApplicationKeyRequired is returned when an application is created
	// without an API key.
	ErrApplicationKeyRequired xerrors.Error = "application key required"
)
View Source
const (
	DefaultMaxRetries int           = 3
	DefaultTimeout    time.Duration = 60 * time.Second
)

Default values for the Config struct.

View Source
const (
	// ErrConfigRequired is returned when a Client is created without a Config.
	ErrConfigRequired xerrors.Error = "config is required"
)

Variables

This section is empty.

Functions

func ComputeSHA256 added in v0.3.0

func ComputeSHA256(r io.Reader) (string, error)

ComputeSHA256 returns the SHA256 hash of the given string as a hex string.

Types

type Application

type Application struct {
	// Name is the name of the application.
	Name string

	// Version is the version of the application.
	Version string

	// Contact is the contact information for the application. Either an email
	// or an URL.
	Contact string
}

Application represents the application that is making requests to the API.

func DefaultApplication

func DefaultApplication() *Application

DefaultApplication returns a new Application with default values.

func (*Application) UserAgent

func (a *Application) UserAgent() *httpx.UserAgent

UserAgent returns the user agent string for the application.

type Client

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

Client is the LanguageTool API client.

func NewClient

func NewClient(cfg *Config) (*Client, error)

NewClient returns a new bunny.net Edge Storage API client.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path, filename string) (*Response, error)

Delete deletes a file from the storage zone.

func (*Client) Download

func (c *Client) Download(ctx context.Context, path, filename string) ([]byte, *Response, error)

Download downloads a file from the storage zone.

func (*Client) List

func (c *Client) List(ctx context.Context, path string) ([]*Object, *Response, error)

List lists the files in the storage zone.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, path, filename, checksum string, body io.Reader) (*Response, error)

Upload uploads a file to the storage zone.

type Config

type Config struct {
	// Application is the application that is making requests to the API.
	Application *Application

	// Logger is the logger to use for logging requests when debugging.
	Logger Logger

	// StorageZone is the name of the storage zone to connect to.
	StorageZone string

	// Key is the API key used to authenticate with the API. The storage zone
	// password also doubles as your key.
	Key string

	// ReadOnlyKey is the read-only API key used to authenticate with the API.
	// This key is optional and only used for read-only operations.
	ReadOnlyKey string

	// Endpoint is the endpoint to use for the API.
	Endpoint Endpoint

	// MaxRetries specifies the maximum number of times to retry a request if it
	// fails due to rate limiting.
	//
	// This field is optional.
	MaxRetries int

	// Timeout is the time limit for requests made by the client to the  API.
	//
	// This field is optional.
	Timeout time.Duration

	// Debug specifies whether or not to enable debug logging.
	//
	// This field is optional.
	Debug bool
	// contains filtered or unexported fields
}

Config holds the basic configuration for the Bunny.net Storage API.

func (*Config) AccessKey

func (c *Config) AccessKey(op Operation) string

AccessKey returns the API key to use for the given operation.

type Endpoint

type Endpoint int

Endpoint represents the primary storage region of a storage zone.

const (
	EndpointFalkenstein Endpoint = iota + 1
	EndpointNewYork
	EndpointLosAngeles
	EndpointSingapore
	EndpointSydney
	EndpointLondon
	EndpointStockholm
	EndpointSaoPaulo
	EndpointJohannesburg
	EndpointLocalhost // For testing purposes only
)

The following endpoints are available for use with the Edge Storage API.

func Parse added in v0.2.0

func Parse(s string) Endpoint

Parse parses a string representation of an endpoint into an Endpoint. If the string is not a valid endpoint, EndpointFalkenstein is returned.

func (Endpoint) IsValid

func (e Endpoint) IsValid() bool

IsValid returns true if the endpoint is a valid Bunny.net endpoint.

func (Endpoint) String

func (e Endpoint) String() string

String returns the string representation of the endpoint.

type Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger defines the interface for logging. It is basically a thin wrapper around the standard logger which implements only a subset of the logger API.

type Object

type Object struct {
	UserID          string `json:"UserId,omitempty"`
	ContentType     string `json:"ContentType,omitempty"`
	Path            string `json:"Path,omitempty"`
	ObjectName      string `json:"ObjectName,omitempty"`
	ReplicatedZones string `json:"ReplicatedZones,omitempty"`
	LastChanged     string `json:"LastChanged,omitempty"`
	StorageZoneName string `json:"StorageZoneName,omitempty"`
	Checksum        string `json:"Checksum,omitempty"`
	DateCreated     string `json:"DateCreated,omitempty"`
	GUID            string `json:"Guid,omitempty"`
	Length          int    `json:"Length,omitempty"`
	ServerID        int    `json:"ServerId,omitempty"`
	StorageZoneID   int    `json:"StorageZoneId,omitempty"`
	ArrayNumber     int    `json:"ArrayNumber,omitempty"`
	IsDirectory     bool   `json:"IsDirectory,omitempty"`
}

Object represents a file or directory in the BunnyCDN Storage API.

type Operation

type Operation int

Operation represents an operation that can be performed on a Bunny.net Storage API.

const (
	OperationRead Operation = iota
	OperationWrite
)

type Response

type Response struct {
	// Header contains the response headers.
	Header http.Header

	// Body contains the response body as a byte slice.
	Body []byte

	// Status is the HTTP status code of the response.
	Status int
}

Response represents a response from the BunnyCDN Storage API.

Directories

Path Synopsis
cmd
bunnystoragectl/internal/app
Package app is the main package for the application.
Package app is the main package for the application.
bunnystoragectl/internal/meta
Package meta provides build information and other metadata for the application.
Package meta provides build information and other metadata for the application.
bunnystoragectl/internal/osutil
Package osutil provides useful functions and utilities for working with the operating system.
Package osutil provides useful functions and utilities for working with the operating system.
internal
build
Package build provides build information about [the bunnystorage package].
Package build provides build information about [the bunnystorage package].
testutil
Package testutil provides utilities for testing.
Package testutil provides utilities for testing.
tests
integration
Package integration contains integration tests for the Bunny Storage client.
Package integration contains integration tests for the Bunny Storage client.

Jump to

Keyboard shortcuts

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