Skip to content

Commit

Permalink
Initial commit (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
sharadregoti authored Apr 29, 2021
1 parent 2acb3df commit ca55d30
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
7 changes: 7 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ func New(project, url string, sslEnabled bool) *API {
return &API{config: c, socket: w, realtime: r}
}

// Ping check if connection is established with space cloud
func (api *API) Ping() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return api.config.Transport.Ping(ctx, api.config.Token)
}

// SetToken sets the JWT token to be used in each request
func (api *API) SetToken(token string) {
api.config.Token = token
Expand Down
48 changes: 48 additions & 0 deletions transport/ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package transport

import (
"context"
"encoding/json"
"fmt"
"net/http"

"github.com/spaceuptech/space-api-go/types"
"github.com/spaceuptech/space-api-go/utils"
)

// Call triggers the gRPC call function on space cloud
func (t *Transport) Ping(ctx context.Context, token string) error {
scheme := "http"
if t.sslEnabled {
scheme = "https"
}

// Make a http request
r, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s://%s/v1/config/env", scheme, t.addr), nil)
if err != nil {
return err
}

// Add appropriate headers
r.Header.Add("Authorization", "Bearer "+token)
r.Header.Add("Content-Type", contentTypeJSON)

// Fire the request
res, err := t.httpClient.Do(r)
if err != nil {
return err
}
defer utils.CloseTheCloser(res.Body)

if res.StatusCode >= 200 && res.StatusCode < 300 {
return nil
}

// Unmarshal the response
result := types.M{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
return err
}

return fmt.Errorf("Service responde with status code (%v) with error message - (%v) ", res.StatusCode, result["error"].(string))
}

0 comments on commit ca55d30

Please sign in to comment.