azqueue

package
v0.0.0-...-648530c Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2023 License: MIT Imports: 27 Imported by: 44

Documentation

Overview

Package azqueue allows you to manipulate Azure Storage queues and their messages.

URL Types

The most common types you'll work with are the XxxURL types. The methods of these types make requests against the Azure Storage Service.

  • ServiceURL's methods perform operations on a storage account.
  • QueueURL's methods perform operations on an account's queue.
  • MessagesURL's methods perform operations with a queue's messages.

Internally, each XxxURL object contains a URL and a request pipeline. The URL indicates the endpoint where each HTTP request is sent and the pipeline indicates how the outgoing HTTP request and incoming HTTP response is processed. The pipeline specifies things like retry policies, logging, deserialization of HTTP response payloads, and more.

Pipelines are threadsafe and may be shared by multiple XxxURL objects. When you create a ServiceURL, you pass an initial pipeline. When you call ServiceURL's NewQueueURL method, the new QueueURL object has its own URL but it shares the same pipeline as the parent ServiceURL object. To work with a queue's messages, call QueueURL's NewMessagesURL method.

If you'd like to use a different pipeline with a ServiceURL, QueueURL, or MessagesURL object, then call the XxxURL object's WithPipeline method passing in the desired pipeline. The WithPipeline methods create a new XxxURL object with the same URL as the original but with the specified pipeline.

Note that XxxURL objects use little memory, are goroutine-safe, and many objects share the same pipeline. This means that XxxURL objects share a lot of system resources making them very efficient.

All of XxxURL's methods that make HTTP requests return rich error handling information so you can discern network failures, transient failures, timeout failures, service failures, etc. See the StorageError interface for more information and an example of how to do deal with errors.

URL and Shared Access Signature Manipulation

The library includes a QueueURLParts type for deconstructing and reconstructing URLs. And you can use the following types for generating and parsing Shared Access Signature (SAS)

  • Use the AccountSASSignatureValues type to create a SAS for a storage account.
  • Use the QueueSASSignatureValues type to create a SAS for a queue.
  • Use the SASQueryParameters type to examine SAS query parameres.

To generate a SAS, you must use the SharedKeyCredential type.

Credentials

When creating a request pipeline, you must specify one of this package's credential types.

  • Call the NewAnonymousCredential function for requests that contain a Shared Access Signature (SAS).
  • Call the NewSharedKeyCredential function (with an account name & key) to access any account resources. You must also use this to generate Shared Access Signatures.

HTTP Request Policy Factories

This package defines several request policy factories for use with the pipeline package. Most applications will not use these factories directly; instead, the NewPipeline function creates these factories, initializes them (via the PipelineOptions type) and returns a pipeline object for use by the XxxURL objects.

However, for advanced scenarios, developers can access these policy factories directly and even create their own and then construct their own pipeline in order to affect HTTP requests and responses performed by the XxxURL objects. For example, developers can introduce their own logging, random failures, request recording & playback for fast testing, HTTP request pacing, alternate retry mechanisms, metering, metrics, etc. The possibilities are endless!

Below are the request pipeline policy factory functions that are provided with this package:

  • NewRetryPolicyFactory Enables rich retry semantics for failed HTTP requests.
  • NewRequestLogPolicyFactory Enables rich logging support for HTTP requests/responses & failures.
  • NewTelemetryPolicyFactory Enables simple modification of the HTTP request's User-Agent header so each request reports the SDK version & language/runtime making the requests.
  • NewUniqueRequestIDPolicyFactory Adds a x-ms-client-request-id header with a unique UUID value to an HTTP request to help with diagnosing failures.

Also, note that all the NewXxxCredential functions return request policy factory objects which get injected into the pipeline.

Example

This example shows how to get started using the Azure Storage Queue SDK for Go.

package main

import (
	"context"
	"fmt"
	"log"
	"net/url"
	"os"
	"time"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create a request pipeline that is used to process HTTP(S) requests and responses. It requires
	// your account credentials. In more advanced scenarios, you can configure telemetry, retry policies,
	// logging, and other options. Also, you can configure multiple request pipelines for different scenarios.
	p := azqueue.NewPipeline(credential, azqueue.PipelineOptions{})

	// From the Azure portal, get your Storage account queue service URL endpoint.
	// The URL typically looks like this:
	u, _ := url.Parse(fmt.Sprintf("https://%s.queue.core.windows.net", accountName))

	// Create an ServiceURL object that wraps the service URL and a request pipeline.
	serviceURL := azqueue.NewServiceURL(*u, p)

	// Now, you can use the serviceURL to perform various queue operations.

	// All HTTP operations allow you to specify a Go context.Context object to control cancellation/timeout.
	ctx := context.TODO() // This example uses a never-expiring context.

	// Create a URL that references a queue in your Azure Storage account.
	// This returns a QueueURL object that wraps the queue's URL and a request pipeline (inherited from serviceURL)
	queueURL := serviceURL.NewQueueURL("examplequeue") // Queue names require lowercase

	// The code below shows how to create the queue. It is common to create a queue and never delete it:
	_, err = queueURL.Create(ctx, azqueue.Metadata{})
	if err != nil {
		log.Fatal(err)
	}

	// The code below shows how a client application enqueues 2 messages into the queue:
	// Create a URL allowing you to manipulate a queue's messages.
	// This returns a MessagesURL object that wraps the queue's messages URL and a request pipeline (inherited from queueURL)
	messagesURL := queueURL.NewMessagesURL()

	// Enqueue 2 messages
	_, err = messagesURL.Enqueue(ctx, "This is message 1", time.Second*0, time.Minute)
	if err != nil {
		log.Fatal(err)
	}
	_, err = messagesURL.Enqueue(ctx, "This is message 2", time.Second*0, time.Minute)
	if err != nil {
		log.Fatal(err)
	}

	// The code below shows how a client or server can determine the approximate count of messages in the queue:
	props, err := queueURL.GetProperties(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Approximate number of messages in the queue=%d\n", props.ApproximateMessagesCount())

	// The code below shows how to initialize a service that wishes to process messages:
	const concurrentMsgProcessing = 16 // Set this as you desire
	msgCh := make(chan *azqueue.DequeuedMessage, concurrentMsgProcessing)
	const poisonMessageDequeueThreshold = 4 // Indicates how many times a message is attempted to be processed before considering it a poison message

	// Create goroutines that can process messages in parallel
	for n := 0; n < concurrentMsgProcessing; n++ {
		go func(msgCh <-chan *azqueue.DequeuedMessage) {
			for {
				msg := <-msgCh // Get a message from the channel

				// Create a URL allowing you to manipulate this message.
				// This returns a MessageIDURL object that wraps the this message's URL and a request pipeline (inherited from messagesURL)
				msgIDURL := messagesURL.NewMessageIDURL(msg.ID)
				popReceipt := msg.PopReceipt // This message's most-recent pop receipt

				if msg.DequeueCount > poisonMessageDequeueThreshold {
					// This message has attempted to be processed too many times; treat it as a poison message
					// DO NOT attempt to process this message
					// Log this message as a poison message somewhere (code not shown)
					// Delete this poison message from the queue so it will never be dequeued again
					msgIDURL.Delete(ctx, popReceipt)
					continue // Process a different message
				}

				// This message is not a poison message, process it (this example just displays it):
				fmt.Print(msg.Text + "\n")

				// NOTE: You can examine/use any of the message's other properties as you desire:
				_, _, _ = msg.InsertionTime, msg.ExpirationTime, msg.NextVisibleTime

				// OPTIONAL: while processing a message, you can update the message's visibility timeout
				// (to prevent other servers from dequeuing the same message simultaneously) and update the
				// message's text (to prevent some successfully-completed processing from re-executing the
				// next time this message is dequeued):
				update, err := msgIDURL.Update(ctx, popReceipt, time.Second*20, "updated msg")
				if err != nil {
					log.Fatal(err)
				}
				popReceipt = update.PopReceipt // Performing any operation on a message ID always requires the most recent pop receipt

				// After processing the message, delete it from the queue so it won't be dequeued ever again:
				_, err = msgIDURL.Delete(ctx, popReceipt)
				if err != nil {
					log.Fatal(err)
				}
				// Loop around to process the next message
			}
		}(msgCh)
	}

	// The code below shows the service's infinite loop that dequeues messages and dispatches them in batches for processsing:
	for {
		// Try to dequeue a batch of messages from the queue
		dequeue, err := messagesURL.Dequeue(ctx, azqueue.QueueMaxMessagesDequeue, 10*time.Second)
		if err != nil {
			log.Fatal(err)
		}
		if dequeue.NumMessages() == 0 {
			// The queue was empty; sleep a bit and try again
			// Shorter time means higher costs & less latency to dequeue a message
			// Higher time means lower costs & more latency to dequeue a message
			time.Sleep(time.Second * 10)
		} else {
			// We got some messages, put them in the channel so that many can be processed in parallel:
			// NOTE: The queue does not guarantee FIFO ordering & processing messages in parallel also does
			// not preserve FIFO ordering. So, the "Output:" order below is not guaranteed but usually works.
			for m := int32(0); m < dequeue.NumMessages(); m++ {
				msgCh <- dequeue.Message(m)
			}
		}
		// This batch of dequeued messages are in the channel, dequeue another batch
		break // NOTE: For this example only, break out of the infinite loop so this example terminates
	}

	time.Sleep(time.Second * 10) // For this example, delay in hopes that both messages complete processing before the example terminates

	// This example deletes the queue (to clean up) but normally, you never delete a queue.
	_, err = queueURL.Delete(ctx)
	if err != nil {
		log.Fatal(err)
	}

}
Output:

Approximate number of messages in the queue=2
This is message 1
This is message 2

Index

Examples

Constants

View Source
const (
	// QueueMaxMessagesDequeue indicates the maximum number of messages
	// you can retrieve with each call to Dequeue (32).
	QueueMaxMessagesDequeue = 32

	// QueueMaxMessagesPeek indicates the maximum number of messages
	// you can retrieve with each call to Peek (32).
	QueueMaxMessagesPeek = 32

	// QueueMessageMaxBytes indicates the maximum number of bytes allowed for a message's UTF-8 text.
	QueueMessageMaxBytes = 64 * 1024 // 64KB
)
View Source
const SASTimeFormat = "2006-01-02T15:04:05Z" //"2017-07-27T00:00:00Z" // ISO 8601

SASTimeFormat represents the format of a SAS start or expiry time. Use it when formatting/parsing a time.Time.

View Source
const SASVersion = ServiceVersion

SASVersion indicates the SAS version.

View Source
const (
	// ServiceVersion specifies the version of the operations used in this package.
	ServiceVersion = "2018-03-28"
)

Variables

This section is empty.

Functions

func FormatTimesForSASSigning

func FormatTimesForSASSigning(startTime, expiryTime time.Time) (string, string)

FormatTimesForSASSigning converts a time.Time to a snapshotTimeFormat string suitable for a SASField's StartTime or ExpiryTime fields. Returns "" if value.IsZero().

func NewPipeline

func NewPipeline(c Credential, o PipelineOptions) pipeline.Pipeline

NewPipeline creates a Pipeline using the specified credentials and options.

Example

This example shows how you can configure a pipeline for making HTTP requests to the Azure Storage Queue Service.

package main

import (
	"log"
	"net/url"
	"os"
	"time"

	"github.com/Azure/azure-pipeline-go/pipeline"
	"github.com/Azure/azure-storage-queue-go/azqueue"
)

func main() {
	// This example shows how to wire in your own logging mechanism (this example uses
	// Go's standard logger to write log information to standard error)
	logger := log.New(os.Stderr, "", log.Ldate|log.Lmicroseconds)

	// Create/configure a request pipeline options object.
	// All PipelineOptions' fields are optional; reasonable defaults are set for anything you do not specify
	po := azqueue.PipelineOptions{
		// Set RetryOptions to control how HTTP request are retried when retryable failures occur
		Retry: azqueue.RetryOptions{
			Policy:        azqueue.RetryPolicyExponential, // Use exponential backoff as opposed to fixed
			MaxTries:      3,                              // Try at most 3 times to perform the operation (set to 1 to disable retries)
			TryTimeout:    time.Second * 3,                // Maximum time allowed for any single try
			RetryDelay:    time.Second * 1,                // Backoff amount for each retry (exponential or fixed)
			MaxRetryDelay: time.Second * 3,                // Max delay between retries
		},

		// Set RequestLogOptions to control how each HTTP request & its response is logged
		RequestLog: azqueue.RequestLogOptions{
			LogWarningIfTryOverThreshold: time.Millisecond * 200, // A successful response taking more than this time to arrive is logged as a warning
		},

		// Set LogOptions to control what & where all pipeline log events go
		Log: pipeline.LogOptions{
			ShouldLog: func(level pipeline.LogLevel) bool {
				return level <= pipeline.LogWarning // Log all events from warning to more severe
			},
			Log: func(s pipeline.LogLevel, m string) { // This func is called to log each event
				// This method is not called for filtered-out severities.
				logger.Output(2, m) // This example uses Go's standard logger
			}},
	}

	// Create a request pipeline object configured with credentials and with pipeline options. Once created,
	// a pipeline object is goroutine-safe and can be safely used with many XxxURL objects simultaneously.
	p := azqueue.NewPipeline(azqueue.NewAnonymousCredential(), po) // A pipeline always requires some credential object

	// Once you've created a pipeline object, associate it with an XxxURL object so that you can perform HTTP requests with it.
	u, _ := url.Parse("https://myaccount.queue.core.windows.net")
	serviceURL := azqueue.NewServiceURL(*u, p)
	// Use the serviceURL as desired...

	// NOTE: When you use an XxxURL object to create another XxxURL object, the new XxxURL object inherits the
	// same pipeline object as its parent. For example, the queueURL and messagesURL objects (created below)
	// all share the same pipeline. Any HTTP operations you perform with these objects share the behavior (retry, logging, etc.)
	queueURL := serviceURL.NewQueueURL("myqueue1")
	messagesURL := queueURL.NewMessagesURL()

	// If you'd like to perform some operations with different behavior, create a new pipeline object and
	// associate it with a new XxxURL object by passing the new pipeline to the XxxURL object's WithPipeline method.

	// In this example, I reconfigure the retry policies, create a new pipeline, and then create a new
	// QueueURL object that has the same URL as its parent.
	po.Retry = azqueue.RetryOptions{
		Policy:        azqueue.RetryPolicyFixed, // Use fixed backoff as opposed to exponential
		MaxTries:      4,                        // Try at most 4 times to perform the operation (set to 1 to disable retries)
		TryTimeout:    time.Minute * 1,          // Maximum time allowed for any single try
		RetryDelay:    time.Second * 5,          // Backoff amount for each retry (exponential or fixed)
		MaxRetryDelay: time.Second * 10,         // Max delay between retries
	}
	newQueueURL := queueURL.WithPipeline(azqueue.NewPipeline(azqueue.NewAnonymousCredential(), po))

	// Now, any MessagesURL object created using newQueueURL inherits the pipeline with the new retry policy.
	newMessagesURL := newQueueURL.NewMessagesURL()
	_, _ = messagesURL, newMessagesURL // Avoid compiler's "declared and not used" error
}
Output:

func NewRequestLogPolicyFactory

func NewRequestLogPolicyFactory(o RequestLogOptions) pipeline.Factory

NewRequestLogPolicyFactory creates a RequestLogPolicyFactory object configured using the specified options.

func NewResponseError

func NewResponseError(cause error, response *http.Response, description string) error

NewResponseError creates an error object that implements the error interface.

func NewRetryPolicyFactory

func NewRetryPolicyFactory(o RetryOptions) pipeline.Factory

NewRetryPolicyFactory creates a RetryPolicyFactory object configured using the specified options.

func NewTelemetryPolicyFactory

func NewTelemetryPolicyFactory(o TelemetryOptions) pipeline.Factory

NewTelemetryPolicyFactory creates a factory that can create telemetry policy objects which add telemetry information to outgoing HTTP requests.

func NewUniqueRequestIDPolicyFactory

func NewUniqueRequestIDPolicyFactory() pipeline.Factory

NewUniqueRequestIDPolicyFactory creates a UniqueRequestIDPolicyFactory object that sets the request's x-ms-client-request-id header if it doesn't already exist.

func UserAgent

func UserAgent() string

UserAgent returns the UserAgent string to use when sending http.Requests.

func Version

func Version() string

Version returns the semantic version (see http://semver.org) of the client.

Types

type AccessPolicy

type AccessPolicy struct {
	// Start - the date-time the policy is active
	Start time.Time `xml:"Start"`
	// Expiry - the date-time the policy expires
	Expiry time.Time `xml:"Expiry"`
	// Permission - the permissions for the acl policy
	Permission string `xml:"Permission"`
}

AccessPolicy - An Access policy

func (AccessPolicy) MarshalXML

func (ap AccessPolicy) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface for AccessPolicy.

func (*AccessPolicy) UnmarshalXML

func (ap *AccessPolicy) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for AccessPolicy.

type AccessPolicyPermission

type AccessPolicyPermission struct {
	Read, Add, Update, ProcessMessages bool
}

The AccessPolicyPermission type simplifies creating the permissions string for a queue's access policy. Initialize an instance of this type and then call its String method to set AccessPolicy's Permission field.

func (*AccessPolicyPermission) Parse

func (p *AccessPolicyPermission) Parse(s string) error

Parse initializes the AccessPolicyPermission's fields from a string.

func (AccessPolicyPermission) String

func (p AccessPolicyPermission) String() string

String produces the access policy permission string for an Azure Storage queue. Call this method to set AccessPolicy's Permission field.

type AccountSASPermissions

type AccountSASPermissions struct {
	Read, Write, Delete, List, Add, Create, Update, Process bool
}

The AccountSASPermissions type simplifies creating the permissions string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's Permissions field.

func (*AccountSASPermissions) Parse

func (p *AccountSASPermissions) Parse(s string) error

Parse initializes the AccountSASPermissions's fields from a string.

func (AccountSASPermissions) String

func (p AccountSASPermissions) String() string

String produces the SAS permissions string for an Azure Storage account. Call this method to set AccountSASSignatureValues's Permissions field.

type AccountSASResourceTypes

type AccountSASResourceTypes struct {
	Service, Container, Object bool
}

The AccountSASResourceTypes type simplifies creating the resource types string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's ResourceTypes field.

func (*AccountSASResourceTypes) Parse

func (rt *AccountSASResourceTypes) Parse(s string) error

Parse initializes the AccountSASResourceType's fields from a string.

func (AccountSASResourceTypes) String

func (rt AccountSASResourceTypes) String() string

String produces the SAS resource types string for an Azure Storage account. Call this method to set AccountSASSignatureValues's ResourceTypes field.

type AccountSASServices

type AccountSASServices struct {
	Blob, Queue, File bool
}

The AccountSASServices type simplifies creating the services string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's Services field.

func (*AccountSASServices) Parse

func (a *AccountSASServices) Parse(s string) error

Parse initializes the AccountSASServices' fields from a string.

func (AccountSASServices) String

func (s AccountSASServices) String() string

String produces the SAS services string for an Azure Storage account. Call this method to set AccountSASSignatureValues's Services field.

type AccountSASSignatureValues

type AccountSASSignatureValues struct {
	Version       string      `param:"sv"`  // If not specified, this defaults to SASVersion
	Protocol      SASProtocol `param:"spr"` // See the SASProtocol* constants
	StartTime     time.Time   `param:"st"`  // Not specified if IsZero
	ExpiryTime    time.Time   `param:"se"`  // Not specified if IsZero
	Permissions   string      `param:"sp"`  // Create by initializing a AccountSASPermissions and then call String()
	IPRange       IPRange     `param:"sip"`
	Services      string      `param:"ss"`  // Create by initializing AccountSASServices and then call String()
	ResourceTypes string      `param:"srt"` // Create by initializing AccountSASResourceTypes and then call String()
}

AccountSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage account. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-an-account-sas

Example

This example shows how to create and use an Azure Storage account Shared Access Signature (SAS).

package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"time"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is required to sign a SAS.
	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query parameters.
	sasQueryParams, err := azqueue.AccountSASSignatureValues{
		Protocol:      azqueue.SASProtocolHTTPS,       // Users MUST use HTTPS (not HTTP)
		ExpiryTime:    time.Now().Add(48 * time.Hour), // 48-hours before expiration
		Permissions:   azqueue.AccountSASPermissions{Read: true, List: true}.String(),
		Services:      azqueue.AccountSASServices{Queue: true}.String(),
		ResourceTypes: azqueue.AccountSASResourceTypes{Object: true}.String(),
	}.NewSASQueryParameters(credential)
	if err != nil {
		log.Fatal(err)
	}

	qp := sasQueryParams.Encode()
	urlToSendToSomeone := fmt.Sprintf("https://%s.queue.core.windows.net?%s", accountName, qp)
	// At this point, you can send the urlToSendToSomeone to someone via email or any other mechanism you choose.

	// ************************************************************************************************

	// When someone receives the URL, they access the SAS-protected resource with code like this:
	u, _ := url.Parse(urlToSendToSomeone)

	// Create an ServiceURL object that wraps the service URL (and its SAS) and a pipeline.
	// When using a SAS URLs, anonymous credentials are required.
	serviceURL := azqueue.NewServiceURL(*u, azqueue.NewPipeline(azqueue.NewAnonymousCredential(), azqueue.PipelineOptions{}))
	// Now, you can use this serviceURL just like any other to make requests of the resource.

	// You can parse a URL into its constituent parts:
	queueURLParts := azqueue.NewQueueURLParts(serviceURL.URL())
	fmt.Printf("SAS Protocol=%v\n", queueURLParts.SAS.Protocol())
	fmt.Printf("SAS Permissions=%v\n", queueURLParts.SAS.Permissions())
	fmt.Printf("SAS Services=%v\n", queueURLParts.SAS.Services())
	fmt.Printf("SAS ResourceTypes=%v\n", queueURLParts.SAS.ResourceTypes())

}
Output:

SAS Protocol=https
SAS Permissions=rl
SAS Services=q
SAS ResourceTypes=o

func (AccountSASSignatureValues) NewSASQueryParameters

func (v AccountSASSignatureValues) NewSASQueryParameters(sharedKeyCredential *SharedKeyCredential) (SASQueryParameters, error)

NewSASQueryParameters uses an account's shared key credential to sign this signature values to produce the proper SAS query parameters.

type CorsRule

type CorsRule struct {
	// AllowedOrigins - The origin domains that are permitted to make a request against the storage service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains to make requests via CORS.
	AllowedOrigins string `xml:"AllowedOrigins"`
	// AllowedMethods - The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated)
	AllowedMethods string `xml:"AllowedMethods"`
	// AllowedHeaders - the request headers that the origin domain may specify on the CORS request.
	AllowedHeaders string `xml:"AllowedHeaders"`
	// ExposedHeaders - The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer
	ExposedHeaders string `xml:"ExposedHeaders"`
	// MaxAgeInSeconds - The maximum amount time that a browser should cache the preflight OPTIONS request.
	MaxAgeInSeconds int32 `xml:"MaxAgeInSeconds"`
}

CorsRule - CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain

type Credential

type Credential interface {
	pipeline.Factory
	// contains filtered or unexported methods
}

Credential represent any credential type; it is used to create a credential policy Factory.

func NewAnonymousCredential

func NewAnonymousCredential() Credential

NewAnonymousCredential creates an anonymous credential for use with HTTP(S) requests that read public resource or for use with Shared Access Signatures (SAS).

type DequeuedMessage

type DequeuedMessage struct {
	ID              MessageID
	InsertionTime   time.Time
	ExpirationTime  time.Time
	PopReceipt      PopReceipt
	NextVisibleTime time.Time
	DequeueCount    int64
	Text            string // UTF-8 string
}

DequeuedMessage holds the properties of a single dequeued message.

type DequeuedMessageItem

type DequeuedMessageItem struct {
	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name `xml:"QueueMessage"`
	// MessageID - The Id of the Message.
	MessageID string `xml:"MessageId"`
	// InsertionTime - The time the Message was inserted into the Queue.
	InsertionTime time.Time `xml:"InsertionTime"`
	// ExpirationTime - The time that the Message will expire and be automatically deleted.
	ExpirationTime time.Time `xml:"ExpirationTime"`
	// PopReceipt - This value is required to delete the Message. If deletion fails using this popreceipt then the message has been dequeued by another client.
	PopReceipt string `xml:"PopReceipt"`
	// TimeNextVisible - The time that the message will again become visible in the Queue.
	TimeNextVisible time.Time `xml:"TimeNextVisible"`
	// DequeueCount - The number of times the message has been dequeued.
	DequeueCount int64 `xml:"DequeueCount"`
	// MessageText - The content of the Message.
	MessageText string `xml:"MessageText"`
}

DequeuedMessageItem - The object returned in the QueueMessageList array when calling Get Messages on a Queue.

func (DequeuedMessageItem) MarshalXML

func (dmi DequeuedMessageItem) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface for DequeuedMessageItem.

func (*DequeuedMessageItem) UnmarshalXML

func (dmi *DequeuedMessageItem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for DequeuedMessageItem.

type DequeuedMessagesResponse

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

DequeueMessagesResponse holds the results of a successful call to Dequeue.

func (DequeuedMessagesResponse) Date

func (dmr DequeuedMessagesResponse) Date() time.Time

Date returns the value for header Date.

func (DequeuedMessagesResponse) Message

func (dmr DequeuedMessagesResponse) Message(index int32) *DequeuedMessage

Message returns the information for dequeued message.

func (DequeuedMessagesResponse) NumMessages

func (dmr DequeuedMessagesResponse) NumMessages() int32

NumMessages returns the number of messages retrieved by the call to Dequeue.

func (DequeuedMessagesResponse) RequestID

func (dmr DequeuedMessagesResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (DequeuedMessagesResponse) Response

func (dmr DequeuedMessagesResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (DequeuedMessagesResponse) Status

func (dmr DequeuedMessagesResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (DequeuedMessagesResponse) StatusCode

func (dmr DequeuedMessagesResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (DequeuedMessagesResponse) Version

func (dmr DequeuedMessagesResponse) Version() string

Version returns the value for header x-ms-version.

type EnqueueMessageResponse

type EnqueueMessageResponse struct {

	// MessageID returns the service-assigned ID for the enqueued message.
	MessageID MessageID

	// PopReceipt returns the service-assigned PopReceipt for the enqueued message.
	// You could use this to create a MessageIDURL object.
	PopReceipt PopReceipt

	// TimeNextVisible returns the time when the message next becomes visible.
	TimeNextVisible time.Time

	// InsertionTime returns the time when the message was enqueued.
	InsertionTime time.Time

	// ExpirationTime returns the time when the message will automatically be deleted from the queue.
	ExpirationTime time.Time
	// contains filtered or unexported fields
}

EnqueueMessageResponse holds the results of a successfully-enqueued message.

func (EnqueueMessageResponse) Date

func (emr EnqueueMessageResponse) Date() time.Time

Date returns the value for header Date.

func (EnqueueMessageResponse) RequestID

func (emr EnqueueMessageResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (EnqueueMessageResponse) Response

func (emr EnqueueMessageResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (EnqueueMessageResponse) Status

func (emr EnqueueMessageResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (EnqueueMessageResponse) StatusCode

func (emr EnqueueMessageResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (EnqueueMessageResponse) Version

func (emr EnqueueMessageResponse) Version() string

Version returns the value for header x-ms-version.

type EnqueueResponse

type EnqueueResponse struct {

	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name          `xml:"QueueMessagesList"`
	Items   []EnqueuedMessage `xml:"QueueMessage"`
	// contains filtered or unexported fields
}

EnqueueResponse - Wraps the response from the messagesClient.Enqueue method.

func (EnqueueResponse) Date

func (er EnqueueResponse) Date() time.Time

Date returns the value for header Date.

func (EnqueueResponse) ErrorCode

func (er EnqueueResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (EnqueueResponse) RequestID

func (er EnqueueResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (EnqueueResponse) Response

func (er EnqueueResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (EnqueueResponse) Status

func (er EnqueueResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (EnqueueResponse) StatusCode

func (er EnqueueResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (EnqueueResponse) Version

func (er EnqueueResponse) Version() string

Version returns the value for header x-ms-version.

type EnqueuedMessage

type EnqueuedMessage struct {
	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name `xml:"QueueMessage"`
	// MessageID - The Id of the Message.
	MessageID string `xml:"MessageId"`
	// InsertionTime - The time the Message was inserted into the Queue.
	InsertionTime time.Time `xml:"InsertionTime"`
	// ExpirationTime - The time that the Message will expire and be automatically deleted.
	ExpirationTime time.Time `xml:"ExpirationTime"`
	// PopReceipt - This value is required to delete the Message. If deletion fails using this popreceipt then the message has been dequeued by another client.
	PopReceipt string `xml:"PopReceipt"`
	// TimeNextVisible - The time that the message will again become visible in the Queue.
	TimeNextVisible time.Time `xml:"TimeNextVisible"`
}

EnqueuedMessage - The object returned in the QueueMessageList array when calling Put Message on a Queue

func (EnqueuedMessage) MarshalXML

func (em EnqueuedMessage) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface for EnqueuedMessage.

func (*EnqueuedMessage) UnmarshalXML

func (em *EnqueuedMessage) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for EnqueuedMessage.

type GeoReplication

type GeoReplication struct {
	// Status - The status of the secondary location. Possible values include: 'GeoReplicationStatusLive', 'GeoReplicationStatusBootstrap', 'GeoReplicationStatusUnavailable', 'GeoReplicationStatusNone'
	Status GeoReplicationStatusType `xml:"Status"`
	// LastSyncTime - A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to be available for read operations at the secondary. Primary writes after this point in time may or may not be available for reads.
	LastSyncTime time.Time `xml:"LastSyncTime"`
}

GeoReplication ...

func (GeoReplication) MarshalXML

func (gr GeoReplication) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface for GeoReplication.

func (*GeoReplication) UnmarshalXML

func (gr *GeoReplication) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for GeoReplication.

type GeoReplicationStatusType

type GeoReplicationStatusType string

GeoReplicationStatusType enumerates the values for geo replication status type.

const (
	// GeoReplicationStatusBootstrap ...
	GeoReplicationStatusBootstrap GeoReplicationStatusType = "bootstrap"
	// GeoReplicationStatusLive ...
	GeoReplicationStatusLive GeoReplicationStatusType = "live"
	// GeoReplicationStatusNone represents an empty GeoReplicationStatusType.
	GeoReplicationStatusNone GeoReplicationStatusType = ""
	// GeoReplicationStatusUnavailable ...
	GeoReplicationStatusUnavailable GeoReplicationStatusType = "unavailable"
)

func PossibleGeoReplicationStatusTypeValues

func PossibleGeoReplicationStatusTypeValues() []GeoReplicationStatusType

PossibleGeoReplicationStatusTypeValues returns an array of possible values for the GeoReplicationStatusType const type.

type IPRange

type IPRange struct {
	Start net.IP // Not specified if length = 0
	End   net.IP // Not specified if length = 0
}

IPRange represents a SAS IP range's start IP and (optionally) end IP.

func (*IPRange) String

func (ipr *IPRange) String() string

String returns a string representation of an IPRange.

type ListQueuesIncludeType

type ListQueuesIncludeType string

ListQueuesIncludeType enumerates the values for list queues include type.

const (
	// ListQueuesIncludeMetadata ...
	ListQueuesIncludeMetadata ListQueuesIncludeType = "metadata"
	// ListQueuesIncludeNone represents an empty ListQueuesIncludeType.
	ListQueuesIncludeNone ListQueuesIncludeType = ""
)

func PossibleListQueuesIncludeTypeValues

func PossibleListQueuesIncludeTypeValues() []ListQueuesIncludeType

PossibleListQueuesIncludeTypeValues returns an array of possible values for the ListQueuesIncludeType const type.

type ListQueuesSegmentDetails

type ListQueuesSegmentDetails struct {
	// Tells the service whether to return metadata for each queue.
	Metadata bool
}

ListQueuesSegmentDetails indicates what additional information the service should return with each queue.

type ListQueuesSegmentOptions

type ListQueuesSegmentOptions struct {
	Detail ListQueuesSegmentDetails // No IncludeType header is produced if ""
	Prefix string                   // No Prefix header is produced if ""

	// SetMaxResults sets the maximum desired results you want the service to return.
	// Note, the service may return fewer results than requested.
	// MaxResults=0 means no 'MaxResults' header specified.
	MaxResults int32
}

ListQueuesSegmentOptions defines options available when calling ListQueuesSegment.

type ListQueuesSegmentResponse

type ListQueuesSegmentResponse struct {

	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName         xml.Name    `xml:"EnumerationResults"`
	ServiceEndpoint string      `xml:"ServiceEndpoint,attr"`
	Prefix          string      `xml:"Prefix"`
	Marker          *string     `xml:"Marker"`
	MaxResults      int32       `xml:"MaxResults"`
	QueueItems      []QueueItem `xml:"Queues>Queue"`
	NextMarker      Marker      `xml:"NextMarker"`
	// contains filtered or unexported fields
}

ListQueuesSegmentResponse - The object returned when calling List Queues on a Queue Service.

func (ListQueuesSegmentResponse) Date

func (lqsr ListQueuesSegmentResponse) Date() time.Time

Date returns the value for header Date.

func (ListQueuesSegmentResponse) ErrorCode

func (lqsr ListQueuesSegmentResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (ListQueuesSegmentResponse) RequestID

func (lqsr ListQueuesSegmentResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (ListQueuesSegmentResponse) Response

func (lqsr ListQueuesSegmentResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (ListQueuesSegmentResponse) Status

func (lqsr ListQueuesSegmentResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (ListQueuesSegmentResponse) StatusCode

func (lqsr ListQueuesSegmentResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (ListQueuesSegmentResponse) Version

func (lqsr ListQueuesSegmentResponse) Version() string

Version returns the value for header x-ms-version.

type Logging

type Logging struct {
	// Version - The version of Storage Analytics to configure.
	Version string `xml:"Version"`
	// Delete - Indicates whether all delete requests should be logged.
	Delete bool `xml:"Delete"`
	// Read - Indicates whether all read requests should be logged.
	Read bool `xml:"Read"`
	// Write - Indicates whether all write requests should be logged.
	Write           bool            `xml:"Write"`
	RetentionPolicy RetentionPolicy `xml:"RetentionPolicy"`
}

Logging - Azure Analytics Logging settings.

type Marker

type Marker struct {
	Val *string
}

Marker represents an opaque value used in paged responses.

func (Marker) NotDone

func (m Marker) NotDone() bool

NotDone returns true if the list enumeration should be started or is not yet complete. Specifically, NotDone returns true for a just-initialized (zero value) Marker indicating that you should make an initial request to get a result portion from the service. NotDone also returns true whenever the service returns an interim result portion. NotDone returns false only after the service has returned the final result portion.

func (*Marker) UnmarshalXML

func (m *Marker) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for Marker.

type MessageID

type MessageID string

MessageID represents a Message ID as a string.

func (MessageID) String

func (id MessageID) String() string

String returns a MessageID as a string

type MessageIDDeleteResponse

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

MessageIDDeleteResponse ...

func (MessageIDDeleteResponse) Date

func (midr MessageIDDeleteResponse) Date() time.Time

Date returns the value for header Date.

func (MessageIDDeleteResponse) ErrorCode

func (midr MessageIDDeleteResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (MessageIDDeleteResponse) RequestID

func (midr MessageIDDeleteResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (MessageIDDeleteResponse) Response

func (midr MessageIDDeleteResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (MessageIDDeleteResponse) Status

func (midr MessageIDDeleteResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (MessageIDDeleteResponse) StatusCode

func (midr MessageIDDeleteResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (MessageIDDeleteResponse) Version

func (midr MessageIDDeleteResponse) Version() string

Version returns the value for header x-ms-version.

type MessageIDURL

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

A MessageIDURL represents a URL to a specific Azure Storage Queue message allowing you to manipulate the message.

func NewMessageIDURL

func NewMessageIDURL(url url.URL, p pipeline.Pipeline) MessageIDURL

NewMessageIDURL creates a MessageIDURL object using the specified URL and request policy pipeline.

func (MessageIDURL) Delete

func (m MessageIDURL) Delete(ctx context.Context, popReceipt PopReceipt) (*MessageIDDeleteResponse, error)

Delete permanently removes the specified message from its queue. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-message2.

func (MessageIDURL) String

func (m MessageIDURL) String() string

String returns the URL as a string.

func (MessageIDURL) URL

func (m MessageIDURL) URL() url.URL

URL returns the URL endpoint used by the MessageIDURL object.

func (MessageIDURL) Update

func (m MessageIDURL) Update(ctx context.Context, popReceipt PopReceipt, visibilityTimeout time.Duration, message string) (*UpdatedMessageResponse, error)

Update changes a message's visibility timeout and contents. The message content must be a UTF-8 encoded string that is up to 64KB in size. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/update-message.

func (MessageIDURL) WithPipeline

func (m MessageIDURL) WithPipeline(p pipeline.Pipeline) MessageIDURL

WithPipeline creates a new MessageIDURL object identical to the source but with the specified request policy pipeline.

type MessageIDUpdateResponse

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

MessageIDUpdateResponse ...

func (MessageIDUpdateResponse) Date

func (miur MessageIDUpdateResponse) Date() time.Time

Date returns the value for header Date.

func (MessageIDUpdateResponse) ErrorCode

func (miur MessageIDUpdateResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (MessageIDUpdateResponse) PopReceipt

func (miur MessageIDUpdateResponse) PopReceipt() string

PopReceipt returns the value for header x-ms-popreceipt.

func (MessageIDUpdateResponse) RequestID

func (miur MessageIDUpdateResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (MessageIDUpdateResponse) Response

func (miur MessageIDUpdateResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (MessageIDUpdateResponse) Status

func (miur MessageIDUpdateResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (MessageIDUpdateResponse) StatusCode

func (miur MessageIDUpdateResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (MessageIDUpdateResponse) TimeNextVisible

func (miur MessageIDUpdateResponse) TimeNextVisible() time.Time

TimeNextVisible returns the value for header x-ms-time-next-visible.

func (MessageIDUpdateResponse) Version

func (miur MessageIDUpdateResponse) Version() string

Version returns the value for header x-ms-version.

type MessagesClearResponse

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

MessagesClearResponse ...

func (MessagesClearResponse) Date

func (mcr MessagesClearResponse) Date() time.Time

Date returns the value for header Date.

func (MessagesClearResponse) ErrorCode

func (mcr MessagesClearResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (MessagesClearResponse) RequestID

func (mcr MessagesClearResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (MessagesClearResponse) Response

func (mcr MessagesClearResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (MessagesClearResponse) Status

func (mcr MessagesClearResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (MessagesClearResponse) StatusCode

func (mcr MessagesClearResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (MessagesClearResponse) Version

func (mcr MessagesClearResponse) Version() string

Version returns the value for header x-ms-version.

type MessagesURL

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

A MessagesURL represents a URL to an Azure Storage Queue's messages allowing you to manipulate its messages.

func NewMessagesURL

func NewMessagesURL(url url.URL, p pipeline.Pipeline) MessagesURL

NewMessageURL creates a MessagesURL object using the specified URL and request policy pipeline.

func (MessagesURL) Clear

Clear deletes all messages from a queue. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/clear-messages.

Example

This examples shows how to clear all of a queue's messages.

package main

import (
	"context"
	"fmt"
	"log"
	"net/url"
	"os"
	"time"

	"github.com/Azure/azure-storage-queue-go/azqueue"
	"net/http"
	"strconv"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account file service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a QueueURL with default pipeline based on an existing queue with name queue6.
	u, _ := url.Parse(fmt.Sprintf("https://%s.queue.core.windows.net/queue6", accountName))

	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.TODO() // This example uses a never-expiring context
	queueURL := azqueue.NewQueueURL(*u, azqueue.NewPipeline(credential, azqueue.PipelineOptions{}))
	_, err = queueURL.Create(ctx, azqueue.Metadata{})
	if err != nil {
		log.Fatal(err)
	}

	// Insert a message so we can verify it disappears after clearing the queue
	messagesURL := queueURL.NewMessagesURL()
	_, err = messagesURL.Enqueue(ctx, "A message", time.Second*0, time.Minute)
	if err != nil {
		log.Fatal(err)
	}

	props, err := queueURL.GetProperties(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Msg count=" + strconv.Itoa(int(props.ApproximateMessagesCount())))

	for {
		clear, err := messagesURL.Clear(ctx)
		if err == nil {
			break // Don't loop if Clear successful
		} else {
			if clear.StatusCode() == http.StatusInternalServerError {
				if stgErr, ok := err.(azqueue.StorageError); ok && stgErr.Response().StatusCode == http.StatusInternalServerError && stgErr.ServiceCode() == azqueue.ServiceCodeOperationTimedOut {
					continue // Service timed out while deleting messages; call Clear again until it return success
				}
			}
			log.Fatal(err)
		}
	}
	props, err = queueURL.GetProperties(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Msg count=" + strconv.Itoa(int(props.ApproximateMessagesCount())))

}
Output:

Msg count=1
Msg count=0

func (MessagesURL) Dequeue

func (m MessagesURL) Dequeue(ctx context.Context, maxMessages int32, visibilityTimeout time.Duration) (*DequeuedMessagesResponse, error)

Dequeue retrieves one or more messages from the front of the queue. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/get-messages.

func (MessagesURL) Enqueue

func (m MessagesURL) Enqueue(ctx context.Context, messageText string, visibilityTimeout time.Duration, timeToLive time.Duration) (*EnqueueMessageResponse, error)

Enqueue adds a new message to the back of a queue. The visibility timeout specifies how long the message should be invisible to Dequeue and Peek operations. The message content must be a UTF-8 encoded string that is up to 64KB in size. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/put-message. The timeToLive interval for the message is defined in seconds. The maximum timeToLive can be any positive number, as well as -time.Second indicating that the message does not expire. If 0 is passed for timeToLive, the default value is 7 days.

func (MessagesURL) NewMessageIDURL

func (m MessagesURL) NewMessageIDURL(messageID MessageID) MessageIDURL

NewMessageIDURL creates a new MessageIDURL object by concatenating messageID to the end of MessagesURL's URL. The new MessageIDURL uses the same request policy pipeline as the MessagesURL. To change the pipeline, create the MessageIDURL and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewMessageIDURL instead of calling this object's NewMessageIDURL method.

func (MessagesURL) Peek

func (m MessagesURL) Peek(ctx context.Context, maxMessages int32) (*PeekedMessagesResponse, error)

Peek retrieves one or more messages from the front of the queue but does not alter the visibility of the message. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/peek-messages.

func (MessagesURL) String

func (m MessagesURL) String() string

String returns the URL as a string.

func (MessagesURL) URL

func (m MessagesURL) URL() url.URL

URL returns the URL endpoint used by the MessagesURL object.

func (MessagesURL) WithPipeline

func (m MessagesURL) WithPipeline(p pipeline.Pipeline) MessagesURL

WithPipeline creates a new MessagesURL object identical to the source but with the specified request policy pipeline.

type Metadata

type Metadata map[string]string

Metadata contains metadata key/value pairs.

func (*Metadata) UnmarshalXML

func (md *Metadata) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for Metadata.

type Metrics

type Metrics struct {
	// Version - The version of Storage Analytics to configure.
	Version *string `xml:"Version"`
	// Enabled - Indicates whether metrics are enabled for the Queue service.
	Enabled bool `xml:"Enabled"`
	// IncludeAPIs - Indicates whether metrics should generate summary statistics for called API operations.
	IncludeAPIs     *bool            `xml:"IncludeAPIs"`
	RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"`
}

Metrics ...

type PeekResponse

type PeekResponse struct {

	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name            `xml:"QueueMessagesList"`
	Items   []PeekedMessageItem `xml:"QueueMessage"`
	// contains filtered or unexported fields
}

PeekResponse - Wraps the response from the messagesClient.Peek method.

func (PeekResponse) Date

func (pr PeekResponse) Date() time.Time

Date returns the value for header Date.

func (PeekResponse) ErrorCode

func (pr PeekResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (PeekResponse) RequestID

func (pr PeekResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (PeekResponse) Response

func (pr PeekResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (PeekResponse) Status

func (pr PeekResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (PeekResponse) StatusCode

func (pr PeekResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (PeekResponse) Version

func (pr PeekResponse) Version() string

Version returns the value for header x-ms-version.

type PeekedMessage

type PeekedMessage struct {
	ID             MessageID
	InsertionTime  time.Time
	ExpirationTime time.Time
	DequeueCount   int64
	Text           string // UTF-8 string
}

PeekedMessage holds the properties of a peeked message.

type PeekedMessageItem

type PeekedMessageItem struct {
	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name `xml:"QueueMessage"`
	// MessageID - The Id of the Message.
	MessageID string `xml:"MessageId"`
	// InsertionTime - The time the Message was inserted into the Queue.
	InsertionTime time.Time `xml:"InsertionTime"`
	// ExpirationTime - The time that the Message will expire and be automatically deleted.
	ExpirationTime time.Time `xml:"ExpirationTime"`
	// DequeueCount - The number of times the message has been dequeued.
	DequeueCount int64 `xml:"DequeueCount"`
	// MessageText - The content of the Message.
	MessageText string `xml:"MessageText"`
}

PeekedMessageItem - The object returned in the QueueMessageList array when calling Peek Messages on a Queue

func (PeekedMessageItem) MarshalXML

func (pmi PeekedMessageItem) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements the xml.Marshaler interface for PeekedMessageItem.

func (*PeekedMessageItem) UnmarshalXML

func (pmi *PeekedMessageItem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements the xml.Unmarshaler interface for PeekedMessageItem.

type PeekedMessagesResponse

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

PeekedMessagesResponse holds the results of a successful call to Peek.

func (PeekedMessagesResponse) Date

func (pmr PeekedMessagesResponse) Date() time.Time

Date returns the value for header Date.

func (PeekedMessagesResponse) Message

func (pmr PeekedMessagesResponse) Message(index int32) *PeekedMessage

Message returns the information for peeked message.

func (PeekedMessagesResponse) NumMessages

func (pmr PeekedMessagesResponse) NumMessages() int32

NumMessages returns the number of messages retrieved by the call to Peek.

func (PeekedMessagesResponse) RequestID

func (pmr PeekedMessagesResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (PeekedMessagesResponse) Response

func (pmr PeekedMessagesResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (PeekedMessagesResponse) Status

func (pmr PeekedMessagesResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (PeekedMessagesResponse) StatusCode

func (pmr PeekedMessagesResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (PeekedMessagesResponse) Version

func (pmr PeekedMessagesResponse) Version() string

Version returns the value for header x-ms-version.

type PipelineOptions

type PipelineOptions struct {
	// Log configures the pipeline's logging infrastructure indicating what information is logged and where.
	Log pipeline.LogOptions

	// Retry configures the built-in retry policy behavior.
	Retry RetryOptions

	// RequestLog configures the built-in request logging policy.
	RequestLog RequestLogOptions

	// Telemetry configures the built-in telemetry policy behavior.
	Telemetry TelemetryOptions
}

PipelineOptions is used to configure a request policy pipeline's retry policy and logging.

type PopReceipt

type PopReceipt string

PopReceipt represents a Message's opaque pop receipt.

func (PopReceipt) String

func (pr PopReceipt) String() string

String returns a PopReceipt as a string

type QueueCreateResponse

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

QueueCreateResponse ...

func (QueueCreateResponse) Date

func (qcr QueueCreateResponse) Date() time.Time

Date returns the value for header Date.

func (QueueCreateResponse) ErrorCode

func (qcr QueueCreateResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueCreateResponse) RequestID

func (qcr QueueCreateResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueCreateResponse) Response

func (qcr QueueCreateResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueCreateResponse) Status

func (qcr QueueCreateResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueCreateResponse) StatusCode

func (qcr QueueCreateResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueCreateResponse) Version

func (qcr QueueCreateResponse) Version() string

Version returns the value for header x-ms-version.

type QueueDeleteResponse

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

QueueDeleteResponse ...

func (QueueDeleteResponse) Date

func (qdr QueueDeleteResponse) Date() time.Time

Date returns the value for header Date.

func (QueueDeleteResponse) ErrorCode

func (qdr QueueDeleteResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueDeleteResponse) RequestID

func (qdr QueueDeleteResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueDeleteResponse) Response

func (qdr QueueDeleteResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueDeleteResponse) Status

func (qdr QueueDeleteResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueDeleteResponse) StatusCode

func (qdr QueueDeleteResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueDeleteResponse) Version

func (qdr QueueDeleteResponse) Version() string

Version returns the value for header x-ms-version.

type QueueGetPropertiesResponse

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

QueueGetPropertiesResponse ...

func (QueueGetPropertiesResponse) ApproximateMessagesCount

func (qgpr QueueGetPropertiesResponse) ApproximateMessagesCount() int32

ApproximateMessagesCount returns the value for header x-ms-approximate-messages-count.

func (QueueGetPropertiesResponse) Date

func (qgpr QueueGetPropertiesResponse) Date() time.Time

Date returns the value for header Date.

func (QueueGetPropertiesResponse) ErrorCode

func (qgpr QueueGetPropertiesResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueGetPropertiesResponse) NewMetadata

func (qgpr QueueGetPropertiesResponse) NewMetadata() Metadata

NewMetadata returns user-defined key/value pairs.

func (QueueGetPropertiesResponse) RequestID

func (qgpr QueueGetPropertiesResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueGetPropertiesResponse) Response

func (qgpr QueueGetPropertiesResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueGetPropertiesResponse) Status

func (qgpr QueueGetPropertiesResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueGetPropertiesResponse) StatusCode

func (qgpr QueueGetPropertiesResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueGetPropertiesResponse) Version

func (qgpr QueueGetPropertiesResponse) Version() string

Version returns the value for header x-ms-version.

type QueueItem

type QueueItem struct {
	// XMLName is used for marshalling and is subject to removal in a future release.
	XMLName xml.Name `xml:"Queue"`
	// Name - The name of the Queue.
	Name     string   `xml:"Name"`
	Metadata Metadata `xml:"Metadata"`
}

QueueItem - An Azure Storage Queue.

type QueueMessage

type QueueMessage struct {
	// MessageText - The content of the message
	MessageText string `xml:"MessageText"`
}

QueueMessage - A Message object which can be stored in a Queue

type QueueMessagesList

type QueueMessagesList struct {
	Items []DequeuedMessageItem `xml:"QueueMessage"`
	// contains filtered or unexported fields
}

QueueMessagesList - Wraps the response from the messagesClient.Dequeue method.

func (QueueMessagesList) Date

func (qml QueueMessagesList) Date() time.Time

Date returns the value for header Date.

func (QueueMessagesList) ErrorCode

func (qml QueueMessagesList) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueMessagesList) RequestID

func (qml QueueMessagesList) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueMessagesList) Response

func (qml QueueMessagesList) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueMessagesList) Status

func (qml QueueMessagesList) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueMessagesList) StatusCode

func (qml QueueMessagesList) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueMessagesList) Version

func (qml QueueMessagesList) Version() string

Version returns the value for header x-ms-version.

type QueueSASPermissions

type QueueSASPermissions struct {
	Read, Add, Update, Process bool
}

The QueueSASPermissions type simplifies creating the permissions string for an Azure Storage queue SAS. Initialize an instance of this type and then call its String method to set QueueSASSignatureValues's Permissions field.

func (*QueueSASPermissions) Parse

func (p *QueueSASPermissions) Parse(s string) error

Parse initializes the QueueSASPermissions's fields from a string.

func (QueueSASPermissions) String

func (p QueueSASPermissions) String() string

String produces the SAS permissions string for an Azure Storage queue. Call this method to set QueueSASSignatureValues's Permissions field.

type QueueSASSignatureValues

type QueueSASSignatureValues struct {
	Version     string      `param:"sv"`  // If not specified, this defaults to SASVersion
	Protocol    SASProtocol `param:"spr"` // See the SASProtocol* constants
	StartTime   time.Time   `param:"st"`  // Not specified if IsZero
	ExpiryTime  time.Time   `param:"se"`  // Not specified if IsZero
	Permissions string      `param:"sp"`  // Create by initializing a QueueSASPermissions and then call String()
	IPRange     IPRange     `param:"sip"`
	Identifier  string      `param:"si"`
	QueueName   string
}

QueueSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage queue.

Example

This example shows how to create and use a Queue Service Shared Access Signature (SAS).

package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"time"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is required to sign a SAS.
	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// This is the name of the queue that we're creating a SAS to.
	queueName := "queue4" // Queue names require lowercase

	// Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query parameters.
	sasQueryParams := azqueue.QueueSASSignatureValues{
		Protocol:    azqueue.SASProtocolHTTPS,       // Users MUST use HTTPS (not HTTP)
		ExpiryTime:  time.Now().Add(48 * time.Hour), // 48-hours before expiration
		QueueName:   queueName,
		Permissions: azqueue.QueueSASPermissions{Add: true, Read: true, Process: true}.String(),
	}.NewSASQueryParameters(credential)

	// Create the URL of the resource you wish to access and append the SAS query parameters.
	// Since this is a queue SAS, the URL is to the Azure storage queue.
	qp := sasQueryParams.Encode()
	urlToSendToSomeone := fmt.Sprintf("https://%s.queue.core.windows.net/%s?%s",
		accountName, queueName, qp)
	// At this point, you can send the urlToSendToSomeone to someone via email or any other mechanism you choose.

	// ************************************************************************************************

	// When someone receives the URL, they access the SAS-protected resource with code like this:
	u, _ := url.Parse(urlToSendToSomeone)

	// Create an QueueURL object that wraps the queue URL (and its SAS) and a pipeline.
	// When using URls with a SAS, anonymous credentials are required.
	queueURL := azqueue.NewQueueURL(*u, azqueue.NewPipeline(azqueue.NewAnonymousCredential(), azqueue.PipelineOptions{}))
	// Now, you can use this queueURL just like any other to make requests of the resource.

	// If you have a SAS query parameter string, you can parse it into its parts:
	queueURLParts := azqueue.NewQueueURLParts(queueURL.URL())
	fmt.Printf("SAS Protocol=%v\n", queueURLParts.SAS.Protocol())
	fmt.Printf("SAS Permissions=%v\n", queueURLParts.SAS.Permissions())

}
Output:

SAS Protocol=https
SAS Permissions=rap

func (QueueSASSignatureValues) NewSASQueryParameters

func (v QueueSASSignatureValues) NewSASQueryParameters(sharedKeyCredential *SharedKeyCredential) SASQueryParameters

NewSASQueryParameters uses an account's shared key credential to sign this signature values to produce the proper SAS query parameters.

type QueueSetAccessPolicyResponse

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

QueueSetAccessPolicyResponse ...

func (QueueSetAccessPolicyResponse) Date

func (qsapr QueueSetAccessPolicyResponse) Date() time.Time

Date returns the value for header Date.

func (QueueSetAccessPolicyResponse) ErrorCode

func (qsapr QueueSetAccessPolicyResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueSetAccessPolicyResponse) RequestID

func (qsapr QueueSetAccessPolicyResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueSetAccessPolicyResponse) Response

func (qsapr QueueSetAccessPolicyResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueSetAccessPolicyResponse) Status

func (qsapr QueueSetAccessPolicyResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueSetAccessPolicyResponse) StatusCode

func (qsapr QueueSetAccessPolicyResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueSetAccessPolicyResponse) Version

func (qsapr QueueSetAccessPolicyResponse) Version() string

Version returns the value for header x-ms-version.

type QueueSetMetadataResponse

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

QueueSetMetadataResponse ...

func (QueueSetMetadataResponse) Date

func (qsmr QueueSetMetadataResponse) Date() time.Time

Date returns the value for header Date.

func (QueueSetMetadataResponse) ErrorCode

func (qsmr QueueSetMetadataResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (QueueSetMetadataResponse) RequestID

func (qsmr QueueSetMetadataResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (QueueSetMetadataResponse) Response

func (qsmr QueueSetMetadataResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (QueueSetMetadataResponse) Status

func (qsmr QueueSetMetadataResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (QueueSetMetadataResponse) StatusCode

func (qsmr QueueSetMetadataResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (QueueSetMetadataResponse) Version

func (qsmr QueueSetMetadataResponse) Version() string

Version returns the value for header x-ms-version.

type QueueURL

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

A QueueURL represents a URL to the Azure Storage queue.

func NewQueueURL

func NewQueueURL(url url.URL, p pipeline.Pipeline) QueueURL

NewQueueURL creates a QueueURL object using the specified URL and request policy pipeline.

func (QueueURL) Create

func (q QueueURL) Create(ctx context.Context, metadata Metadata) (*QueueCreateResponse, error)

Create creates a queue within a storage account. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/create-queue4.

func (QueueURL) Delete

func (q QueueURL) Delete(ctx context.Context) (*QueueDeleteResponse, error)

Delete permanently deletes a queue. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-queue3.

func (QueueURL) GetAccessPolicy

func (q QueueURL) GetAccessPolicy(ctx context.Context) (*SignedIdentifiers, error)

GetAccessPolicy returns details about any stored access policies specified on the queue that may be used with Shared Access Signatures. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-acl.

func (QueueURL) GetProperties

func (q QueueURL) GetProperties(ctx context.Context) (*QueueGetPropertiesResponse, error)

GetProperties retrieves queue properties and user-defined metadata and properties on the specified queue. Metadata is associated with the queue as name-values pairs. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata.

Example

This examples shows how to create a queue with metadata and then how to get properties & update the queue's metadata.

package main

import (
	"context"
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/Azure/azure-storage-queue-go/azqueue"
	"strconv"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account file service URL endpoint.
	accountName, accountKey := accountInfo()

	// Create a FileURL with default pipeline based on an existing share with name myshare.
	u, _ := url.Parse(fmt.Sprintf("https://%s.queue.core.windows.net/queue5", accountName))
	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}
	queueURL := azqueue.NewQueueURL(*u, azqueue.NewPipeline(credential, azqueue.PipelineOptions{}))

	ctx := context.TODO() // This example uses a never-expiring context

	// Create a queue with metadata (string key/value pairs)
	// NOTE: Metadata key names are always converted to lowercase before being sent to the Storage Service.
	// Therefore, you should always use lowercase letters; especially when querying a map for a metadata key.
	_, err = queueURL.Create(ctx, azqueue.Metadata{"createdby": "Jeffrey"})
	if err != nil {
		log.Fatal(err)
	}

	// Query the queue's properties (which includes its metadata)
	props, err := queueURL.GetProperties(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// Show some of the queue's read-only properties (0 messages in the queue)
	fmt.Println("Msg count=" + strconv.Itoa(int(props.ApproximateMessagesCount())))

	// Show the queue's metadata
	fmt.Println("Queue metadata values:")
	metadata := props.NewMetadata()
	for k, v := range metadata {
		fmt.Print("   " + k + "=" + v + "\n")
	}

	// Add a key/value pair to the queue's metadata
	metadata["updatedby"] = "Aidan" // Add a new key/value; NOTE: The keyname is in all lowercase letters
	_, err = queueURL.SetMetadata(ctx, metadata)
	if err != nil {
		log.Fatal(err)
	}

	props, err = queueURL.GetProperties(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// Show the queue's metadata
	fmt.Println("Queue new metadata values:")
	for k, v := range props.NewMetadata() {
		fmt.Print("   " + k + "=" + v + "\n")
	}

	_, err = queueURL.Delete(ctx) // Delete the queue
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Msg count=0
Queue metadata values:
   createdby=Jeffrey
Queue new metadata values:
   createdby=Jeffrey
   updatedby=Aidan

func (QueueURL) NewMessagesURL

func (q QueueURL) NewMessagesURL() MessagesURL

NewMessagesURL creates a new MessagesURL object by concatenating "messages" to the end of QueueURL's URL. The new MessagesURL uses the same request policy pipeline as the QueueURL. To change the pipeline, create the MessagesURL and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewMessagesURL instead of calling this object's NewMessagesURL method.

func (QueueURL) SetAccessPolicy

func (q QueueURL) SetAccessPolicy(ctx context.Context, permissions []SignedIdentifier) (*QueueSetAccessPolicyResponse, error)

SetAccessPolicy sets sets stored access policies for the queue that may be used with Shared Access Signatures. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-acl.

Example

This example shows how to set a queue's access policies.

package main

import (
	"context"
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

// Please set the ACCOUNT_NAME and ACCOUNT_KEY environment variables to your storage account's
// name and account key, before running the examples.
func accountInfo() (string, string) {
	return os.Getenv("ACCOUNT_NAME"), os.Getenv("ACCOUNT_KEY")
}

func main() {
	// From the Azure portal, get your Storage account's name and account key.
	accountName, accountKey := accountInfo()

	// Use your Storage account's name and key to create a credential object; this is used to access your account.
	credential, err := azqueue.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		log.Fatal(err)
	}

	// Create a QueueURL object that wraps the queue's URL and a default pipeline.
	u, _ := url.Parse(fmt.Sprintf("https://%s.queue.core.windows.net/queue7", accountName))
	queueURL := azqueue.NewQueueURL(*u, azqueue.NewPipeline(credential, azqueue.PipelineOptions{}))

	// All operations allow you to specify a timeout via a Go context.Context object.
	ctx := context.TODO() // This example uses a never-expiring context

	// Create the container (with no metadata)
	_, err = queueURL.Create(ctx, azqueue.Metadata{})
	if err != nil {
		log.Fatal(err)
	}

	// Create a URL that references a to-be-created blob in your Azure Storage account's container.
	// This returns a BlockBlobURL object that wraps the blob's URL and a request pipeline (inherited from containerURL)
	_, err = queueURL.SetAccessPolicy(ctx, []azqueue.SignedIdentifier{
		{
			ID:           "Managers",
			AccessPolicy: azqueue.AccessPolicy{Permission: azqueue.AccessPolicyPermission{Add: true}.String()},
		},
		{
			ID:           "Engineers",
			AccessPolicy: azqueue.AccessPolicy{Permission: azqueue.AccessPolicyPermission{Read: true, ProcessMessages: true}.String()},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	ap, err := queueURL.GetAccessPolicy(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// Display the access policy's signedIdentifiers
	for _, si := range ap.Items {
		fmt.Println(si.ID, si.AccessPolicy.Permission)
	}

	if _, err := queueURL.Delete(ctx); err != nil { // Delete the queue that this example used
		log.Fatal(err)
	}

}
Output:

Managers a
Engineers rp

func (QueueURL) SetMetadata

func (q QueueURL) SetMetadata(ctx context.Context, metadata Metadata) (*QueueSetMetadataResponse, error)

SetMetadata sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-metadata.

func (QueueURL) String

func (q QueueURL) String() string

String returns the URL as a string.

func (QueueURL) URL

func (q QueueURL) URL() url.URL

URL returns the URL endpoint used by the QueueURL object.

func (QueueURL) WithPipeline

func (q QueueURL) WithPipeline(p pipeline.Pipeline) QueueURL

WithPipeline creates a new QueueURL object identical to the source but with the specified request policy pipeline.

type QueueURLParts

type QueueURLParts struct {
	Scheme         string // Ex: "https://"
	Host           string // Ex: "account.queue.core.windows.net"
	QueueName      string // "" if no queue name
	Messages       bool   // true if "/messages" was/should be in URL
	MessageID      MessageID
	SAS            SASQueryParameters
	UnparsedParams string
}

A QueueURLParts object represents the components that make up an Azure Storage Queue URL. You parse an existing URL into its parts by calling NewQueueURLParts(). You construct a URL from parts by calling URL(). NOTE: Changing any SAS-related field requires computing a new SAS signature.

Example

This example shows how to break a URL into its parts so you can examine and/or change some of its values and then construct a new URL.

package main

import (
	"fmt"
	"log"
	"net/url"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

func main() {
	// Let's start with a URL that identifies a queue that also contains a Shared Access Signature (SAS):
	u, _ := url.Parse("https://myaccount.queue.core.windows.net/aqueue/messages/30dd879c-ee2f-11db-8314-0800200c9a66?" +
		"sv=2015-02-21&sr=q&st=2111-01-09T01:42:34.936Z&se=2222-03-09T01:42:34.936Z&sp=rup&sip=168.1.5.60-168.1.5.70&" +
		"spr=https,http&si=myIdentifier&ss=q&srt=o&sig=92836758923659283652983562==")

	// You can parse this URL into its constituent parts:
	parts := azqueue.NewQueueURLParts(*u)

	// Now, we access the parts (this example prints them).
	fmt.Println(parts.Host, parts.QueueName)
	sas := parts.SAS
	fmt.Println(sas.Version(), sas.Resource(), sas.StartTime(), sas.ExpiryTime(), sas.Permissions(),
		sas.IPRange(), sas.Protocol(), sas.Identifier(), sas.Services(), sas.ResourceTypes(), sas.Signature())

	// You can then change some of the fields and construct a new URL:
	parts.SAS = azqueue.SASQueryParameters{} // Remove the SAS query parameters
	parts.QueueName = "otherqueue"           // Change the queue name
	parts.MessageID = ""

	// Construct a new URL from the parts:
	newURL, err := parts.URL()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(newURL.String())
	// NOTE: You can pass the new URL to NewQueueURL to manipulate the queue.

}
Output:

myaccount.queue.core.windows.net aqueue
2015-02-21 q 2111-01-09 01:42:34.936 +0000 UTC 2222-03-09 01:42:34.936 +0000 UTC rup {168.1.5.60 168.1.5.70} https,http myIdentifier q o 92836758923659283652983562==
https://myaccount.queue.core.windows.net/otherqueue/messages

func NewQueueURLParts

func NewQueueURLParts(u url.URL) QueueURLParts

NewQueueURLParts parses a URL initializing QueueURLParts' fields including any SAS-related query parameters. Any other query parameters remain in the UnparsedParams field. This method overwrites all fields in the QueueURLParts object.

func (QueueURLParts) URL

func (up QueueURLParts) URL() (url.URL, error)

URL returns a URL object whose fields are initialized from the QueueURLParts fields. The URL's RawQuery field contains the SAS and unparsed query parameters.

type RequestLogOptions

type RequestLogOptions struct {
	// LogWarningIfTryOverThreshold logs a warning if a tried operation takes longer than the specified
	// duration (-1=no logging; 0=default threshold).
	LogWarningIfTryOverThreshold time.Duration
}

RequestLogOptions configures the retry policy's behavior.

type ResponseError

type ResponseError interface {
	// Error exposes the Error(), Temporary() and Timeout() methods.
	net.Error // Includes the Go error interface
	// Response returns the HTTP response. You may examine this but you should not modify it.
	Response() *http.Response
}

ResponseError identifies a responder-generated network or response parsing error.

type RetentionPolicy

type RetentionPolicy struct {
	// Enabled - Indicates whether a retention policy is enabled for the storage service
	Enabled bool `xml:"Enabled"`
	// Days - Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted
	Days *int32 `xml:"Days"`
}

RetentionPolicy - the retention policy

type RetryOptions

type RetryOptions struct {
	// Policy tells the pipeline what kind of retry policy to use. See the RetryPolicy* constants.\
	// A value of zero means that you accept our default policy.
	Policy RetryPolicy

	// MaxTries specifies the maximum number of attempts an operation will be tried before producing an error (0=default).
	// A value of zero means that you accept our default policy. A value of 1 means 1 try and no retries.
	MaxTries int32

	// TryTimeout indicates the maximum time allowed for any single try of an HTTP request.
	// A value of zero means that you accept our default timeout. NOTE: When transferring large amounts
	// of data, the default TryTimeout will probably not be sufficient. You should override this value
	// based on the bandwidth available to the host machine and proximity to the Storage service. A good
	// starting point may be something like (60 seconds per MB of anticipated-payload-size).
	TryTimeout time.Duration

	// RetryDelay specifies the amount of delay to use before retrying an operation (0=default).
	// When RetryPolicy is specified as RetryPolicyExponential, the delay increases exponentially
	// with each retry up to a maximum specified by MaxRetryDelay.
	// If you specify 0, then you must also specify 0 for MaxRetryDelay.
	// If you specify RetryDelay, then you must also specify MaxRetryDelay, and MaxRetryDelay should be
	// equal to or greater than RetryDelay.
	RetryDelay time.Duration

	// MaxRetryDelay specifies the maximum delay allowed before retrying an operation (0=default).
	// If you specify 0, then you must also specify 0 for RetryDelay.
	MaxRetryDelay time.Duration

	// RetryReadsFromSecondaryHost specifies whether the retry policy should retry a read operation against another host.
	// If RetryReadsFromSecondaryHost is "" (the default) then operations are not retried against another host.
	// NOTE: Before setting this field, make sure you understand the issues around reading stale & potentially-inconsistent
	// data at this webpage: https://docs.microsoft.com/en-us/azure/storage/common/storage-designing-ha-apps-with-ragrs
	RetryReadsFromSecondaryHost string
}

RetryOptions configures the retry policy's behavior.

type RetryPolicy

type RetryPolicy int32

RetryPolicy tells the pipeline what kind of retry policy to use. See the RetryPolicy* constants.

const (
	// RetryPolicyExponential tells the pipeline to use an exponential back-off retry policy
	RetryPolicyExponential RetryPolicy = 0

	// RetryPolicyFixed tells the pipeline to use a fixed back-off retry policy
	RetryPolicyFixed RetryPolicy = 1
)

type SASProtocol

type SASProtocol string
const (
	// SASProtocolHTTPS can be specified for a SAS protocol
	SASProtocolHTTPS SASProtocol = "https"

	// SASProtocolHTTPSandHTTP can be specified for a SAS protocol
	SASProtocolHTTPSandHTTP SASProtocol = "https,http"
)

type SASQueryParameters

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

A SASQueryParameters object represents the components that make up an Azure Storage SAS' query parameters. You parse a map of query parameters into its fields by calling NewSASQueryParameters(). You add the components to a query parameter map by calling AddToValues(). NOTE: Changing any field requires computing a new SAS signature using a XxxSASSignatureValues type.

This type defines the components used by all Azure Storage resources (Containers, Blobs, Files, & Queues).

func (*SASQueryParameters) Encode

func (p *SASQueryParameters) Encode() string

Encode encodes the SAS query parameters into URL encoded form sorted by key.

func (*SASQueryParameters) ExpiryTime

func (p *SASQueryParameters) ExpiryTime() time.Time

func (*SASQueryParameters) IPRange

func (p *SASQueryParameters) IPRange() IPRange

func (*SASQueryParameters) Identifier

func (p *SASQueryParameters) Identifier() string

func (*SASQueryParameters) Permissions

func (p *SASQueryParameters) Permissions() string

func (*SASQueryParameters) Protocol

func (p *SASQueryParameters) Protocol() SASProtocol

func (*SASQueryParameters) Resource

func (p *SASQueryParameters) Resource() string

func (*SASQueryParameters) ResourceTypes

func (p *SASQueryParameters) ResourceTypes() string

func (*SASQueryParameters) Services

func (p *SASQueryParameters) Services() string

func (*SASQueryParameters) Signature

func (p *SASQueryParameters) Signature() string

func (*SASQueryParameters) StartTime

func (p *SASQueryParameters) StartTime() time.Time

func (*SASQueryParameters) Version

func (p *SASQueryParameters) Version() string

type ServiceCodeType

type ServiceCodeType string

ServiceCodeType is a string identifying a storage service error. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/status-and-error-codes2

const (
	// The specified marker is invalid (400).
	ServiceCodeInvalidMarker ServiceCodeType = "InvalidMarker"

	// The specified message does not exist (404).
	ServiceCodeMessageNotFound ServiceCodeType = "MessageNotFound"

	// The message exceeds the maximum allowed size (400).
	ServiceCodeMessageTooLarge ServiceCodeType = "MessageTooLarge"

	// The specified pop receipt did not match the pop receipt for a dequeued message (400).
	ServiceCodePopReceiptMismatch ServiceCodeType = "PopReceiptMismatch"

	// The specified queue already exists (409).
	ServiceCodeQueueAlreadyExists ServiceCodeType = "QueueAlreadyExists"

	// The specified queue is being deleted (409).
	ServiceCodeQueueBeingDeleted ServiceCodeType = "QueueBeingDeleted"

	// The specified queue has been disabled by the administrator (409).
	ServiceCodeQueueDisabled ServiceCodeType = "QueueDisabled"

	// The specified queue is not empty (409).
	ServiceCodeQueueNotEmpty ServiceCodeType = "QueueNotEmpty"

	// The specified queue does not exist (404).
	ServiceCodeQueueNotFound ServiceCodeType = "QueueNotFound"
)

ServiceCode values indicate a service failure.

const (
	// ServiceCodeNone is the default value. It indicates that the error was related to the service or that the service didn't return a code.
	ServiceCodeNone ServiceCodeType = ""

	// ServiceCodeAccountAlreadyExists means the specified account already exists.
	ServiceCodeAccountAlreadyExists ServiceCodeType = "AccountAlreadyExists"

	// ServiceCodeAccountBeingCreated means the specified account is in the process of being created (403).
	ServiceCodeAccountBeingCreated ServiceCodeType = "AccountBeingCreated"

	// ServiceCodeAccountIsDisabled means the specified account is disabled (403).
	ServiceCodeAccountIsDisabled ServiceCodeType = "AccountIsDisabled"

	// ServiceCodeAuthenticationFailed means the server failed to authenticate the request. Make sure the value of the Authorization header is formed correctly including the signature (403).
	ServiceCodeAuthenticationFailed ServiceCodeType = "AuthenticationFailed"

	// ServiceCodeConditionHeadersNotSupported means the condition headers are not supported (400).
	ServiceCodeConditionHeadersNotSupported ServiceCodeType = "ConditionHeadersNotSupported"

	// ServiceCodeConditionNotMet means the condition specified in the conditional header(s) was not met for a read/write operation (304/412).
	ServiceCodeConditionNotMet ServiceCodeType = "ConditionNotMet"

	// ServiceCodeEmptyMetadataKey means the key for one of the metadata key-value pairs is empty (400).
	ServiceCodeEmptyMetadataKey ServiceCodeType = "EmptyMetadataKey"

	// ServiceCodeInsufficientAccountPermissions means read operations are currently disabled or Write operations are not allowed or The account being accessed does not have sufficient permissions to execute this operation (403).
	ServiceCodeInsufficientAccountPermissions ServiceCodeType = "InsufficientAccountPermissions"

	// ServiceCodeInternalError means the server encountered an internal error. Please retry the request (500).
	ServiceCodeInternalError ServiceCodeType = "InternalError"

	// ServiceCodeInvalidAuthenticationInfo means the authentication information was not provided in the correct format. Verify the value of Authorization header (400).
	ServiceCodeInvalidAuthenticationInfo ServiceCodeType = "InvalidAuthenticationInfo"

	// ServiceCodeInvalidHeaderValue means the value provided for one of the HTTP headers was not in the correct format (400).
	ServiceCodeInvalidHeaderValue ServiceCodeType = "InvalidHeaderValue"

	// ServiceCodeInvalidHTTPVerb means the HTTP verb specified was not recognized by the server (400).
	ServiceCodeInvalidHTTPVerb ServiceCodeType = "InvalidHttpVerb"

	// ServiceCodeInvalidInput means one of the request inputs is not valid (400).
	ServiceCodeInvalidInput ServiceCodeType = "InvalidInput"

	// ServiceCodeInvalidMd5 means the MD5 value specified in the request is invalid. The MD5 value must be 128 bits and Base64-encoded (400).
	ServiceCodeInvalidMd5 ServiceCodeType = "InvalidMd5"

	// ServiceCodeInvalidMetadata means the specified metadata is invalid. It includes characters that are not permitted (400).
	ServiceCodeInvalidMetadata ServiceCodeType = "InvalidMetadata"

	// ServiceCodeInvalidQueryParameterValue means an invalid value was specified for one of the query parameters in the request URI (400).
	ServiceCodeInvalidQueryParameterValue ServiceCodeType = "InvalidQueryParameterValue"

	// ServiceCodeInvalidRange means the range specified is invalid for the current size of the resource (416).
	ServiceCodeInvalidRange ServiceCodeType = "InvalidRange"

	// ServiceCodeInvalidResourceName means the specified resource name contains invalid characters (400).
	ServiceCodeInvalidResourceName ServiceCodeType = "InvalidResourceName"

	// ServiceCodeInvalidURI means the requested URI does not represent any resource on the server (400).
	ServiceCodeInvalidURI ServiceCodeType = "InvalidUri"

	// ServiceCodeInvalidXMLDocument means the specified XML is not syntactically valid (400).
	ServiceCodeInvalidXMLDocument ServiceCodeType = "InvalidXmlDocument"

	// ServiceCodeInvalidXMLNodeValue means the value provided for one of the XML nodes in the request body was not in the correct format (400).
	ServiceCodeInvalidXMLNodeValue ServiceCodeType = "InvalidXmlNodeValue"

	// ServiceCodeMd5Mismatch means the MD5 value specified in the request did not match the MD5 value calculated by the server (400).
	ServiceCodeMd5Mismatch ServiceCodeType = "Md5Mismatch"

	// ServiceCodeMetadataTooLarge means the size of the specified metadata exceeds the maximum size permitted (400).
	ServiceCodeMetadataTooLarge ServiceCodeType = "MetadataTooLarge"

	// ServiceCodeMissingContentLengthHeader means the Content-Length header was not specified (411).
	ServiceCodeMissingContentLengthHeader ServiceCodeType = "MissingContentLengthHeader"

	// ServiceCodeMissingRequiredQueryParameter means a required query parameter was not specified for this request (400).
	ServiceCodeMissingRequiredQueryParameter ServiceCodeType = "MissingRequiredQueryParameter"

	// ServiceCodeMissingRequiredHeader means a required HTTP header was not specified (400).
	ServiceCodeMissingRequiredHeader ServiceCodeType = "MissingRequiredHeader"

	// ServiceCodeMissingRequiredXMLNode means a required XML node was not specified in the request body (400).
	ServiceCodeMissingRequiredXMLNode ServiceCodeType = "MissingRequiredXmlNode"

	// ServiceCodeMultipleConditionHeadersNotSupported means multiple condition headers are not supported (400).
	ServiceCodeMultipleConditionHeadersNotSupported ServiceCodeType = "MultipleConditionHeadersNotSupported"

	// ServiceCodeOperationTimedOut means the operation could not be completed within the permitted time (500).
	ServiceCodeOperationTimedOut ServiceCodeType = "OperationTimedOut"

	// ServiceCodeOutOfRangeInput means one of the request inputs is out of range (400).
	ServiceCodeOutOfRangeInput ServiceCodeType = "OutOfRangeInput"

	// ServiceCodeOutOfRangeQueryParameterValue means a query parameter specified in the request URI is outside the permissible range (400).
	ServiceCodeOutOfRangeQueryParameterValue ServiceCodeType = "OutOfRangeQueryParameterValue"

	// ServiceCodeRequestBodyTooLarge means the size of the request body exceeds the maximum size permitted (413).
	ServiceCodeRequestBodyTooLarge ServiceCodeType = "RequestBodyTooLarge"

	// ServiceCodeResourceTypeMismatch means the specified resource type does not match the type of the existing resource (409).
	ServiceCodeResourceTypeMismatch ServiceCodeType = "ResourceTypeMismatch"

	// ServiceCodeRequestURLFailedToParse means the url in the request could not be parsed (400).
	ServiceCodeRequestURLFailedToParse ServiceCodeType = "RequestUrlFailedToParse"

	// ServiceCodeResourceAlreadyExists means the specified resource already exists (409).
	ServiceCodeResourceAlreadyExists ServiceCodeType = "ResourceAlreadyExists"

	// ServiceCodeResourceNotFound means the specified resource does not exist (404).
	ServiceCodeResourceNotFound ServiceCodeType = "ResourceNotFound"

	// ServiceCodeServerBusy means the server is currently unable to receive requests. Please retry your request or Ingress/egress is over the account limit or operations per second is over the account limit (503).
	ServiceCodeServerBusy ServiceCodeType = "ServerBusy"

	// ServiceCodeUnsupportedHeader means one of the HTTP headers specified in the request is not supported (400).
	ServiceCodeUnsupportedHeader ServiceCodeType = "UnsupportedHeader"

	// ServiceCodeUnsupportedXMLNode means one of the XML nodes specified in the request body is not supported (400).
	ServiceCodeUnsupportedXMLNode ServiceCodeType = "UnsupportedXmlNode"

	// ServiceCodeUnsupportedQueryParameter means one of the query parameters specified in the request URI is not supported (400).
	ServiceCodeUnsupportedQueryParameter ServiceCodeType = "UnsupportedQueryParameter"

	// ServiceCodeUnsupportedHTTPVerb means the resource doesn't support the specified HTTP verb (405).
	ServiceCodeUnsupportedHTTPVerb ServiceCodeType = "UnsupportedHttpVerb"
)

type ServiceSetPropertiesResponse

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

ServiceSetPropertiesResponse ...

func (ServiceSetPropertiesResponse) ErrorCode

func (sspr ServiceSetPropertiesResponse) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (ServiceSetPropertiesResponse) RequestID

func (sspr ServiceSetPropertiesResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (ServiceSetPropertiesResponse) Response

func (sspr ServiceSetPropertiesResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (ServiceSetPropertiesResponse) Status

func (sspr ServiceSetPropertiesResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (ServiceSetPropertiesResponse) StatusCode

func (sspr ServiceSetPropertiesResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (ServiceSetPropertiesResponse) Version

func (sspr ServiceSetPropertiesResponse) Version() string

Version returns the value for header x-ms-version.

type ServiceURL

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

A ServiceURL represents a URL to the Azure Storage Queue service allowing you to manipulate queues.

func NewServiceURL

func NewServiceURL(primaryURL url.URL, p pipeline.Pipeline) ServiceURL

NewServiceURL creates a ServiceURL object using the specified URL and request policy pipeline.

func (ServiceURL) GetProperties

func (s ServiceURL) GetProperties(ctx context.Context) (*StorageServiceProperties, error)

GetProperties gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-service-properties.

func (ServiceURL) GetStatistics

func (s ServiceURL) GetStatistics(ctx context.Context) (*StorageServiceStats, error)

GetStatistics retrieves statistics related to replication for the Queue service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the storage account. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-service-stats.

func (ServiceURL) ListQueuesSegment

ListQueuesSegment returns a single segment of queues starting from the specified Marker. Use an empty Marker to start enumeration from the beginning. Queue names are returned in lexicographic order. After getting a segment, process it, and then call ListQueuesSegment again (passing the the previously-returned Marker) to get the next segment. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/list-queues1.

func (ServiceURL) NewQueueURL

func (s ServiceURL) NewQueueURL(queueName string) QueueURL

NewQueueURL creates a new QueueURL object by concatenating queueName to the end of ServiceURL's URL. The new QueueURL uses the same request policy pipeline as the ServiceURL. To change the pipeline, create the QueueURL and then call its WithPipeline method passing in the desired pipeline object. Or, call this package's NewQueueURL instead of calling this object's NewQueueURL method.

func (ServiceURL) SetProperties

SetProperties sets properties for a storage account’s Queue service endpoint, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties.

func (ServiceURL) String

func (s ServiceURL) String() string

String returns the URL as a string.

func (ServiceURL) URL

func (s ServiceURL) URL() url.URL

URL returns the URL endpoint used by the ServiceURL object.

func (ServiceURL) WithPipeline

func (s ServiceURL) WithPipeline(p pipeline.Pipeline) ServiceURL

WithPipeline creates a new ServiceURL object identical to the source but with the specified request policy pipeline.

type SharedKeyCredential

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

SharedKeyCredential contains an account's name and its primary or secondary key. It is immutable making it shareable and goroutine-safe.

func NewSharedKeyCredential

func NewSharedKeyCredential(accountName, accountKey string) (*SharedKeyCredential, error)

NewSharedKeyCredential creates an immutable SharedKeyCredential containing the storage account's name and either its primary or secondary key.

func (SharedKeyCredential) AccountName

func (f SharedKeyCredential) AccountName() string

AccountName returns the Storage account's name.

func (*SharedKeyCredential) ComputeHMACSHA256

func (f *SharedKeyCredential) ComputeHMACSHA256(message string) (base64String string)

ComputeHMACSHA256 generates a hash signature for an HTTP request or for a SAS.

func (*SharedKeyCredential) New

New creates a credential policy object.

type SignedIdentifier

type SignedIdentifier struct {
	// ID - a unique id
	ID string `xml:"Id"`
	// AccessPolicy - The access policy
	AccessPolicy AccessPolicy `xml:"AccessPolicy"`
}

SignedIdentifier - signed identifier

type SignedIdentifiers

type SignedIdentifiers struct {
	Items []SignedIdentifier `xml:"SignedIdentifier"`
	// contains filtered or unexported fields
}

SignedIdentifiers - Wraps the response from the queueClient.GetAccessPolicy method.

func (SignedIdentifiers) Date

func (si SignedIdentifiers) Date() time.Time

Date returns the value for header Date.

func (SignedIdentifiers) ErrorCode

func (si SignedIdentifiers) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (SignedIdentifiers) RequestID

func (si SignedIdentifiers) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (SignedIdentifiers) Response

func (si SignedIdentifiers) Response() *http.Response

Response returns the raw HTTP response object.

func (SignedIdentifiers) Status

func (si SignedIdentifiers) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (SignedIdentifiers) StatusCode

func (si SignedIdentifiers) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (SignedIdentifiers) Version

func (si SignedIdentifiers) Version() string

Version returns the value for header x-ms-version.

type StorageError

type StorageError interface {
	// ResponseError implements error's Error(), net.Error's Temporary() and Timeout() methods & Response().
	ResponseError

	// ServiceCode returns a service error code. Your code can use this to make error recovery decisions.
	ServiceCode() ServiceCodeType
}

StorageError identifies a responder-generated network or response parsing error.

Example
package main

import (
	"context"
	"log"
	"net/url"

	"github.com/Azure/azure-storage-queue-go/azqueue"
)

func main() {
	// This example shows how to handle errors returned from various XxxURL methods. All these methods return an
	// object implementing the pipeline.Response interface and an object implementing Go's error interface.
	// The error result is nil if the request was successful; your code can safely use the Response interface object.
	// If error is non-nil, the error could be due to:

	// 1. An invalid argument passed to the method. You should not write code to handle these errors;
	//    instead, fix these errors as they appear during development/testing.

	// 2. A network request didn't reach an Azure Storage Service. This usually happens due to a bad URL or
	//    faulty networking infrastructure (like a router issue). In this case, an object implementing the
	//    net.Error interface will be returned. The net.Error interface offers Timeout and Temporary methods
	//    which return true if the network error is determined to be a timeout or temporary condition. If
	//    your pipeline uses the retry policy factory, then this policy looks for Timeout/Temporary and
	//    automatically retries based on the retry options you've configured. Because of the retry policy,
	//    your code will usually not call the Timeout/Temporary methods explicitly other than possibly logging
	//    the network failure.

	// 3. A network request did reach the Azure Storage Service but the service failed to perform the
	//    requested operation. In this case, an object implementing the StorageError interface is returned.
	//    The StorageError interface also implements the net.Error interface and, if you use the retry policy,
	//    you would most likely ignore the Timeout/Temporary methods. However, the StorageError interface exposes
	//    richer information such as a service error code, an error description, details data, and the
	//    service-returned http.Response. And, from the http.Response, you can get the initiating http.Request.

	u, _ := url.Parse("https://myaccount.queue.core.windows.net/queue2") // Assumes the 'myaccount' storage account exists
	queueURL := azqueue.NewQueueURL(*u, azqueue.NewPipeline(azqueue.NewAnonymousCredential(), azqueue.PipelineOptions{}))
	create, err := queueURL.Create(context.Background(), azqueue.Metadata{})

	if err != nil { // An error occurred
		if serr, ok := err.(azqueue.StorageError); ok { // This error is a Service-specific error
			// StorageError also implements net.Error so you could call its Timeout/Temporary methods if you want.
			switch serr.ServiceCode() { // Compare serviceCode to various ServiceCodeXxx constants
			case azqueue.ServiceCodeQueueAlreadyExists:
				// You can also look at the http.Response object that failed.
				if failedResponse := serr.Response(); failedResponse != nil {
					// From the response object, you can get the initiating http.Request object
					failedRequest := failedResponse.Request
					_ = failedRequest // Avoid compiler's "declared and not used" error
				}

			case azqueue.ServiceCodeQueueBeingDeleted:
				// Handle this error ...
			default:
				// Handle other errors ...
			}
		}
		log.Fatal(err) // Error is not due to Azure Storage service; networking infrastructure failure
	}

	// If err is nil, then the method was successful; use the response to access the result
	_ = create // Avoid compiler's "declared and not used" error
}
Output:

type StorageErrorCodeType

type StorageErrorCodeType string

StorageErrorCodeType enumerates the values for storage error code type.

const (
	// StorageErrorCodeAccountAlreadyExists ...
	StorageErrorCodeAccountAlreadyExists StorageErrorCodeType = "AccountAlreadyExists"
	// StorageErrorCodeAccountBeingCreated ...
	StorageErrorCodeAccountBeingCreated StorageErrorCodeType = "AccountBeingCreated"
	// StorageErrorCodeAccountIsDisabled ...
	StorageErrorCodeAccountIsDisabled StorageErrorCodeType = "AccountIsDisabled"
	// StorageErrorCodeAuthenticationFailed ...
	StorageErrorCodeAuthenticationFailed StorageErrorCodeType = "AuthenticationFailed"
	// StorageErrorCodeConditionHeadersNotSupported ...
	StorageErrorCodeConditionHeadersNotSupported StorageErrorCodeType = "ConditionHeadersNotSupported"
	// StorageErrorCodeConditionNotMet ...
	StorageErrorCodeConditionNotMet StorageErrorCodeType = "ConditionNotMet"
	// StorageErrorCodeEmptyMetadataKey ...
	StorageErrorCodeEmptyMetadataKey StorageErrorCodeType = "EmptyMetadataKey"
	// StorageErrorCodeInsufficientAccountPermissions ...
	StorageErrorCodeInsufficientAccountPermissions StorageErrorCodeType = "InsufficientAccountPermissions"
	// StorageErrorCodeInternalError ...
	StorageErrorCodeInternalError StorageErrorCodeType = "InternalError"
	// StorageErrorCodeInvalidAuthenticationInfo ...
	StorageErrorCodeInvalidAuthenticationInfo StorageErrorCodeType = "InvalidAuthenticationInfo"
	// StorageErrorCodeInvalidHeaderValue ...
	StorageErrorCodeInvalidHeaderValue StorageErrorCodeType = "InvalidHeaderValue"
	// StorageErrorCodeInvalidHTTPVerb ...
	StorageErrorCodeInvalidHTTPVerb StorageErrorCodeType = "InvalidHttpVerb"
	// StorageErrorCodeInvalidInput ...
	StorageErrorCodeInvalidInput StorageErrorCodeType = "InvalidInput"
	// StorageErrorCodeInvalidMarker ...
	StorageErrorCodeInvalidMarker StorageErrorCodeType = "InvalidMarker"
	// StorageErrorCodeInvalidMd5 ...
	StorageErrorCodeInvalidMd5 StorageErrorCodeType = "InvalidMd5"
	// StorageErrorCodeInvalidMetadata ...
	StorageErrorCodeInvalidMetadata StorageErrorCodeType = "InvalidMetadata"
	// StorageErrorCodeInvalidQueryParameterValue ...
	StorageErrorCodeInvalidQueryParameterValue StorageErrorCodeType = "InvalidQueryParameterValue"
	// StorageErrorCodeInvalidRange ...
	StorageErrorCodeInvalidRange StorageErrorCodeType = "InvalidRange"
	// StorageErrorCodeInvalidResourceName ...
	StorageErrorCodeInvalidResourceName StorageErrorCodeType = "InvalidResourceName"
	// StorageErrorCodeInvalidURI ...
	StorageErrorCodeInvalidURI StorageErrorCodeType = "InvalidUri"
	// StorageErrorCodeInvalidXMLDocument ...
	StorageErrorCodeInvalidXMLDocument StorageErrorCodeType = "InvalidXmlDocument"
	// StorageErrorCodeInvalidXMLNodeValue ...
	StorageErrorCodeInvalidXMLNodeValue StorageErrorCodeType = "InvalidXmlNodeValue"
	// StorageErrorCodeMd5Mismatch ...
	StorageErrorCodeMd5Mismatch StorageErrorCodeType = "Md5Mismatch"
	// StorageErrorCodeMessageNotFound ...
	StorageErrorCodeMessageNotFound StorageErrorCodeType = "MessageNotFound"
	// StorageErrorCodeMessageTooLarge ...
	StorageErrorCodeMessageTooLarge StorageErrorCodeType = "MessageTooLarge"
	// StorageErrorCodeMetadataTooLarge ...
	StorageErrorCodeMetadataTooLarge StorageErrorCodeType = "MetadataTooLarge"
	// StorageErrorCodeMissingContentLengthHeader ...
	StorageErrorCodeMissingContentLengthHeader StorageErrorCodeType = "MissingContentLengthHeader"
	// StorageErrorCodeMissingRequiredHeader ...
	StorageErrorCodeMissingRequiredHeader StorageErrorCodeType = "MissingRequiredHeader"
	// StorageErrorCodeMissingRequiredQueryParameter ...
	StorageErrorCodeMissingRequiredQueryParameter StorageErrorCodeType = "MissingRequiredQueryParameter"
	// StorageErrorCodeMissingRequiredXMLNode ...
	StorageErrorCodeMissingRequiredXMLNode StorageErrorCodeType = "MissingRequiredXmlNode"
	// StorageErrorCodeMultipleConditionHeadersNotSupported ...
	StorageErrorCodeMultipleConditionHeadersNotSupported StorageErrorCodeType = "MultipleConditionHeadersNotSupported"
	// StorageErrorCodeNone represents an empty StorageErrorCodeType.
	StorageErrorCodeNone StorageErrorCodeType = ""
	// StorageErrorCodeOperationTimedOut ...
	StorageErrorCodeOperationTimedOut StorageErrorCodeType = "OperationTimedOut"
	// StorageErrorCodeOutOfRangeInput ...
	StorageErrorCodeOutOfRangeInput StorageErrorCodeType = "OutOfRangeInput"
	// StorageErrorCodeOutOfRangeQueryParameterValue ...
	StorageErrorCodeOutOfRangeQueryParameterValue StorageErrorCodeType = "OutOfRangeQueryParameterValue"
	// StorageErrorCodePopReceiptMismatch ...
	StorageErrorCodePopReceiptMismatch StorageErrorCodeType = "PopReceiptMismatch"
	// StorageErrorCodeQueueAlreadyExists ...
	StorageErrorCodeQueueAlreadyExists StorageErrorCodeType = "QueueAlreadyExists"
	// StorageErrorCodeQueueBeingDeleted ...
	StorageErrorCodeQueueBeingDeleted StorageErrorCodeType = "QueueBeingDeleted"
	// StorageErrorCodeQueueDisabled ...
	StorageErrorCodeQueueDisabled StorageErrorCodeType = "QueueDisabled"
	// StorageErrorCodeQueueNotEmpty ...
	StorageErrorCodeQueueNotEmpty StorageErrorCodeType = "QueueNotEmpty"
	// StorageErrorCodeQueueNotFound ...
	StorageErrorCodeQueueNotFound StorageErrorCodeType = "QueueNotFound"
	// StorageErrorCodeRequestBodyTooLarge ...
	StorageErrorCodeRequestBodyTooLarge StorageErrorCodeType = "RequestBodyTooLarge"
	// StorageErrorCodeRequestURLFailedToParse ...
	StorageErrorCodeRequestURLFailedToParse StorageErrorCodeType = "RequestUrlFailedToParse"
	// StorageErrorCodeResourceAlreadyExists ...
	StorageErrorCodeResourceAlreadyExists StorageErrorCodeType = "ResourceAlreadyExists"
	// StorageErrorCodeResourceNotFound ...
	StorageErrorCodeResourceNotFound StorageErrorCodeType = "ResourceNotFound"
	// StorageErrorCodeResourceTypeMismatch ...
	StorageErrorCodeResourceTypeMismatch StorageErrorCodeType = "ResourceTypeMismatch"
	// StorageErrorCodeServerBusy ...
	StorageErrorCodeServerBusy StorageErrorCodeType = "ServerBusy"
	// StorageErrorCodeUnsupportedHeader ...
	StorageErrorCodeUnsupportedHeader StorageErrorCodeType = "UnsupportedHeader"
	// StorageErrorCodeUnsupportedHTTPVerb ...
	StorageErrorCodeUnsupportedHTTPVerb StorageErrorCodeType = "UnsupportedHttpVerb"
	// StorageErrorCodeUnsupportedQueryParameter ...
	StorageErrorCodeUnsupportedQueryParameter StorageErrorCodeType = "UnsupportedQueryParameter"
	// StorageErrorCodeUnsupportedXMLNode ...
	StorageErrorCodeUnsupportedXMLNode StorageErrorCodeType = "UnsupportedXmlNode"
)

func PossibleStorageErrorCodeTypeValues

func PossibleStorageErrorCodeTypeValues() []StorageErrorCodeType

PossibleStorageErrorCodeTypeValues returns an array of possible values for the StorageErrorCodeType const type.

type StorageServiceProperties

type StorageServiceProperties struct {

	// Logging - Azure Analytics Logging settings
	Logging *Logging `xml:"Logging"`
	// HourMetrics - A summary of request statistics grouped by API in hourly aggregates for queues
	HourMetrics *Metrics `xml:"HourMetrics"`
	// MinuteMetrics - a summary of request statistics grouped by API in minute aggregates for queues
	MinuteMetrics *Metrics `xml:"MinuteMetrics"`
	// Cors - The set of CORS rules.
	Cors []CorsRule `xml:"Cors>CorsRule"`
	// contains filtered or unexported fields
}

StorageServiceProperties - Storage Service Properties.

func (StorageServiceProperties) ErrorCode

func (ssp StorageServiceProperties) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (StorageServiceProperties) RequestID

func (ssp StorageServiceProperties) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (StorageServiceProperties) Response

func (ssp StorageServiceProperties) Response() *http.Response

Response returns the raw HTTP response object.

func (StorageServiceProperties) Status

func (ssp StorageServiceProperties) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (StorageServiceProperties) StatusCode

func (ssp StorageServiceProperties) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (StorageServiceProperties) Version

func (ssp StorageServiceProperties) Version() string

Version returns the value for header x-ms-version.

type StorageServiceStats

type StorageServiceStats struct {

	// GeoReplication - Geo-Replication information for the Secondary Storage Service
	GeoReplication *GeoReplication `xml:"GeoReplication"`
	// contains filtered or unexported fields
}

StorageServiceStats - Stats for the storage service.

func (StorageServiceStats) Date

func (sss StorageServiceStats) Date() time.Time

Date returns the value for header Date.

func (StorageServiceStats) ErrorCode

func (sss StorageServiceStats) ErrorCode() string

ErrorCode returns the value for header x-ms-error-code.

func (StorageServiceStats) RequestID

func (sss StorageServiceStats) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (StorageServiceStats) Response

func (sss StorageServiceStats) Response() *http.Response

Response returns the raw HTTP response object.

func (StorageServiceStats) Status

func (sss StorageServiceStats) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (StorageServiceStats) StatusCode

func (sss StorageServiceStats) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (StorageServiceStats) Version

func (sss StorageServiceStats) Version() string

Version returns the value for header x-ms-version.

type TelemetryOptions

type TelemetryOptions struct {
	// Value is a string prepended to each request's User-Agent and sent to the service.
	// The service records the user-agent in logs for diagnostics and tracking of client requests.
	Value string
}

TelemetryOptions configures the telemetry policy's behavior.

type TokenCredential

type TokenCredential interface {
	Credential
	Token() string
	SetToken(newToken string)
}

TokenCredential represents a token credential (which is also a pipeline.Factory).

func NewTokenCredential

func NewTokenCredential(initialToken string, tokenRefresher TokenRefresher) TokenCredential

NewTokenCredential creates a token credential for use with role-based access control (RBAC) access to Azure Storage resources. You initialize the TokenCredential with an initial token value. If you pass a non-nil value for tokenRefresher, then the function you pass will be called immediately so it can refresh and change the TokenCredential's token value by calling SetToken. Your tokenRefresher function must return a time.Duration indicating how long the TokenCredential object should wait before calling your tokenRefresher function again. If your tokenRefresher callback fails to refresh the token, you can return a duration of 0 to stop your TokenCredential object from ever invoking tokenRefresher again. Also, oen way to deal with failing to refresh a token is to cancel a context.Context object used by requests that have the TokenCredential object in their pipeline.

type TokenRefresher

type TokenRefresher func(credential TokenCredential) time.Duration

TokenRefresher represents a callback method that you write; this method is called periodically so you can refresh the token credential's value.

type UpdatedMessageResponse

type UpdatedMessageResponse struct {

	// PopReceipt returns the value for header x-ms-popreceipt.
	PopReceipt PopReceipt

	// TimeNextVisible returns the value for header x-ms-time-next-visible.
	TimeNextVisible time.Time
	// contains filtered or unexported fields
}

func (UpdatedMessageResponse) Date

func (miur UpdatedMessageResponse) Date() time.Time

Date returns the value for header Date.

func (UpdatedMessageResponse) RequestID

func (miur UpdatedMessageResponse) RequestID() string

RequestID returns the value for header x-ms-request-id.

func (UpdatedMessageResponse) Response

func (miur UpdatedMessageResponse) Response() *http.Response

Response returns the raw HTTP response object.

func (UpdatedMessageResponse) Status

func (miur UpdatedMessageResponse) Status() string

Status returns the HTTP status message of the response, e.g. "200 OK".

func (UpdatedMessageResponse) StatusCode

func (miur UpdatedMessageResponse) StatusCode() int

StatusCode returns the HTTP status code of the response, e.g. 200.

func (UpdatedMessageResponse) Version

func (miur UpdatedMessageResponse) Version() string

Version returns the value for header x-ms-version.

Jump to

Keyboard shortcuts

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