gorax

package module
v0.0.0-...-8e891f6 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2013 License: Apache-2.0 Imports: 8 Imported by: 0

README

gorax V0.0.1

The Go ecosystem seems to lack a comprehensive cloud services API (at the time this README was first written). As both Go and cloud services are trending in many businesses, and with Go used increasingly in infrastructure, it seems like an odd omission. To fill this gap, gorax provides a Go binding to the Rackspace cloud APIs. Rackspace offers many APIs that are compatible with OpenStack, and thus provides an ideal springboard for wider OpenStack technology adoption in the Go community.

The name, gorax, is derived from its sister (and, presently, far more complete) project Pyrax, which offers similar capabilities for Python.

This library is still in the very early stages of development. Unless you want to contribute, it probably isn't what you want

Build Status

Build Status

Installation and Testing

To install:

go get github.com/racker/gorax

To run unit tests:

go test github.com/racker/gorax/v2.0/cloud/server
go test github.com/racker/gorax/v2.0/identity

To run integration tests and examples, you'll need a Rackspace cloud user account and password. You may find the tests and examples in the github.com/racker/gorax/exampels directory. Note that most, if not all, of the examples therein require a username and password to run. For this reason, no scripting to invoke these tests exist.

Contributing

The following guidelines are preliminary, as this project is just starting out. However, this should serve as a working first-draft.

Branching

The master branch must always be a valid build. The go get command will not work otherwise. Therefore, development must occur on a different branch. As with Pyrax, we choose to stage all changes in a branch named "working."

When creating a feature branch, do so off the working branch:

git checkout working
git pull
git checkout -b featureBranch
git checkout -b featureBranch-wip

Perform all your editing and testing in the WIP-branch. Feel free to make as many commits as you see fit. You may even open "WIP" pull requests from your feature branch to seek feedback. WIP pull requests will never be merged, however.

To get code merged, you'll need to "squash" your changes into a single commit. These steps should be followed:

git checkout featureBranch
git merge --squash featureBranch-wip
git commit -a
git push origin featureBranch

You may now open a nice, clean, self-contained pull request from featureBranch to working.

The git commit -a command above will open a text editor so that you may provide a comprehensive description of the changes.

In general, when submitting a pull request against working, be sure to answer the following questions:

  • What is the problem?
  • Why is it a problem?
  • What is your solution?
  • How does your solution work? (Recommended for non-trivial changes.)
  • Why should we use your solution over someone elses? (Recommended especially if multiple solutions being discussed.)

Remember that monster-sized pull requests are a bear to code-review, so having helpful commit logs are an absolute must to review changes as quickly as possible.

Finally, (s)he who breaks working is ultimately responsible for fixing working.

Source Representation

The Go community firmly believes in a consistent representation for all Go source code. We do too. Make sure all source code is passed through "go fmt" before you create your pull request.

Please note, however, that we fully acknowledge and recognize that we no longer rely upon punch-cards for representing source files. Therefore, no 80-column limit exists. However, if a line exceeds 132 columns, you may want to consider splitting the line.

Unit and Integration Tests

Pull requests that include non-trivial code changes without accompanying unit tests will be flatly rejected. While we have no way of enforcing this practice, you can ensure your code is thoroughly tested by always writing tests first by intention.

When creating a pull request, if even one test fails, the PR will be rejected. Make sure all unit tests pass. Make sure all integration tests pass.

Documentation

Private functions and methods which are obvious to anyone unfamiliar with gorax needn't be accompanied by documentation. However, this is a code-smell; if submitting a PR, expect to justify your decision.

Public functions, regardless of how obvious, must have accompanying godoc-style documentation. This is not to suggest you should provide a tome for each function, however. Sometimes a link to more information is more appropriate, provided the link is stable, reliable, and pertinent.

Changing documentation often results in bizarre diffs in pull requests, due to text often spanning multiple lines. To work around this, put one logical thought or sentence on a single line. While this looks weird in a plain-text editor, remember that both godoc and HTML viewers will reflow text. The source code and its comments should be easy to edit with minimal diff pollution. Let software dedicated to presenting the documentation to human readers deal with its presentation.

Examples

Image List from a Region
package main

import (
	"fmt"
	"github.com/racker/gorax/v2.0/cloud/servers"
	"github.com/racker/gorax/v2.0/identity"
	"os"
)

func main() {
	if len(os.Args) < 3 {
		panic("Usage: I need both username and API key on CLI, in that order.")
	}
	username := os.Args[1]
	password := os.Args[2]

	id := identity.NewIdentity(username, password, "")
	err := id.Authenticate()
	if err != nil {
		panic(err)
	}

	region, err := servers.RegionByName(id, "dfw")
	if err != nil {
		panic(err)
	}

	images, err := region.Images()
	if err != nil {
		panic(err)
	}

	fmt.Printf("%-36s   Name\n", "UUID")
	for _, i := range images {
		fmt.Printf("%36s - %s\n", string(i.Id[0:36]), i.Name)
	}
}
Cloud Monitoring

Preliminary.

package main

import (
  "github.com/racker/gorax/monitoring"
  "github.com/racker/gorax/identity"
  "fmt"
)

func main() {
  cm := monitoring.MakePasswordMonitoringClient("https://monitoring.api.rackspacecloud.com/v1.0", identity.USIdentityService, "username", "password")
  cm.SetDebug(true)
  checks, err := cm.ListChecks("enuzk2tiph")
  fmt.Printf("%s\n", checks)
  fmt.Printf("%s\n", err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type JSONRequestBody

type JSONRequestBody struct {
	Object interface{}
	// contains filtered or unexported fields
}

func (*JSONRequestBody) Body

func (b *JSONRequestBody) Body() (io.Reader, error)

func (*JSONRequestBody) ContentLength

func (b *JSONRequestBody) ContentLength() (int64, error)

func (*JSONRequestBody) ContentType

func (b *JSONRequestBody) ContentType() (string, error)

type RequestBody

type RequestBody interface {
	ContentType() (string, error)
	ContentLength() (int64, error)
	Body() (io.Reader, error)
}

The RequestBody interface represents an abstract concept of a hunk of data passed along with an HTTP request. Bodies may be part of a request, a response, or both, depending upon the resource accessed and the method used.

The ContentType() (string, error) method yields the official, even if experimental, MIME type string for the content in the body. The ContentLength() (int64, error) method yields its length. Finally, the Body() (io.Reader, error) method yields a reader interface that allows the client software access to the contents of the data.

type RequestMiddleware

type RequestMiddleware interface {
	HandleRequest(*RestRequest) (*RestRequest, error)
}

type RestClient

type RestClient struct {
	BaseUrl            string
	RequestMiddlewares []RequestMiddleware
	Debug              bool
	// contains filtered or unexported fields
}

The RestClient object encapsulates a connection to a RESTful service. Several assumptions are made about this service:

1. All resources exposed by the service sits under a single root path, referenced by the field named BaseUrl. 2. All requests made to the service pass through a set of "middleware" filters (more generally, "middlewares"). This set may be empty, and may be inspected via the RequestMiddlewares field. 3. If any one of the filters produces an error, the entire request fails. 4. Filters may alter the original request. For example, an authentication filter may inject an authentication token, while a tracing filter may inject a unique tracing token for logging purposes.

Additionally, the Debug field indicates whether or not request/response logging (usually to stdout) occurs.

func MakeRestClient

func MakeRestClient(url string) *RestClient

MakeRestClient() creates a new RestClient reference to a RESTful service. The provided URL sets the BaseUrl of the client, which scopes the resource paths of all RestRequests used to invoke services. This function can never fail except in out-of-memory situations.

func (*RestClient) PerformRequest

func (c *RestClient) PerformRequest(restReq *RestRequest) (*RestResponse, error)

PerformRequest() returns the RESTful response to a RESTful request against a web server. The request must be encapsulated in a RestRequest object.

This function will return with an error if the REST server provides a response which is not anticipated by the client software. To configure the list of anticipated response codes, the RestRequest must have a non-nil ExpectedStatusCodes field value. See the RestRequest type for more details.

If the request is in debug mode, diagnostic dumps of the HTTP traffic will appear on stdout.

PerformRequest() computes the content length and type from the request's configured body, if any exists.

If the accepted response type isn't explicitly set prior to calling PerformRequest(), it will be set to application/json by default.

PerformRequest() takes care of applying any transformations to your request via the client's configured set of middleware filters. For example, if a client has a password authenticator middleware filter configured for it, then all requests made through that client will have its provided username and password fields authenticated in prior to the actual and intended request handler for the specified resource.

func (*RestClient) SetDebug

func (c *RestClient) SetDebug(debug bool)

The SetDebug() function either enables (true) or disables (false) diagnostic output to stdout of all traffic (request and response alike) made through the client.

type RestError

type RestError struct {
	ErrorString string
}

func (*RestError) Error

func (e *RestError) Error() string

type RestRequest

type RestRequest struct {
	Method              string
	Path                string
	Header              http.Header
	Body                RequestBody
	ExpectedStatusCodes []int
}

The RestRequest object encapsulates a single RESTful request.

The Method field indicates what operation to perform on the web server. Unless you know what you're doing, you should restrain your methods to the basic set of GET, PUT, POST, and DELETE.

Path indicates the specific resource the request is being applied against. When making a RestClient object, you'll be able to specify a prefix which scopes this field. Thus, the Path field is always relative to the RestClient's base URL. See also the RestClient type.

Header provides a mapping of MIME header keys to one or more values for each key. Refer to http://godoc.org/net/http#Header for more details. This field may be set to nil if the client needs no headers. However, upon making the first REST request, a nil Header field will be initialized to an empty Header map.

Body provides an optional body for the request.

ExpectedStatusCodes provides a set of response codes considered to be valid for the request. This field may also be nil if you just don't care about response checking.

type RestResponse

type RestResponse struct {
	*http.Response
}

func (*RestResponse) DeserializeBody

func (r *RestResponse) DeserializeBody(target interface{}) error

DeserializeBody() recreates an object graph as denoted in the REST response's body.

This method will return an error if the response's content-type cannot be recognized. Presently, the RestResponse type only supports application/json; future versions of this type may support additional types. Refer to http://godoc.org/encoding/json for more information.

Directories

Path Synopsis
v2.0

Jump to

Keyboard shortcuts

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