mirror of
https://github.com/mainflux/mainflux.git
synced 2025-04-29 13:49:28 +08:00

* MF-354 - Add Go SDK This PR adds Go SDK. It also refactors `cli` to use new SDK. Signed-off-by: drasko <drasko.draskovic@gmail.com> * Use http consts. Add doc. Signed-off-by: drasko <drasko.draskovic@gmail.com> * Insline const Signed-off-by: drasko <drasko.draskovic@gmail.com> * Add initial SDK tests Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix SDK to return values (not HTTP rsp) Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix CLI and test Signed-off-by: drasko <drasko.draskovic@gmail.com> * fix typos, add header Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix doc Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix doc, add comment Signed-off-by: drasko <drasko.draskovic@gmail.com> * Inline error checks Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix typos Signed-off-by: drasko <drasko.draskovic@gmail.com> * Inline errs Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix typo Signed-off-by: drasko <drasko.draskovic@gmail.com> * Change fnc parameter name Signed-off-by: drasko <drasko.draskovic@gmail.com> * Rename getters to Go standard Signed-off-by: drasko <drasko.draskovic@gmail.com> * Use struct and interface Signed-off-by: drasko <drasko.draskovic@gmail.com> * Simplify sdk struct Signed-off-by: drasko <drasko.draskovic@gmail.com> * Fix README Signed-off-by: drasko <drasko.draskovic@gmail.com>
62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
//
|
|
// Copyright (c) 2018
|
|
// Mainflux
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
|
|
package sdk
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// CreateUser - create user
|
|
func (sdk *MfxSDK) CreateUser(user, pwd string) error {
|
|
msg := fmt.Sprintf(`{"email": "%s", "password": "%s"}`, user, pwd)
|
|
url := fmt.Sprintf("%s/users", sdk.url)
|
|
|
|
resp, err := sdk.httpClient.Post(url, contentTypeJSON, strings.NewReader(msg))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusCreated {
|
|
return fmt.Errorf("%d", resp.StatusCode)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// CreateToken - create user token
|
|
func (sdk *MfxSDK) CreateToken(user, pwd string) (string, error) {
|
|
msg := fmt.Sprintf(`{"email": "%s", "password": "%s"}`, user, pwd)
|
|
url := fmt.Sprintf("%s/tokens", sdk.url)
|
|
|
|
resp, err := sdk.httpClient.Post(url, contentTypeJSON, strings.NewReader(msg))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusCreated {
|
|
return "", fmt.Errorf("%d", resp.StatusCode)
|
|
}
|
|
|
|
var t tokenRes
|
|
if err := json.Unmarshal(body, &t); err != nil {
|
|
return "", err
|
|
}
|
|
return t.Token, nil
|
|
}
|