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	"path"
16	"sort"
17
18	"github.com/joyent/triton-go/client"
19	"github.com/pkg/errors"
20)
21
22type ServicesClient struct {
23	client *client.Client
24}
25
26type Service struct {
27	Name     string
28	Endpoint string
29}
30
31type ListServicesInput struct{}
32
33func (c *ServicesClient) List(ctx context.Context, _ *ListServicesInput) ([]*Service, error) {
34	fullPath := path.Join("/", c.client.AccountName, "services")
35	reqInputs := client.RequestInput{
36		Method: http.MethodGet,
37		Path:   fullPath,
38	}
39	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
40	if respReader != nil {
41		defer respReader.Close()
42	}
43	if err != nil {
44		return nil, errors.Wrap(err, "unable to list services")
45	}
46
47	var intermediate map[string]string
48	decoder := json.NewDecoder(respReader)
49	if err = decoder.Decode(&intermediate); err != nil {
50		return nil, errors.Wrap(err, "unable to decode list services response")
51	}
52
53	keys := make([]string, len(intermediate))
54	i := 0
55	for k := range intermediate {
56		keys[i] = k
57		i++
58	}
59	sort.Strings(keys)
60
61	result := make([]*Service, len(intermediate))
62	i = 0
63	for _, key := range keys {
64		result[i] = &Service{
65			Name:     key,
66			Endpoint: intermediate[key],
67		}
68		i++
69	}
70
71	return result, nil
72}
73