« Back to Index

Go: Enums

View original Gist on GitHub

Tags: #go

Golang enums with method for comparison.go

package main

import (
	"fmt"
)

// Product is a base for the different product variants.
type Product int64

// Implements Stringer interface so that fmt.Printf will 
// be able to to convert from int64 to string via %s format.
func (p Product) String() string {
	switch p {
	case ProductBrotliCompression:
		return "brotli_compression"
	case ProductDomainInspector:
		return "domain_inspector"
	case ProductFanout:
		return "fanout"
	case ProductImageOptimizer:
		return "image_optimizer"
	case ProductOriginInspector:
		return "origin_inspector"
	case ProductWebSockets:
		return "websockets"
	}
	return "unknown"
}

const (
	ProductUndefined Product = iota
	ProductBrotliCompression
	ProductDomainInspector
	ProductFanout
	ProductImageOptimizer
	ProductOriginInspector
	ProductWebSockets
)

// ProductEnablementInput is used as input to the various ProductEnablement
// functions.
type ProductEnablementInput struct {
	// ProductID is the ID of the product and is constrained by the Product type (required).
	ProductID Product
	// ServiceID is the ID of the service (required).
	ServiceID string
}

// GetProductEnablement retrieves the specified resource.
func (c *Client) GetProductEnablement(i *ProductEnablementInput) (*ProductEnablement, error) {
	if i.ProductID == ProductUndefined {
		return nil, ErrMissingProductID
	}
	if i.ServiceID == "" {
		return nil, ErrMissingServiceID
	}

	path := fmt.Sprintf("/enabled-products/%s/services/%s", i.ProductID, i.ServiceID)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var h *ProductEnablement
	if err := decodeBodyMap(resp.Body, &h); err != nil {
		return nil, err
	}

	return h, nil
}