Go ExampleΒΆ

This is an example of how to use the Memset API with Go (golang) and the standard library JSON package.

Substitute API_KEY_HEX with a valid API key.

// Memset API example with Go
//
// This was written with Go 1 and only uses standard library components
//
// It uses the JSON interface to the Memset API and it uses the
// generic JSON tools in Go.  This means that it is necessary to use
// type assertions to read data from the API.  See below for some
// examples.
//
// The Rpc* functions below can be used as helper functions to make
// the dynamically typed API more compatible with a statically typed
// language like Go

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

var uri = "https://API_KEY_HEX:@api.memset.com/v1/json/"

type Param map[string]interface{}

// An RPC function for the Memset API
// Call with a method name and a Param map returns an interface{}
// which is most likely a map[string]interface{} of results
func Rpc(method string, params Param) (interface{}, error) {
	encoded_params, err := json.Marshal(params)
	if err != nil {
		return nil, err
	}
	resp, err := http.PostForm(uri+method, url.Values{"parameters": {string(encoded_params)}})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("Bad response %s", resp.Status)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var result interface{}
	err = json.Unmarshal(body, &result)
	return result, err
}

// As Rpc but will log.Fatal any error messages
func RpcChecked(method string, params Param) interface{} {
	result, err := Rpc(method, params)
	if err != nil {
		log.Fatal(err)
	}
	return result
}

// As RpcChecked but returns the result as a map
func RpcCheckedMap(method string, params Param) Param {
	return RpcChecked(method, params).(map[string]interface{})
}

// As RpcChecked but returns the result as an array of maps
func RpcCheckedMapArray(method string, params Param) []Param {
	result := RpcChecked(method, params).([]interface{})
	new_result := make([]Param, len(result))
	for i := range result {
		new_result[i] = result[i].(map[string]interface{})
	}
	return new_result
}

func main() {
	fmt.Println("get the service list")
	r := RpcCheckedMapArray("service.list", Param{})
	fmt.Println(r)
	fmt.Println("First service", r[0])
	fmt.Println("First service nickname", r[0]["nickname"])

	fmt.Println("get the server list")
	r = RpcCheckedMapArray("server.list", Param{})
	fmt.Println(r)
	fmt.Println("First server", r[0])
	fmt.Println("First server nickname", r[0]["nickname"].(string))

	fmt.Println("get server information (one parameter)")
	result := RpcCheckedMap("server.info", Param{"name": "myserver1"})
	for key, value := range result {
		fmt.Printf("  %s = %v\n", key, value)
	}
	// use type assertions to get values out and use them
	nickname := result["nickname"].(string)
	fmt.Printf("Nickname is %s\n", nickname)
	monitor := result["monitor"].(bool)
	if monitor {
		fmt.Println("Monitoring is On")
	} else {
		fmt.Println("Monitoring is Off")
	}

	fmt.Println("set a new nickname for a product (two parameters)")
	result = RpcCheckedMap("service.set_nickname", Param{"name": "myserver1", "nickname": "www"})
	fmt.Println(result)

	fmt.Println("reboot a server")
	job := RpcCheckedMap("server.reboot", Param{"name": "myserver1"})
	for !job["finished"].(bool) {
		fmt.Println("Waiting for reboot to finish...")
		time.Sleep(5 * time.Second)
		job = RpcCheckedMap("job.status", Param{"id": job["id"]})
	}
	if !job["error"].(bool) {
		fmt.Println("Reboot OK")
	} else {
		fmt.Println("Reboot FAILED")
	}
}

Previous topic

Perl 5 Example

Next topic

cURL Example

This Page