go-maxcdn: github.com/MaxCDN/go-maxcdn Index | Examples | Files

package maxcdn

import "github.com/MaxCDN/go-maxcdn"

Package maxcdn is the Golang bindings for MaxCDN's REST API.

Developer Notes:

- Custom types can be (somewhat) easily generated by using `maxcurl` (see: https://github.com/MaxCDN/maxcdn-tools/tree/master/maxcurl) to fetch the raw json output and the `json2struct` tool at http://mervine.net/json2struct to generate a sample struct. In the resulting struct, I recommend changing a `float64` types to `int` types and replacing any resulting `interface{}` types with `string` types.

Code:

// Basic Get
max := NewMaxCDN(alias, token, secret)
var got Generic
res, err := max.Get(&got, "/account.json", nil)
if err != nil {
    panic(err)
}

fmt.Printf("code: %d\n", res.Code)
fmt.Printf("name: %s\n", got["name"].(string))

// Basic Put
form := url.Values{}
form.Set("name", "new name")

var put Generic
if _, err = max.Put(&put, "/account.json", form); err == nil &&
    put["name"].(string) == "new name" {
    fmt.Println("name successfully updated")
}

// Basic Delete
if _, err = max.Delete("/zones/pull.json/123456", nil); err == nil {
    fmt.Println("zone successfully deleted")
}

// Logs
if logs, err := max.GetLogs(nil); err == nil {
    for _, line := range logs.Records {
        fmt.Printf("%+v\n", line)
    }
}

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/account.json", nil); err == nil {
    fmt.Printf("%+v\n", data)
}

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/account.json/address", nil); err == nil {
    fmt.Printf("%+v\n", data)
}

Code:

var form url.Values

name := stringFromTimestamp()
max := NewMaxCDN(alias, token, secret)

if alias == "" || token == "" || secret == "" {
    max.HTTPClient = stubHTTPOk()
}

// GET /account.json
var getAcct Generic
res, err := max.Get(&getAcct, "/account.json", nil)
if err != nil || res.Code != 200 ||
    getAcct["account"].(map[string]interface{})["name"].(string) == "" {
    fmt.Println("GET account")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", getAcct)
}

// PUT /account.json
var putAcct Generic
form = url.Values{}
form.Set("name", name)
res, err = max.Put(&putAcct, "/account.json", form)
if err != nil || res.Code != 200 ||
    putAcct["account"].(map[string]interface{})["name"].(string) == "" {
    fmt.Println("PUT account")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", putAcct)
}

// GET /account.json/address
var getAddr Generic
res, err = max.Get(&getAddr, "/account.json/address", nil)
if err != nil || res.Code != 200 ||
    getAddr["address"].(map[string]interface{})["street1"].(string) == "" {
    fmt.Println("GET address")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", getAddr)
}

// PUT /account.json/address
var putAddr Generic
form = url.Values{}
form.Set("street1", name)
res, err = max.Put(&putAddr, "/account.json/address", form)
if err != nil || res.Code != 200 ||
    putAddr["address"].(map[string]interface{})["street1"].(string) == "" {
    fmt.Println("GET address")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", putAddr)
}

// GET /reports/popularfiles.json
var popular Generic
res, err = max.Get(&popular, "/reports/popularfiles.json", nil)
if err != nil || res.Code != 200 ||
    popular["popularfiles"].([]interface{})[0].(map[string]interface{})["uri"].(string) == "" {
    fmt.Println("GET popularfiles")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", popular)
}

file := popular["popularfiles"].([]interface{})[0].(map[string]interface{})["uri"].(string)

// GET /reports/stats.json
var stats Generic
res, err = max.Get(&stats, "/reports/stats.json", nil)
if err != nil || res.Code != 200 || stats["total"] == "" {
    fmt.Println("GET stats")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", stats)
}

// GET /reports/stats.json/daily
var daily Generic
res, err = max.Get(&daily, "/reports/stats.json/daily", nil)
if err != nil || res.Code != 200 || daily["total"] == "" {
    fmt.Println("GET stats/daily")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", daily)
}

// GET /zones/pull.json
var getPulls Generic
res, err = max.Get(&getPulls, "/zones/pull.json", nil)
if err != nil || res.Code != 200 ||
    getPulls["pullzones"].([]interface{})[0].(map[string]interface{})["id"].(string) == "" {
    fmt.Println("GET zones/getPull")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", daily)
}

// note: order matters for the rest

// POST /zones/pull.json
var postPull Generic
form = url.Values{}
form.Set("name", name)
form.Set("url", "http://www.example.com")
res, err = max.Post(&postPull, "/zones/pull.json", form)
if err != nil || res.Code != 201 ||
    postPull["pullzone"].(map[string]interface{})["name"].(string) == "" {
    fmt.Println("POST zones/pull")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", daily)
}

id := int(postPull["pullzone"].(map[string]interface{})["id"].(float64))

// GET /zones/pull.json/{{zone_id}}
var getPull Generic
endpoint := fmt.Sprintf("/zones/pull.json/%d", id)
res, err = max.Get(&getPull, endpoint, nil)
if err != nil || res.Code != 200 ||
    getPull["pullzone"].(map[string]interface{})["id"].(string) == "" {
    fmt.Println("GET zones/getPull/{{zone_id}}")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
    fmt.Printf("data:\n%+v\n", getPull)
}

// DELETE /zones/pull.json/{{zone_id}}
res, err = max.Delete(endpoint, nil)
if err != nil || res.Code != 200 {
    fmt.Println("DELETE zones/pull/{{zone_id}}")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
}

// PurgeZone
if res, err := max.PurgeZone(id); err != nil || res.Code != 200 {
    fmt.Println("PurgeZone")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
}

// PurgeFile
if res, err := max.PurgeFile(id, file); err != nil || res.Code != 200 {
    fmt.Println("PurgeFile")
    fmt.Printf("error:\n%+v\n", err)
    fmt.Printf("code:\n%+v\n", res.Code)
}

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/account.json", nil); err == nil {
    alias := data["alias"].(string)
    name := data["name"].(string)
    fmt.Printf("alias: %s\n", alias)
    fmt.Printf("name:  %s\n", name)
}

Code:

max := NewMaxCDN(alias, token, secret)
fmt.Printf("%#v\n", max)

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/reports/popularfiles.json", nil); err == nil {
    for i, file := range data {
        uri := file.(map[string]interface{})["uri"].(string)
        hit := file.(map[string]interface{})["hit"].(string)
        fmt.Printf("%2s: %30s=%s, \n", i, uri, hit)
    }
}
fmt.Println("----")
summaryHit := data["summary"].(map[string]interface{})["uri"].(string)
fmt.Printf("    %30s=%s, \n", "summary", summaryHit)

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
response, _ := max.Get(&data, "/account.json", nil)
fmt.Printf("%+v\n", response)

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/reports/stats.json/hourly", nil); err == nil {
    fmt.Printf("%+v\n", data)
}

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
if _, err := max.Get(&data, "/reports/stats.json", nil); err == nil {
    fmt.Printf("%+v\n", data)
}

Index

Examples

Package Files

doc.go maxcdn.go types.go

Variables

var APIHost = "https://rws.maxcdn.com"

APIHost is the hostname, including protocol, to MaxCDN's API.

type Error Uses

type Error struct {
    Message string `json:"message,omitempty"`
    Type    string `json:"type,omitempty"`
}

Error represent a maxcnd error.

func (Error) Error Uses

func (e Error) Error() string

Error implements go's error interface.

type Generic Uses

type Generic map[string]interface{}

Generic is the generic data type for JSON responses from API calls.

type LogRecord Uses

type LogRecord struct {
    Bytes           int     `json:"bytes"`
    CacheStatus     string  `json:"cache_status"`
    ClientAsn       string  `json:"client_asn"`
    ClientCity      string  `json:"client_city"`
    ClientContinent string  `json:"client_continent"`
    ClientCountry   string  `json:"client_country"`
    ClientDma       string  `json:"client_dma"`
    ClientIP        string  `json:"client_ip"`
    ClientLatitude  float64 `json:"client_latitude"`
    ClientLongitude float64 `json:"client_longitude"`
    ClientState     string  `json:"client_state"`
    CompanyID       int     `json:"company_id"`
    Hostname        string  `json:"hostname"`
    Method          string  `json:"method"`
    OriginTime      float64 `json:"origin_time"`
    Pop             string  `json:"pop"`
    Protocol        string  `json:"protocol"`
    QueryString     string  `json:"query_string"`
    Referer         string  `json:"referer"`
    Scheme          string  `json:"scheme"`
    Status          int     `json:"status"`
    Time            string  `json:"time"`
    URI             string  `json:"uri"`
    UserAgent       string  `json:"user_agent"`
    ZoneID          int     `json:"zone_id"`
}

LogRecord holds the data of a single record.

type Logs Uses

type Logs struct {
    Limit       int         `json:"limit"`
    NextPageKey string      `json:"next_page_key"`
    Page        int         `json:"page"`
    Records     []LogRecord `json:"records"`
    RequestTime int         `json:"request_time"`
}

Logs .

type MaxCDN Uses

type MaxCDN struct {

    // MaxCDN Consumer Alias
    Alias string

    // Display raw http Request and Response for each http Transport
    Verbose bool

    HTTPClient *http.Client
    // contains filtered or unexported fields
}

MaxCDN is the core struct for interacting with MaxCDN.

HTTPClient can be overridden as needed, but will be set to http.DefaultClient by default.

Code:

// This specific example shows how to purge a cache without using the Purge
// methods, more as an example of using Delete, then anything, really.
max := NewMaxCDN(alias, token, secret)

res, err := max.Delete("/zones/pull.json/123456/cache", nil)
if err != nil {
    panic(err)
}

if res.Code == 200 {
    fmt.Println("Purge suucceeded")
}

Code:

// Run low-level Do method.
max := NewMaxCDN(alias, token, secret)

if rsp, err := max.Do("GET", "/account.json", nil); err == nil {
    fmt.Printf("Response Code: %d\n", rsp.Code)

    var data Generic
    if err = json.Unmarshal(rsp.Data, &data); err == nil {
        fmt.Printf("%+v\n", data["account"])
    }
}

Code:

// Run mid-level DoParse method.
max := NewMaxCDN(alias, token, secret)

var data Generic
response, err := max.DoParse(&data, "GET", "/account.json/address", nil)
if err != nil {
    panic(err)
}

fmt.Printf("code: %d\n", response.Code)
fmt.Printf("name: %s\n", data["street1"].(string))

Code:

max := NewMaxCDN(alias, token, secret)

var data Generic
response, err := max.Get(&data, "/account.json/address", nil)
if err != nil {
    panic(err)
}

fmt.Printf("code: %d\n", response.Code)
fmt.Printf("name: %s\n", data["street1"].(string))

Code:

max := NewMaxCDN(alias, token, secret)
if logs, err := max.GetLogs(nil); err == nil {
    for _, line := range logs.Records {
        fmt.Printf("%+v\n", line)
    }
}

Code:

max := NewMaxCDN(alias, token, secret)

form := url.Values{}
form.Set("name", "newzone")

// When creating a new zone, the url must be real and resolve.
form.Set("url", "http://www.example.com")

var data Generic
_, err := max.Post(&data, "/zones/pull.json", form)
if err != nil {
    panic(err)
}

if data["name"].(string) == "newzone" {
    fmt.Println("Successfully created new Pull Zone.")
}

Code:

max := NewMaxCDN(alias, token, secret)

payload, err := max.PurgeFile(123456, "/master.css")
if err != nil {
    panic(err)
}

if payload.Code == 200 {
    fmt.Println("Purge succeeded")
}

Code:

max := NewMaxCDN(alias, token, secret)

files := []string{"/master.css", "/master.js"}
payloads, err := max.PurgeFiles(123456, files)
if err != nil {
    panic(err)
}

if len(payloads) == len(files) {
    fmt.Printf("Purges succeeded")
}

Code:

max := NewMaxCDN(alias, token, secret)

rsp, err := max.PurgeZone(123456)
if err != nil {
    panic(err)
}

if rsp.Code == 200 {
    fmt.Println("Purge succeeded")
}

Code:

max := NewMaxCDN(alias, token, secret)

zones := []int{123456, 234567, 345678}
rsps, err := max.PurgeZones(zones)
if err != nil {
    panic(err)
}

if len(rsps) == len(zones) {
    fmt.Printf("Purges succeeded")
}

Code:

max := NewMaxCDN(alias, token, secret)

form := url.Values{}
form.Set("name", "example name")

var data Generic
response, err := max.Put(&data, "/account.json", form)
if err != nil {
    panic(err)
}

fmt.Printf("code: %d\n", response.Code)
fmt.Printf("name: %s\n", data["name"].(string))

Code:

// Run low-level Request method.
max := NewMaxCDN(alias, token, secret)

check := func(e error) {
    if e != nil {
        panic(e)
    }
}

res, err := max.Request("GET", "/account.json", nil)
defer res.Body.Close()
check(err)

body, err := ioutil.ReadAll(res.Body)
check(err)

fmt.Println(string(body))

func NewMaxCDN Uses

func NewMaxCDN(alias, token, secret string) *MaxCDN

NewMaxCDN sets up a new MaxCDN instance.

func (*MaxCDN) Delete Uses

func (max *MaxCDN) Delete(endpoint string, form url.Values) (*Response, error)

Delete does an OAuth signed http.Delete

Delete does not take an endpointType because delete only returns a status code.

func (*MaxCDN) Do Uses

func (max *MaxCDN) Do(method, endpoint string, form url.Values) (*Response, error)

Do is a low level method to interact with MaxCDN's RESTful API via Request and return a parsed Response. It's used by all other methods.

This method closes the raw http.Response body.

func (*MaxCDN) DoParse Uses

func (max *MaxCDN) DoParse(endpointType interface{}, method, endpoint string, form url.Values) (*Response, error)

DoParse execute the http query and unmarshal the data into `endpointType`.

func (*MaxCDN) Get Uses

func (max *MaxCDN) Get(endpointType interface{}, endpoint string, form url.Values) (*Response, error)

Get does an OAuth signed http.Get

func (*MaxCDN) GetLogs Uses

func (max *MaxCDN) GetLogs(form url.Values) (Logs, error)

GetLogs is a seperate getter for MaxCDN's logs.json endpoint, as it currently doesn't follow the json format of other endpoints.

func (*MaxCDN) Post Uses

func (max *MaxCDN) Post(endpointType interface{}, endpoint string, form url.Values) (*Response, error)

Post does an OAuth signed http.Post

func (*MaxCDN) PurgeFile Uses

func (max *MaxCDN) PurgeFile(zone int, file string) (*Response, error)

PurgeFile purges a specified file by zone from cache.

func (*MaxCDN) PurgeFileString Uses

func (max *MaxCDN) PurgeFileString(zone string, file string) (*Response, error)

PurgeFileString purges a specified file by zone from cache.

func (*MaxCDN) PurgeFiles Uses

func (max *MaxCDN) PurgeFiles(zone int, files []string) ([]*Response, error)

PurgeFiles purges multiple files from a zone.

func (*MaxCDN) PurgeZone Uses

func (max *MaxCDN) PurgeZone(zone int) (*Response, error)

PurgeZone purges a specified zones cache.

func (*MaxCDN) PurgeZoneString Uses

func (max *MaxCDN) PurgeZoneString(zone string) (*Response, error)

PurgeZoneString purges a specified zones cache.

func (*MaxCDN) PurgeZones Uses

func (max *MaxCDN) PurgeZones(zones []int) ([]*Response, error)

PurgeZones purges multiple zones caches.

func (*MaxCDN) PurgeZonesString Uses

func (max *MaxCDN) PurgeZonesString(zones []string) ([]*Response, error)

PurgeZonesString purges multiple zones caches.

func (*MaxCDN) Put Uses

func (max *MaxCDN) Put(endpointType interface{}, endpoint string, form url.Values) (*Response, error)

Put does an OAuth signed http.Put

func (*MaxCDN) Request Uses

func (max *MaxCDN) Request(method, endpoint string, form url.Values) (*http.Response, error)

Request is a low level method to interact with MaxCDN's RESTful API. It's used by all other methods.

If using this method, you must manually close the res.Body or bad things may happen.

type Response Uses

type Response struct {
    Code  int             `json:"code,omitempty"`
    Data  json.RawMessage `json:"data,omitempty"`
    Error Error           `json:"error,omitempty"`

    // Non-JSON data.
    Headers http.Header `json:"-"`
}

Response object for all json requests.

Package maxcdn imports 10 packages (graph) and is imported by 4 packages. Updated 2018-05-08. Refresh now. Tools for package owners.