1//
2// Copyright (c) 2018, Joyent, Inc. All rights reserved.
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7//
8
9package compute
10
11import (
12	"context"
13	"encoding/json"
14	"net/http"
15
16	"github.com/joyent/triton-go/client"
17	pkgerrors "github.com/pkg/errors"
18)
19
20const pingEndpoint = "/--ping"
21
22type CloudAPI struct {
23	Versions []string `json:"versions"`
24}
25
26type PingOutput struct {
27	Ping     string   `json:"ping"`
28	CloudAPI CloudAPI `json:"cloudapi"`
29}
30
31// Ping sends a request to the '/--ping' endpoint and returns a `pong` as well
32// as a list of API version numbers your instance of CloudAPI is presenting.
33func (c *ComputeClient) Ping(ctx context.Context) (*PingOutput, error) {
34	reqInputs := client.RequestInput{
35		Method: http.MethodGet,
36		Path:   pingEndpoint,
37	}
38	response, err := c.Client.ExecuteRequestRaw(ctx, reqInputs)
39	if err != nil {
40		return nil, pkgerrors.Wrap(err, "unable to ping")
41	}
42	if response == nil {
43		return nil, pkgerrors.Wrap(err, "unable to ping")
44	}
45	if response.Body != nil {
46		defer response.Body.Close()
47	}
48
49	var result *PingOutput
50	decoder := json.NewDecoder(response.Body)
51	if err = decoder.Decode(&result); err != nil {
52		if err != nil {
53			return nil, pkgerrors.Wrap(err, "unable to decode ping response")
54		}
55	}
56
57	return result, nil
58}
59