From d73a5d53fec0313a51ca933321ea75de7ad0c90e Mon Sep 17 00:00:00 2001 From: Drasko DRASKOVIC Date: Wed, 11 Aug 2021 16:58:10 +0200 Subject: [PATCH] MF 1413 - Use per-service URL in SDK (#1444) * Use per-service URL in SDK Signed-off-by: Drasko DRASKOVIC * Fix CLI Signed-off-by: Drasko Draskovic * Fix CLI messaging Signed-off-by: Drasko Draskovic * Fix message tests Signed-off-by: Drasko Draskovic * Simplify Bootstrap Signed-off-by: Drasko Draskovic * Update API doc and responses Signed-off-by: Drasko Draskovic * fix failing certs, bootstrap tests Signed-off-by: mteodor * fix failing certs, bootstrap tests Signed-off-by: mteodor * Fix tests and rename to auth service Signed-off-by: Drasko Draskovic * Clean the code Signed-off-by: Drasko Draskovic * Remove unnecessary Repository logs Signed-off-by: dusanb94 * Always return error in case of repo failure Signed-off-by: dusanb94 * Cleanup SDK and CLI Update tests, remove linter warnings, remove dead code. Signed-off-by: dusanb94 * Clean the code Signed-off-by: Drasko Draskovic * Undo Bootstrap changes Signed-off-by: Drasko Draskovic * Fix tests Signed-off-by: Drasko Draskovic * Fix linter Signed-off-by: Drasko Draskovic Co-authored-by: mteodor Co-authored-by: dusanb94 --- Makefile | 9 -- bootstrap/api/endpoint_test.go | 71 +++++++------- bootstrap/mocks/users.go | 4 +- bootstrap/postgres/configs.go | 25 ++--- bootstrap/postgres/configs_test.go | 4 +- bootstrap/redis/producer/streams_test.go | 18 ++-- bootstrap/service_test.go | 28 +++--- certs/service.go | 3 +- certs/service_test.go | 26 +++-- cli/config.go | 36 ++----- cli/message.go | 6 +- cli/provision.go | 13 +-- cmd/bootstrap/main.go | 3 +- cmd/certs/main.go | 71 +++++++------- cmd/cli/main.go | 116 ++++++++++++----------- cmd/provision/main.go | 25 ++--- pkg/sdk/go/bootstrap.go | 26 ++--- pkg/sdk/go/certs.go | 3 +- pkg/sdk/go/channels.go | 26 ++--- pkg/sdk/go/channels_test.go | 73 +++++--------- pkg/sdk/go/groups.go | 39 +++----- pkg/sdk/go/message.go | 7 +- pkg/sdk/go/message_test.go | 20 ++-- pkg/sdk/go/sdk.go | 77 ++++++--------- pkg/sdk/go/things.go | 26 ++--- pkg/sdk/go/things_test.go | 104 +++++++------------- pkg/sdk/go/users.go | 15 +-- pkg/sdk/go/users_test.go | 24 ++--- pkg/sdk/go/version.go | 2 +- pkg/sdk/go/version_test.go | 10 +- provision/config.go | 5 +- tools/provision/provision.go | 17 ++-- 32 files changed, 369 insertions(+), 563 deletions(-) diff --git a/Makefile b/Makefile index eab5f326..990d5a2d 100644 --- a/Makefile +++ b/Makefile @@ -102,12 +102,3 @@ rundev: run: docker-compose -f docker/docker-compose.yml up -runlora: - docker-compose \ - -f docker/docker-compose.yml \ - -f docker/addons/influxdb-writer/docker-compose.yml \ - -f docker/addons/lora-adapter/docker-compose.yml up \ - -# Run all Mainflux core services except distributed tracing system - Jaeger. Recommended on gateways: -rungw: - MF_JAEGER_URL= docker-compose -f docker/docker-compose.yml up --scale jaeger=0 diff --git a/bootstrap/api/endpoint_test.go b/bootstrap/api/endpoint_test.go index 199a68ff..2163ee8e 100644 --- a/bootstrap/api/endpoint_test.go +++ b/bootstrap/api/endpoint_test.go @@ -160,7 +160,7 @@ func dec(in []byte) ([]byte, error) { func newService(auth mainflux.AuthServiceClient, url string) bootstrap.Service { things := mocks.NewConfigsRepository() config := mfsdk.Config{ - BaseURL: url, + ThingsURL: url, } sdk := mfsdk.NewSDK(config) @@ -200,10 +200,10 @@ func toJSON(data interface{}) string { } func TestAdd(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) data := toJSON(addReq) @@ -314,6 +314,7 @@ func TestAdd(t *testing.T) { token: tc.auth, body: strings.NewReader(tc.req), } + res, err := req.make() assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) @@ -324,10 +325,10 @@ func TestAdd(t *testing.T) { } func TestView(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) c := newConfig([]bootstrap.Channel{}) @@ -421,13 +422,13 @@ func TestView(t *testing.T) { } func TestUpdate(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) @@ -515,13 +516,13 @@ func TestUpdate(t *testing.T) { } } func TestUpdateCert(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) @@ -610,13 +611,13 @@ func TestUpdateCert(t *testing.T) { } func TestUpdateConnections(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) @@ -723,13 +724,13 @@ func TestList(t *testing.T) { var active, inactive []config list := make([]config, configNum) - users := mocks.NewUsersService(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) path := fmt.Sprintf("%s/%s", bs.URL, "things/configs") - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) for i := 0; i < configNum; i++ { c.ExternalID = strconv.Itoa(i) @@ -971,13 +972,13 @@ func TestList(t *testing.T) { } func TestRemove(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) @@ -1033,13 +1034,13 @@ func TestRemove(t *testing.T) { } func TestBootstrap(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) @@ -1161,13 +1162,13 @@ func TestBootstrap(t *testing.T) { } func TestChangeState(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + auth := mocks.NewAuthClient(map[string]string{validToken: email}) - ts := newThingsServer(newThingsService(users)) - svc := newService(users, ts.URL) + ts := newThingsServer(newThingsService(auth)) + svc := newService(auth, ts.URL) bs := newBootstrapServer(svc) - c := newConfig([]bootstrap.Channel{bootstrap.Channel{ID: "1"}}) + c := newConfig([]bootstrap.Channel{{ID: "1"}}) saved, err := svc.Add(context.Background(), validToken, c) require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) diff --git a/bootstrap/mocks/users.go b/bootstrap/mocks/users.go index beffd7f2..d3730b2c 100644 --- a/bootstrap/mocks/users.go +++ b/bootstrap/mocks/users.go @@ -18,8 +18,8 @@ type serviceMock struct { users map[string]string } -// NewUsersService creates mock of users service. -func NewUsersService(users map[string]string) mainflux.AuthServiceClient { +// NewAuthClient creates mock of users service. +func NewAuthClient(users map[string]string) mainflux.AuthServiceClient { return &serviceMock{users} } diff --git a/bootstrap/postgres/configs.go b/bootstrap/postgres/configs.go index 522ae20b..2081bd25 100644 --- a/bootstrap/postgres/configs.go +++ b/bootstrap/postgres/configs.go @@ -72,25 +72,23 @@ func (cr configRepository) Save(cfg bootstrap.Config, chsConnIDs []string) (stri e = bootstrap.ErrConflict } - cr.rollback("Failed to insert a Config", tx, err) - + cr.rollback("Failed to insert a Config", tx) return "", errors.Wrap(errSaveDB, e) } if err := insertChannels(cfg.Owner, cfg.MFChannels, tx); err != nil { - cr.rollback("Failed to insert Channels", tx, err) - + cr.rollback("Failed to insert Channels", tx) return "", errors.Wrap(errSaveChannels, err) } if err := insertConnections(cfg, chsConnIDs, tx); err != nil { - cr.rollback("Failed to insert connections", tx, err) - + cr.rollback("Failed to insert connections", tx) return "", errors.Wrap(errSaveConnections, err) } if err := tx.Commit(); err != nil { - cr.rollback("Failed to commit Config save", tx, err) + cr.rollback("Failed to commit Config save", tx) + return "", err } return cfg.MFThing, nil @@ -296,8 +294,7 @@ func (cr configRepository) UpdateConnections(owner, id string, channels []bootst } if err := insertChannels(owner, channels, tx); err != nil { - cr.rollback("Failed to insert Channels during the update", tx, err) - + cr.rollback("Failed to insert Channels during the update", tx) return err } @@ -307,13 +304,13 @@ func (cr configRepository) UpdateConnections(owner, id string, channels []bootst return bootstrap.ErrNotFound } } - cr.rollback("Failed to update connections during the update", tx, err) - + cr.rollback("Failed to update connections during the update", tx) return err } if err := tx.Commit(); err != nil { - cr.rollback("Failed to commit Config update", tx, err) + cr.rollback("Failed to commit Config update", tx) + return err } return nil @@ -449,9 +446,7 @@ func (cr configRepository) retrieveAll(owner string, filter bootstrap.Filter) (s return fmt.Sprintf(template, f), params } -func (cr configRepository) rollback(content string, tx *sqlx.Tx, err error) { - cr.log.Error(fmt.Sprintf("%s %s", content, err)) - +func (cr configRepository) rollback(content string, tx *sqlx.Tx) { if err := tx.Rollback(); err != nil { cr.log.Error(fmt.Sprintf("Failed to rollback due to %s", err)) } diff --git a/bootstrap/postgres/configs_test.go b/bootstrap/postgres/configs_test.go index 6fd6b78a..f0785613 100644 --- a/bootstrap/postgres/configs_test.go +++ b/bootstrap/postgres/configs_test.go @@ -26,8 +26,8 @@ var ( ExternalKey: "external-key", Owner: "user@email.com", MFChannels: []bootstrap.Channel{ - bootstrap.Channel{ID: "1", Name: "name 1", Metadata: map[string]interface{}{"meta": 1.0}}, - bootstrap.Channel{ID: "2", Name: "name 2", Metadata: map[string]interface{}{"meta": 2.0}}, + {ID: "1", Name: "name 1", Metadata: map[string]interface{}{"meta": 1.0}}, + {ID: "2", Name: "name 2", Metadata: map[string]interface{}{"meta": 2.0}}, }, Content: "content", State: bootstrap.Inactive, diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index b22454a9..880c4363 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -65,7 +65,7 @@ var ( func newService(auth mainflux.AuthServiceClient, url string) bootstrap.Service { configs := mocks.NewConfigsRepository() config := mfsdk.Config{ - BaseURL: url, + ThingsURL: url, } sdk := mfsdk.NewSDK(config) @@ -92,7 +92,7 @@ func newThingsServer(svc things.Service) *httptest.Server { } func TestAdd(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -161,7 +161,7 @@ func TestAdd(t *testing.T) { } func TestView(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -180,7 +180,7 @@ func TestView(t *testing.T) { func TestUpdate(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) svc = producer.NewEventStoreMiddleware(svc, redisClient) @@ -255,7 +255,7 @@ func TestUpdate(t *testing.T) { func TestUpdateConnections(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) svc = producer.NewEventStoreMiddleware(svc, redisClient) @@ -317,7 +317,7 @@ func TestUpdateConnections(t *testing.T) { } } func TestList(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -338,7 +338,7 @@ func TestList(t *testing.T) { func TestRemove(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) svc = producer.NewEventStoreMiddleware(svc, redisClient) @@ -401,7 +401,7 @@ func TestRemove(t *testing.T) { func TestBootstrap(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) svc = producer.NewEventStoreMiddleware(svc, redisClient) @@ -470,7 +470,7 @@ func TestBootstrap(t *testing.T) { func TestChangeState(t *testing.T) { redisClient.FlushAll(context.Background()).Err() - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) svc = producer.NewEventStoreMiddleware(svc, redisClient) diff --git a/bootstrap/service_test.go b/bootstrap/service_test.go index d365dc8a..a1b0beca 100644 --- a/bootstrap/service_test.go +++ b/bootstrap/service_test.go @@ -57,7 +57,7 @@ var ( func newService(auth mainflux.AuthServiceClient, url string) bootstrap.Service { things := mocks.NewConfigsRepository() config := mfsdk.Config{ - BaseURL: url, + ThingsURL: url, } sdk := mfsdk.NewSDK(config) @@ -99,7 +99,7 @@ func enc(in []byte) ([]byte, error) { } func TestAdd(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -151,7 +151,7 @@ func TestAdd(t *testing.T) { } func TestView(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -192,7 +192,7 @@ func TestView(t *testing.T) { } func TestUpdate(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -244,7 +244,7 @@ func TestUpdate(t *testing.T) { } func TestUpdateCert(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -302,7 +302,7 @@ func TestUpdateCert(t *testing.T) { } func TestUpdateConnections(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -376,7 +376,7 @@ func TestUpdateConnections(t *testing.T) { } func TestList(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -484,7 +484,7 @@ func TestList(t *testing.T) { } func TestRemove(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -531,7 +531,7 @@ func TestRemove(t *testing.T) { } func TestBootstrap(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -592,7 +592,7 @@ func TestBootstrap(t *testing.T) { } func TestChangeState(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -651,7 +651,7 @@ func TestChangeState(t *testing.T) { } func TestUpdateChannelHandler(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -688,7 +688,7 @@ func TestUpdateChannelHandler(t *testing.T) { } func TestRemoveChannelHandler(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -720,7 +720,7 @@ func TestRemoveChannelHandler(t *testing.T) { } func TestRemoveCoinfigHandler(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) @@ -752,7 +752,7 @@ func TestRemoveCoinfigHandler(t *testing.T) { } func TestDisconnectThingsHandler(t *testing.T) { - users := mocks.NewUsersService(map[string]string{validToken: email}) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) svc := newService(users, server.URL) diff --git a/certs/service.go b/certs/service.go index 71a9b07a..9461b02d 100644 --- a/certs/service.go +++ b/certs/service.go @@ -58,8 +58,7 @@ type Config struct { HTTPPort string ServerCert string ServerKey string - BaseURL string - ThingsPrefix string + CertsURL string JaegerURL string AuthURL string AuthTimeout time.Duration diff --git a/certs/service_test.go b/certs/service_test.go index 676eb023..8343c943 100644 --- a/certs/service_test.go +++ b/certs/service_test.go @@ -43,15 +43,14 @@ const ( key = "rsa" certNum = 10 - cfgLogLevel = "error" - cfgClientTLS = false - cfgServerCert = "" - cfgServerKey = "" - cfgBaseURL = "http://localhost" - cfgThingsPrefix = "" - cfgJaegerURL = "" - cfgAuthURL = "localhost:8181" - cfgAuthTimeout = "1s" + cfgLogLevel = "error" + cfgClientTLS = false + cfgServerCert = "" + cfgServerKey = "" + cfgCertsURL = "http://localhost" + cfgJaegerURL = "" + cfgAuthURL = "localhost:8181" + cfgAuthTimeout = "1s" caPath = "../docker/ssl/certs/ca.crt" caKeyPath = "../docker/ssl/certs/ca.key" @@ -60,12 +59,12 @@ const ( ) func newService(tokens map[string]string) (certs.Service, error) { - users := bsmocks.NewUsersService(map[string]string{token: email}) - server := newThingsServer(newThingsService(users)) + ac := bsmocks.NewAuthClient(map[string]string{token: email}) + server := newThingsServer(newThingsService(ac)) auth := thmocks.NewAuthService(tokens) config := mfsdk.Config{ - BaseURL: server.URL, + ThingsURL: server.URL, } sdk := mfsdk.NewSDK(config) @@ -86,8 +85,7 @@ func newService(tokens map[string]string) (certs.Service, error) { ClientTLS: cfgClientTLS, ServerCert: cfgServerCert, ServerKey: cfgServerKey, - BaseURL: cfgBaseURL, - ThingsPrefix: cfgThingsPrefix, + CertsURL: cfgCertsURL, JaegerURL: cfgJaegerURL, AuthURL: cfgAuthURL, SignTLSCert: tlsCert, diff --git a/cli/config.go b/cli/config.go index 41627b7b..300dfa18 100644 --- a/cli/config.go +++ b/cli/config.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "log" "os" - "path" "github.com/mainflux/mainflux/pkg/errors" "github.com/pelletier/go-toml" @@ -44,36 +43,19 @@ func read(file string) (Config, error) { return c, nil } -func getConfigPath() (string, error) { - // Check if a config path passed by user exists. - if ConfigPath != "" { - if _, err := os.Stat(ConfigPath); os.IsNotExist(err) { - errConfigNotFound := errors.Wrap(errors.New("config file was not found"), err) - logError(errConfigNotFound) - return "", err - } - } - - // If not, then read it from the user config directory. - if ConfigPath == "" { - userConfigDir, _ := os.UserConfigDir() - ConfigPath = path.Join(userConfigDir, "mainflux", "cli.toml") - } - - if _, err := os.Stat(ConfigPath); os.IsNotExist(err) { - return "", err - } - - return ConfigPath, nil -} - func ParseConfig() { - path, err := getConfigPath() - if err != nil { + if ConfigPath == "" { + // No config file return } - config, err := read(path) + if _, err := os.Stat(ConfigPath); os.IsNotExist(err) { + errConfigNotFound := errors.Wrap(errors.New("config file was not found"), err) + logError(errConfigNotFound) + return + } + + config, err := read(ConfigPath) if err != nil { log.Fatal(err) } diff --git a/cli/message.go b/cli/message.go index bdc0d77b..413a0c5d 100644 --- a/cli/message.go +++ b/cli/message.go @@ -5,10 +5,8 @@ package cli import "github.com/spf13/cobra" -const contentTypeSenml = "application/senml+json" - var cmdMessages = []cobra.Command{ - cobra.Command{ + { Use: "send", Short: "send [....] ", Long: `Sends message on the channel`, @@ -26,7 +24,7 @@ var cmdMessages = []cobra.Command{ logOK() }, }, - cobra.Command{ + { Use: "read", Short: "read [....] ", Long: `Reads all channel messages`, diff --git a/cli/provision.go b/cli/provision.go index 184c451f..4892f1be 100644 --- a/cli/provision.go +++ b/cli/provision.go @@ -9,21 +9,21 @@ import ( "errors" "fmt" "io" + "math/rand" "os" "path/filepath" + "time" "github.com/docker/docker/pkg/namesgenerator" mfxsdk "github.com/mainflux/mainflux/pkg/sdk/go" "github.com/spf13/cobra" ) -var errMalformedCSV = errors.New("malformed CSV") - const jsonExt = ".json" const csvExt = ".csv" var cmdProvision = []cobra.Command{ - cobra.Command{ + { Use: "things", Short: "things ", Long: `Bulk create things`, @@ -53,7 +53,7 @@ var cmdProvision = []cobra.Command{ logJSON(things) }, }, - cobra.Command{ + { Use: "channels", Short: "channels ", Long: `Bulk create channels`, @@ -78,7 +78,7 @@ var cmdProvision = []cobra.Command{ logJSON(channels) }, }, - cobra.Command{ + { Use: "connect", Short: "connect ", Long: `Bulk connect things to channels`, @@ -101,7 +101,7 @@ var cmdProvision = []cobra.Command{ } }, }, - cobra.Command{ + { Use: "test", Short: "test", Long: `Provisions test setup: one test user, two things and two channels. \ @@ -118,6 +118,7 @@ var cmdProvision = []cobra.Command{ return } + rand.Seed(time.Now().UnixNano()) un := fmt.Sprintf("%s@email.com", namesgenerator.GetRandomName(0)) // Create test user user := mfxsdk.User{ diff --git a/cmd/bootstrap/main.go b/cmd/bootstrap/main.go index 1166d783..2150c5f6 100644 --- a/cmd/bootstrap/main.go +++ b/cmd/bootstrap/main.go @@ -269,8 +269,7 @@ func newService(auth mainflux.AuthServiceClient, db *sqlx.DB, logger mflog.Logge thingsRepo := postgres.NewConfigRepository(db, logger) config := mfsdk.Config{ - BaseURL: cfg.baseURL, - ThingsPrefix: cfg.thingsPrefix, + BootstrapURL: cfg.baseURL, } sdk := mfsdk.NewSDK(config) diff --git a/cmd/certs/main.go b/cmd/certs/main.go index e3cfa6bd..2f3fcb32 100644 --- a/cmd/certs/main.go +++ b/cmd/certs/main.go @@ -53,8 +53,7 @@ const ( defPort = "8204" defServerCert = "" defServerKey = "" - defBaseURL = "http://localhost" - defThingsPrefix = "" + defCertsURL = "http://localhost" defJaegerURL = "" defAuthURL = "localhost:8181" defAuthTimeout = "1s" @@ -85,8 +84,7 @@ const ( envCACerts = "MF_CERTS_CA_CERTS" envServerCert = "MF_CERTS_SERVER_CERT" envServerKey = "MF_CERTS_SERVER_KEY" - envBaseURL = "MF_SDK_BASE_URL" - envThingsPrefix = "MF_SDK_THINGS_PREFIX" + envCertsURL = "MF_SDK_CERTS_URL" envJaegerURL = "MF_JAEGER_URL" envAuthURL = "MF_AUTH_GRPC_URL" envAuthTimeout = "MF_AUTH_GRPC_TIMEOUT" @@ -109,26 +107,24 @@ var ( errPrivateKeyEmpty = errors.New("private key empty") errPrivateKeyUnsupportedType = errors.New("private key unsupported type") errCertsRemove = errors.New("failed to remove certificate") - errCACertificateDoesntExist = errors.New("CA certificate doesnt exist") - errCAKeyDoesntExist = errors.New("CA certificate key doesnt exist") + errCACertificateNotExist = errors.New("CA certificate does not exist") + errCAKeyNotExist = errors.New("CA certificate key does not exist") ) type config struct { - logLevel string - dbConfig postgres.Config - clientTLS bool - encKey []byte - caCerts string - httpPort string - serverCert string - serverKey string - baseURL string - thingsPrefix string - jaegerURL string - authURL string - authTimeout time.Duration - // Sign and issue certificates - // without 3rd party PKI + logLevel string + dbConfig postgres.Config + clientTLS bool + encKey []byte + caCerts string + httpPort string + serverCert string + serverKey string + certsURL string + jaegerURL string + authURL string + authTimeout time.Duration + // Sign and issue certificates without 3rd party PKI signCAPath string signCAKeyPath string signRSABits int @@ -216,18 +212,17 @@ func loadConfig() config { } return config{ - logLevel: mainflux.Env(envLogLevel, defLogLevel), - dbConfig: dbConfig, - clientTLS: tls, - caCerts: mainflux.Env(envCACerts, defCACerts), - httpPort: mainflux.Env(envPort, defPort), - serverCert: mainflux.Env(envServerCert, defServerCert), - serverKey: mainflux.Env(envServerKey, defServerKey), - baseURL: mainflux.Env(envBaseURL, defBaseURL), - thingsPrefix: mainflux.Env(envThingsPrefix, defThingsPrefix), - jaegerURL: mainflux.Env(envJaegerURL, defJaegerURL), - authURL: mainflux.Env(envAuthURL, defAuthURL), - authTimeout: authTimeout, + logLevel: mainflux.Env(envLogLevel, defLogLevel), + dbConfig: dbConfig, + clientTLS: tls, + caCerts: mainflux.Env(envCACerts, defCACerts), + httpPort: mainflux.Env(envPort, defPort), + serverCert: mainflux.Env(envServerCert, defServerCert), + serverKey: mainflux.Env(envServerKey, defServerKey), + certsURL: mainflux.Env(envCertsURL, defCertsURL), + jaegerURL: mainflux.Env(envJaegerURL, defJaegerURL), + authURL: mainflux.Env(envAuthURL, defAuthURL), + authTimeout: authTimeout, signCAKeyPath: mainflux.Env(envSignCAKey, defSignCAKeyPath), signCAPath: mainflux.Env(envSignCAPath, defSignCAPath), @@ -324,8 +319,7 @@ func newService(auth mainflux.AuthServiceClient, db *sqlx.DB, logger mflog.Logge HTTPPort: cfg.httpPort, ServerCert: cfg.serverCert, ServerKey: cfg.serverKey, - BaseURL: cfg.baseURL, - ThingsPrefix: cfg.thingsPrefix, + CertsURL: cfg.certsURL, JaegerURL: cfg.jaegerURL, AuthURL: cfg.authURL, AuthTimeout: cfg.authTimeout, @@ -340,8 +334,7 @@ func newService(auth mainflux.AuthServiceClient, db *sqlx.DB, logger mflog.Logge } config := mfsdk.Config{ - BaseURL: cfg.baseURL, - ThingsPrefix: cfg.thingsPrefix, + CertsURL: cfg.certsURL, } sdk := mfsdk.NewSDK(config) @@ -387,11 +380,11 @@ func loadCertificates(conf config) (tls.Certificate, *x509.Certificate, error) { } if _, err := os.Stat(conf.signCAPath); os.IsNotExist(err) { - return tlsCert, caCert, errCACertificateDoesntExist + return tlsCert, caCert, errCACertificateNotExist } if _, err := os.Stat(conf.signCAKeyPath); os.IsNotExist(err) { - return tlsCert, caCert, errCAKeyDoesntExist + return tlsCert, caCert, errCAKeyNotExist } tlsCert, err := tls.LoadX509KeyPair(conf.signCAPath, conf.signCAKeyPath) diff --git a/cmd/cli/main.go b/cmd/cli/main.go index 2db8af9b..6ca4843f 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -4,6 +4,7 @@ package main import ( + "fmt" "log" "github.com/mainflux/mainflux/cli" @@ -11,21 +12,20 @@ import ( "github.com/spf13/cobra" ) +const defURL string = "http://localhost" + func main() { msgContentType := string(sdk.CTJSONSenML) sdkConf := sdk.Config{ - BaseURL: "http://localhost", - ReaderURL: "http://localhost:8905", - BootstrapURL: "http://localhost:8202", - CertsURL: "http://localhost:8204", - ReaderPrefix: "", - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "http", - BootstrapPrefix: "things", - MsgContentType: sdk.ContentType(msgContentType), - TLSVerification: false, + AuthURL: defURL, + ThingsURL: defURL, + UsersURL: defURL, + ReaderURL: defURL, + HTTPAdapterURL: fmt.Sprintf("%s/http", defURL), + BootstrapURL: defURL, + CertsURL: defURL, + MsgContentType: sdk.ContentType(msgContentType), + TLSVerification: false, } // Root @@ -64,49 +64,57 @@ func main() { // Root Flags rootCmd.PersistentFlags().StringVarP( - &sdkConf.BaseURL, - "mainflux-url", - "m", - sdkConf.BaseURL, - "Mainflux host URL", - ) - - rootCmd.PersistentFlags().StringVarP( - &sdkConf.UsersPrefix, - "users-prefix", - "u", - sdkConf.UsersPrefix, - "Mainflux users service prefix", - ) - - rootCmd.PersistentFlags().StringVarP( - &sdkConf.ThingsPrefix, - "things-prefix", - "t", - sdkConf.ThingsPrefix, - "Mainflux things service prefix", - ) - - rootCmd.PersistentFlags().StringVarP( - &sdkConf.GroupsPrefix, - "groups-prefix", - "g", - sdkConf.GroupsPrefix, - "Mainflux groups service prefix", - ) - - rootCmd.PersistentFlags().StringVarP( - &sdkConf.HTTPAdapterPrefix, - "http-prefix", + &sdkConf.AuthURL, + "auth-url", "a", - sdkConf.HTTPAdapterPrefix, - "Mainflux http adapter prefix", + sdkConf.AuthURL, + "Mainflux Auth URL", + ) + + rootCmd.PersistentFlags().StringVarP( + &sdkConf.BootstrapURL, + "bootstrap-url", + "b", + sdkConf.BootstrapURL, + "Mainflux Bootstrap URL", + ) + + rootCmd.PersistentFlags().StringVarP( + &sdkConf.CertsURL, + "certs-url", + "e", + sdkConf.CertsURL, + "Mainflux Certs URL", + ) + + rootCmd.PersistentFlags().StringVarP( + &sdkConf.ThingsURL, + "things-url", + "t", + sdkConf.ThingsURL, + "Mainflux Things URL", + ) + + rootCmd.PersistentFlags().StringVarP( + &sdkConf.UsersURL, + "users-url", + "u", + sdkConf.UsersURL, + "Mainflux Users URL", + ) + + rootCmd.PersistentFlags().StringVarP( + &sdkConf.HTTPAdapterURL, + "http-url", + "p", + sdkConf.HTTPAdapterURL, + "Mainflux message content type", ) rootCmd.PersistentFlags().StringVarP( &msgContentType, "content-type", - "c", + "y", msgContentType, "Mainflux message content type", ) @@ -119,17 +127,19 @@ func main() { "Do not check for TLS cert", ) - rootCmd.PersistentFlags().StringVar( + rootCmd.PersistentFlags().StringVarP( &cli.ConfigPath, "config", - "", + "c", + cli.ConfigPath, "Mainflux config path", ) - rootCmd.PersistentFlags().BoolVar( + rootCmd.PersistentFlags().BoolVarP( &cli.RawOutput, "raw", - false, + "r", + cli.RawOutput, "Enables raw output mode for easier parsing of output", ) diff --git a/cmd/provision/main.go b/cmd/provision/main.go index c98cc588..d3dfc5ed 100644 --- a/cmd/provision/main.go +++ b/cmd/provision/main.go @@ -25,8 +25,8 @@ const ( defTLS = "false" defServerCert = "" defServerKey = "" - defThingsLocation = "http://localhost" - defUsersLocation = "http://localhost" + defThingsURL = "http://localhost" + defUsersURL = "http://localhost" defHTTPPort = "8190" defMfUser = "test@example.com" defMfPass = "test" @@ -47,8 +47,8 @@ const ( envTLS = "MF_PROVISION_ENV_CLIENTS_TLS" envServerCert = "MF_PROVISION_SERVER_CERT" envServerKey = "MF_PROVISION_SERVER_KEY" - envUsersLocation = "MF_PROVISION_USERS_LOCATION" - envThingsLocation = "MF_PROVISION_THINGS_LOCATION" + envUsersURL = "MF_PROVISION_USERS_LOCATION" + envThingsURL = "MF_PROVISION_THINGS_LOCATION" envMfUser = "MF_PROVISION_USER" envMfPass = "MF_PROVISION_PASS" envMfAPIKey = "MF_PROVISION_API_KEY" @@ -61,6 +61,8 @@ const ( envBSContent = "MF_PROVISION_BS_CONTENT" envCertsHoursValid = "MF_PROVISION_CERTS_HOURS_VALID" envCertsKeyBits = "MF_PROVISION_CERTS_RSA_BITS" + + contentType = "application/json" ) var ( @@ -93,12 +95,11 @@ func main() { } SDKCfg := mfSDK.Config{ - BaseURL: cfg.Server.ThingsLocation, - BootstrapURL: cfg.Server.MfBSURL, - CertsURL: cfg.Server.MfCertsURL, - HTTPAdapterPrefix: "http", - MsgContentType: "application/json", - TLSVerification: cfg.Server.TLS, + ThingsURL: cfg.Server.ThingsURL, + BootstrapURL: cfg.Server.MfBSURL, + CertsURL: cfg.Server.MfCertsURL, + MsgContentType: contentType, + TLSVerification: cfg.Server.TLS, } SDK := mfSDK.NewSDK(SDKCfg) @@ -188,8 +189,8 @@ func loadConfig() (provision.Config, error) { MfUser: mainflux.Env(envMfUser, defMfUser), MfPass: mainflux.Env(envMfPass, defMfPass), MfAPIKey: mainflux.Env(envMfAPIKey, defMfAPIKey), - ThingsLocation: mainflux.Env(envThingsLocation, defThingsLocation), - UsersLocation: mainflux.Env(envUsersLocation, defUsersLocation), + ThingsURL: mainflux.Env(envThingsURL, defThingsURL), + UsersURL: mainflux.Env(envUsersURL, defUsersURL), TLS: tls, }, Certs: provision.Certs{ diff --git a/pkg/sdk/go/bootstrap.go b/pkg/sdk/go/bootstrap.go index 6fd34310..ca8d5c23 100644 --- a/pkg/sdk/go/bootstrap.go +++ b/pkg/sdk/go/bootstrap.go @@ -52,8 +52,7 @@ func (sdk mfSDK) AddBootstrap(token string, cfg BootstrapConfig) (string, error) return "", err } - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, configsEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.bootstrapURL, configsEndpoint) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return "", err @@ -83,9 +82,7 @@ func (sdk mfSDK) Whitelist(token string, cfg BootstrapConfig) error { return ErrFailedWhitelist } - endpoint := fmt.Sprintf("%s/%s", whitelistEndpoint, cfg.MFThing) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, whitelistEndpoint, cfg.MFThing) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { return errors.Wrap(ErrFailedWhitelist, err) @@ -105,9 +102,7 @@ func (sdk mfSDK) Whitelist(token string, cfg BootstrapConfig) error { } func (sdk mfSDK) ViewBootstrap(token, id string) (BootstrapConfig, error) { - endpoint := fmt.Sprintf("%s/%s", configsEndpoint, id) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, id) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return BootstrapConfig{}, err @@ -142,9 +137,7 @@ func (sdk mfSDK) UpdateBootstrap(token string, cfg BootstrapConfig) error { return err } - endpoint := fmt.Sprintf("%s/%s", configsEndpoint, cfg.MFThing) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, cfg.MFThing) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { return err @@ -162,8 +155,7 @@ func (sdk mfSDK) UpdateBootstrap(token string, cfg BootstrapConfig) error { return nil } func (sdk mfSDK) UpdateBootstrapCerts(token, id, clientCert, clientKey, ca string) error { - endpoint := fmt.Sprintf("%s/%s", bootstrapCertsEndpoint, id) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, bootstrapCertsEndpoint, id) request := ConfigUpdateCertReq{ ClientCert: clientCert, ClientKey: clientKey, @@ -192,9 +184,7 @@ func (sdk mfSDK) UpdateBootstrapCerts(token, id, clientCert, clientKey, ca strin } func (sdk mfSDK) RemoveBootstrap(token, id string) error { - endpoint := fmt.Sprintf("%s/%s", configsEndpoint, id) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, configsEndpoint, id) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err @@ -213,9 +203,7 @@ func (sdk mfSDK) RemoveBootstrap(token, id string) error { } func (sdk mfSDK) Bootstrap(externalKey, externalID string) (BootstrapConfig, error) { - endpoint := fmt.Sprintf("%s/%s", bootstrapEndpoint, externalID) - url := createURL(sdk.bootstrapURL, sdk.bootstrapPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.bootstrapURL, bootstrapEndpoint, externalID) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return BootstrapConfig{}, err diff --git a/pkg/sdk/go/certs.go b/pkg/sdk/go/certs.go index 211db208..31bc814d 100644 --- a/pkg/sdk/go/certs.go +++ b/pkg/sdk/go/certs.go @@ -29,7 +29,8 @@ func (sdk mfSDK) IssueCert(thingID string, keyBits int, keyType, valid, token st if err != nil { return Cert{}, err } - url := createURL(sdk.certsURL, sdk.certsPrefix, certsEndpoint) + + url := fmt.Sprintf("%s/%s", sdk.certsURL, certsEndpoint) res, err := request(http.MethodPost, token, url, d) if err != nil { return Cert{}, err diff --git a/pkg/sdk/go/channels.go b/pkg/sdk/go/channels.go index 9b3ec3c9..d027e4f3 100644 --- a/pkg/sdk/go/channels.go +++ b/pkg/sdk/go/channels.go @@ -22,7 +22,7 @@ func (sdk mfSDK) CreateChannel(c Channel, token string) (string, error) { return "", err } - url := createURL(sdk.baseURL, sdk.thingsPrefix, channelsEndpoint) + url := fmt.Sprintf("%s/%s", sdk.thingsURL, channelsEndpoint) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return "", err @@ -47,9 +47,7 @@ func (sdk mfSDK) CreateChannels(chs []Channel, token string) ([]Channel, error) return []Channel{}, err } - endpoint := fmt.Sprintf("%s/%s", channelsEndpoint, "bulk") - url := createURL(sdk.baseURL, sdk.channelsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, "bulk") req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return []Channel{}, err @@ -79,9 +77,7 @@ func (sdk mfSDK) CreateChannels(chs []Channel, token string) ([]Channel, error) } func (sdk mfSDK) Channels(token string, offset, limit uint64, name string) (ChannelsPage, error) { - endpoint := fmt.Sprintf("%s?offset=%d&limit=%d&name=%s", channelsEndpoint, offset, limit, name) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s?offset=%d&limit=%d&name=%s", sdk.thingsURL, channelsEndpoint, offset, limit, name) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return ChannelsPage{}, err @@ -111,9 +107,7 @@ func (sdk mfSDK) Channels(token string, offset, limit uint64, name string) (Chan } func (sdk mfSDK) ChannelsByThing(token, thingID string, offset, limit uint64, disconn bool) (ChannelsPage, error) { - endpoint := fmt.Sprintf("things/%s/channels?offset=%d&limit=%d&disconnected=%t", thingID, offset, limit, disconn) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/things/%s/channels?offset=%d&limit=%d&disconnected=%t", sdk.thingsURL, thingID, offset, limit, disconn) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return ChannelsPage{}, err @@ -143,9 +137,7 @@ func (sdk mfSDK) ChannelsByThing(token, thingID string, offset, limit uint64, di } func (sdk mfSDK) Channel(id, token string) (Channel, error) { - endpoint := fmt.Sprintf("%s/%s", channelsEndpoint, id) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, id) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return Channel{}, err @@ -180,9 +172,7 @@ func (sdk mfSDK) UpdateChannel(c Channel, token string) error { return err } - endpoint := fmt.Sprintf("%s/%s", channelsEndpoint, c.ID) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, c.ID) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { return err @@ -201,9 +191,7 @@ func (sdk mfSDK) UpdateChannel(c Channel, token string) error { } func (sdk mfSDK) DeleteChannel(id, token string) error { - endpoint := fmt.Sprintf("%s/%s", channelsEndpoint, id) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, channelsEndpoint, id) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err diff --git a/pkg/sdk/go/channels_test.go b/pkg/sdk/go/channels_test.go index d0238f66..105ebe7d 100644 --- a/pkg/sdk/go/channels_test.go +++ b/pkg/sdk/go/channels_test.go @@ -25,13 +25,9 @@ func TestCreateChannel(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -86,13 +82,9 @@ func TestCreateChannels(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -153,13 +145,9 @@ func TestChannel(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -209,19 +197,16 @@ func TestChannels(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } var channels []sdk.Channel mainfluxSDK := sdk.NewSDK(sdkConf) for i := 1; i < 101; i++ { ch := sdk.Channel{ID: fmt.Sprintf("%03d", i), Name: "test"} - mainfluxSDK.CreateChannel(ch, token) + _, err := mainfluxSDK.CreateChannel(ch, token) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s", err)) channels = append(channels, ch) } @@ -295,13 +280,9 @@ func TestChannelsByThing(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -432,13 +413,9 @@ func TestUpdateChannel(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -494,13 +471,9 @@ func TestDeleteChannel(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) diff --git a/pkg/sdk/go/groups.go b/pkg/sdk/go/groups.go index 8121cee7..b1df7c55 100644 --- a/pkg/sdk/go/groups.go +++ b/pkg/sdk/go/groups.go @@ -28,8 +28,7 @@ func (sdk mfSDK) CreateGroup(g Group, token string) (string, error) { return "", err } - url := createURL(sdk.baseURL, sdk.groupsPrefix, groupsEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.authURL, groupsEndpoint) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return "", err @@ -50,10 +49,7 @@ func (sdk mfSDK) CreateGroup(g Group, token string) (string, error) { } func (sdk mfSDK) DeleteGroup(id, token string) error { - endpoint := fmt.Sprintf("%s/%s", groupsEndpoint, id) - - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.authURL, groupsEndpoint, id) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err @@ -73,9 +69,7 @@ func (sdk mfSDK) DeleteGroup(id, token string) error { func (sdk mfSDK) Assign(memberIDs []string, memberType, groupID string, token string) error { var ids []string - endpoint := fmt.Sprintf("%s/%s/members", groupsEndpoint, groupID) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s/members", sdk.authURL, groupsEndpoint, groupID) ids = append(ids, memberIDs...) assignReq := assignRequest{ Type: memberType, @@ -106,9 +100,7 @@ func (sdk mfSDK) Assign(memberIDs []string, memberType, groupID string, token st func (sdk mfSDK) Unassign(token, groupID string, memberIDs ...string) error { var ids []string - endpoint := fmt.Sprintf("%s/%s/members", groupsEndpoint, groupID) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s/members", sdk.authURL, groupsEndpoint, groupID) ids = append(ids, memberIDs...) assignReq := assignRequest{ Members: ids, @@ -137,8 +129,7 @@ func (sdk mfSDK) Unassign(token, groupID string, memberIDs ...string) error { } func (sdk mfSDK) Members(groupID, token string, offset, limit uint64) (auth.MemberPage, error) { - endpoint := fmt.Sprintf("%s/%s/members?offset=%d&limit=%d&", groupsEndpoint, groupID, offset, limit) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) + url := fmt.Sprintf("%s, %s/%s/members?offset=%d&limit=%d&", sdk.authURL, groupsEndpoint, groupID, offset, limit) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return auth.MemberPage{}, err @@ -168,20 +159,17 @@ func (sdk mfSDK) Members(groupID, token string, offset, limit uint64) (auth.Memb } func (sdk mfSDK) Groups(offset, limit uint64, token string) (auth.GroupPage, error) { - endpoint := fmt.Sprintf("%s?offset=%d&limit=%d&tree=false", groupsEndpoint, offset, limit) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) + url := fmt.Sprintf("%s/%s?offset=%d&limit=%d&tree=false", sdk.authURL, groupsEndpoint, offset, limit) return sdk.getGroups(token, url) } func (sdk mfSDK) Parents(id string, offset, limit uint64, token string) (auth.GroupPage, error) { - endpoint := fmt.Sprintf("%s/%s/parents?offset=%d&limit=%d&tree=false&level=%d", groupsEndpoint, id, offset, limit, auth.MaxLevel) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s/parents?offset=%d&limit=%d&tree=false&level=%d", sdk.authURL, groupsEndpoint, id, offset, limit, auth.MaxLevel) return sdk.getGroups(token, url) } func (sdk mfSDK) Children(id string, offset, limit uint64, token string) (auth.GroupPage, error) { - endpoint := fmt.Sprintf("%s/%s/children?offset=%d&limit=%d&tree=false&level=%d", groupsEndpoint, id, offset, limit, auth.MaxLevel) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s/children?offset=%d&limit=%d&tree=false&level=%d", sdk.authURL, groupsEndpoint, id, offset, limit, auth.MaxLevel) return sdk.getGroups(token, url) } @@ -214,9 +202,7 @@ func (sdk mfSDK) getGroups(token, url string) (auth.GroupPage, error) { } func (sdk mfSDK) Group(id, token string) (Group, error) { - endpoint := fmt.Sprintf("%s/%s", groupsEndpoint, id) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.authURL, groupsEndpoint, id) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return Group{}, err @@ -251,9 +237,7 @@ func (sdk mfSDK) UpdateGroup(t Group, token string) error { return err } - endpoint := fmt.Sprintf("%s/%s", groupsEndpoint, t.ID) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s", sdk.authURL, groupsEndpoint, t.ID) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { return err @@ -272,8 +256,7 @@ func (sdk mfSDK) UpdateGroup(t Group, token string) error { } func (sdk mfSDK) Memberships(memberID, token string, offset, limit uint64) (GroupsPage, error) { - endpoint := fmt.Sprintf("%s/%s/groups?offset=%d&limit=%d&", membersEndpoint, memberID, offset, limit) - url := createURL(sdk.baseURL, sdk.groupsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s/groups?offset=%d&limit=%d&", sdk.authURL, membersEndpoint, memberID, offset, limit) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return GroupsPage{}, err diff --git a/pkg/sdk/go/message.go b/pkg/sdk/go/message.go index 4223f91d..ef104b65 100644 --- a/pkg/sdk/go/message.go +++ b/pkg/sdk/go/message.go @@ -21,8 +21,7 @@ func (sdk mfSDK) SendMessage(chanName, msg, token string) error { subtopicPart = fmt.Sprintf("/%s", strings.Replace(chanNameParts[1], ".", "/", -1)) } - endpoint := fmt.Sprintf("channels/%s/messages%s", chanID, subtopicPart) - url := createURL(sdk.baseURL, sdk.httpAdapterPrefix, endpoint) + url := fmt.Sprintf("%s/channels/%s/messages%s", sdk.httpAdapterURL, chanID, subtopicPart) req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(msg)) if err != nil { @@ -49,9 +48,7 @@ func (sdk mfSDK) ReadMessages(chanName, token string) (MessagesPage, error) { subtopicPart = fmt.Sprintf("?subtopic=%s", strings.Replace(chanNameParts[1], ".", "/", -1)) } - endpoint := fmt.Sprintf("channels/%s/messages%s", chanID, subtopicPart) - url := createURL(sdk.readerURL, "", endpoint) - + url := fmt.Sprintf("%s/channels/%s/messages%s", sdk.readerURL, chanID, subtopicPart) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return MessagesPage{}, err diff --git a/pkg/sdk/go/message_test.go b/pkg/sdk/go/message_test.go index eeb1690d..10a39368 100644 --- a/pkg/sdk/go/message_test.go +++ b/pkg/sdk/go/message_test.go @@ -38,13 +38,9 @@ func TestSendMessage(t *testing.T) { ts := newMessageServer(pub) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + HTTPAdapterURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -108,13 +104,9 @@ func TestSetContentType(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + HTTPAdapterURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) diff --git a/pkg/sdk/go/sdk.go b/pkg/sdk/go/sdk.go index e54730f2..81e34239 100644 --- a/pkg/sdk/go/sdk.go +++ b/pkg/sdk/go/sdk.go @@ -6,7 +6,6 @@ package sdk import ( "crypto/tls" "errors" - "fmt" "net/http" "github.com/mainflux/mainflux/auth" @@ -23,8 +22,6 @@ const ( CTBinary ContentType = "application/octet-stream" ) -const minPassLen = 8 - var ( // ErrUnauthorized indicates that entity creation failed. ErrUnauthorized = errors.New("unauthorized, missing credentials") @@ -258,52 +255,44 @@ type SDK interface { } type mfSDK struct { - baseURL string - readerURL string - bootstrapURL string - certsURL string - readerPrefix string - usersPrefix string - groupsPrefix string - thingsPrefix string - certsPrefix string - channelsPrefix string - httpAdapterPrefix string - bootstrapPrefix string - msgContentType ContentType - client *http.Client + authURL string + bootstrapURL string + certsURL string + httpAdapterURL string + readerURL string + thingsURL string + usersURL string + + msgContentType ContentType + client *http.Client } // Config contains sdk configuration parameters. type Config struct { - BaseURL string - ReaderURL string - BootstrapURL string - CertsURL string - ReaderPrefix string - UsersPrefix string - GroupsPrefix string - ThingsPrefix string - HTTPAdapterPrefix string - BootstrapPrefix string - MsgContentType ContentType - TLSVerification bool + AuthURL string + BootstrapURL string + CertsURL string + HTTPAdapterURL string + ReaderURL string + ThingsURL string + UsersURL string + + MsgContentType ContentType + TLSVerification bool } // NewSDK returns new mainflux SDK instance. func NewSDK(conf Config) SDK { return &mfSDK{ - baseURL: conf.BaseURL, - readerURL: conf.ReaderURL, - bootstrapURL: conf.BootstrapURL, - certsURL: conf.CertsURL, - readerPrefix: conf.ReaderPrefix, - usersPrefix: conf.UsersPrefix, - groupsPrefix: conf.GroupsPrefix, - thingsPrefix: conf.ThingsPrefix, - httpAdapterPrefix: conf.HTTPAdapterPrefix, - bootstrapPrefix: conf.BootstrapPrefix, - msgContentType: conf.MsgContentType, + authURL: conf.AuthURL, + bootstrapURL: conf.BootstrapURL, + certsURL: conf.CertsURL, + httpAdapterURL: conf.HTTPAdapterURL, + readerURL: conf.ReaderURL, + thingsURL: conf.ThingsURL, + usersURL: conf.UsersURL, + + msgContentType: conf.MsgContentType, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ @@ -325,11 +314,3 @@ func (sdk mfSDK) sendRequest(req *http.Request, token, contentType string) (*htt return sdk.client.Do(req) } - -func createURL(baseURL, prefix, endpoint string) string { - if prefix == "" { - return fmt.Sprintf("%s/%s", baseURL, endpoint) - } - - return fmt.Sprintf("%s/%s/%s", baseURL, prefix, endpoint) -} diff --git a/pkg/sdk/go/things.go b/pkg/sdk/go/things.go index e720fccd..b7f1d16e 100644 --- a/pkg/sdk/go/things.go +++ b/pkg/sdk/go/things.go @@ -23,7 +23,7 @@ func (sdk mfSDK) CreateThing(t Thing, token string) (string, error) { return "", err } - url := createURL(sdk.baseURL, sdk.thingsPrefix, thingsEndpoint) + url := fmt.Sprintf("%s/%s", sdk.thingsURL, thingsEndpoint) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { @@ -50,8 +50,7 @@ func (sdk mfSDK) CreateThings(things []Thing, token string) ([]Thing, error) { return []Thing{}, err } - endpoint := fmt.Sprintf("%s/%s", thingsEndpoint, "bulk") - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, "bulk") req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { @@ -83,7 +82,7 @@ func (sdk mfSDK) CreateThings(things []Thing, token string) ([]Thing, error) { func (sdk mfSDK) Things(token string, offset, limit uint64, name string) (ThingsPage, error) { endpoint := fmt.Sprintf("%s?offset=%d&limit=%d&name=%s", thingsEndpoint, offset, limit, name) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) + url := fmt.Sprintf("%s/%s", sdk.thingsURL, endpoint) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { @@ -114,9 +113,7 @@ func (sdk mfSDK) Things(token string, offset, limit uint64, name string) (Things } func (sdk mfSDK) ThingsByChannel(token, chanID string, offset, limit uint64, disconn bool) (ThingsPage, error) { - endpoint := fmt.Sprintf("channels/%s/things?offset=%d&limit=%d&disconnected=%t", chanID, offset, limit, disconn) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/channels/%s/things?offset=%d&limit=%d&disconnected=%t", sdk.thingsURL, chanID, offset, limit, disconn) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return ThingsPage{}, err @@ -146,8 +143,7 @@ func (sdk mfSDK) ThingsByChannel(token, chanID string, offset, limit uint64, dis } func (sdk mfSDK) Thing(id, token string) (Thing, error) { - endpoint := fmt.Sprintf("%s/%s", thingsEndpoint, id) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, id) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { @@ -183,8 +179,7 @@ func (sdk mfSDK) UpdateThing(t Thing, token string) error { return err } - endpoint := fmt.Sprintf("%s/%s", thingsEndpoint, t.ID) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, t.ID) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { @@ -204,8 +199,7 @@ func (sdk mfSDK) UpdateThing(t Thing, token string) error { } func (sdk mfSDK) DeleteThing(id, token string) error { - endpoint := fmt.Sprintf("%s/%s", thingsEndpoint, id) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) + url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, id) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { @@ -230,7 +224,7 @@ func (sdk mfSDK) Connect(connIDs ConnectionIDs, token string) error { return err } - url := createURL(sdk.baseURL, sdk.thingsPrefix, connectEndpoint) + url := fmt.Sprintf("%s/%s", sdk.thingsURL, connectEndpoint) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return err @@ -249,9 +243,7 @@ func (sdk mfSDK) Connect(connIDs ConnectionIDs, token string) error { } func (sdk mfSDK) DisconnectThing(thingID, chanID, token string) error { - endpoint := fmt.Sprintf("%s/%s/%s/%s", channelsEndpoint, chanID, thingsEndpoint, thingID) - url := createURL(sdk.baseURL, sdk.thingsPrefix, endpoint) - + url := fmt.Sprintf("%s/%s/%s/%s/%s", sdk.thingsURL, channelsEndpoint, chanID, thingsEndpoint, thingID) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err diff --git a/pkg/sdk/go/things_test.go b/pkg/sdk/go/things_test.go index 239f3cf3..4af920f0 100644 --- a/pkg/sdk/go/things_test.go +++ b/pkg/sdk/go/things_test.go @@ -62,13 +62,9 @@ func TestCreateThing(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -123,13 +119,9 @@ func TestCreateThings(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -191,13 +183,9 @@ func TestThing(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -248,21 +236,17 @@ func TestThings(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } var things []sdk.Thing mainfluxSDK := sdk.NewSDK(sdkConf) for i := 1; i < 101; i++ { - th := sdk.Thing{ID: fmt.Sprintf("%03d", i), Name: "test_device", Metadata: metadata} - mainfluxSDK.CreateThing(th, token) + _, err := mainfluxSDK.CreateThing(th, token) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s", err)) th.Key = fmt.Sprintf("%s%012d", keyPrefix, 2*i) things = append(things, th) } @@ -337,13 +321,9 @@ func TestThingsByChannel(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -477,13 +457,9 @@ func TestUpdateThing(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -560,13 +536,9 @@ func TestDeleteThing(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -632,13 +604,9 @@ func TestConnectThing(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -737,13 +705,9 @@ func TestConnect(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -843,13 +807,9 @@ func TestDisconnectThing(t *testing.T) { ts := newThingsServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) diff --git a/pkg/sdk/go/users.go b/pkg/sdk/go/users.go index a8601711..6ccfc688 100644 --- a/pkg/sdk/go/users.go +++ b/pkg/sdk/go/users.go @@ -27,8 +27,7 @@ func (sdk mfSDK) CreateUser(u User) (string, error) { return "", err } - url := createURL(sdk.baseURL, sdk.usersPrefix, usersEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.usersURL, usersEndpoint) resp, err := sdk.client.Post(url, string(CTJSON), bytes.NewReader(data)) if err != nil { return "", err @@ -43,8 +42,7 @@ func (sdk mfSDK) CreateUser(u User) (string, error) { } func (sdk mfSDK) User(token string) (User, error) { - url := createURL(sdk.baseURL, sdk.usersPrefix, usersEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.usersURL, usersEndpoint) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return User{}, err @@ -79,8 +77,7 @@ func (sdk mfSDK) CreateToken(user User) (string, error) { return "", err } - url := createURL(sdk.baseURL, sdk.usersPrefix, tokensEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.usersURL, tokensEndpoint) resp, err := sdk.client.Post(url, string(CTJSON), bytes.NewReader(data)) if err != nil { return "", err @@ -110,8 +107,7 @@ func (sdk mfSDK) UpdateUser(u User, token string) error { return err } - url := createURL(sdk.baseURL, sdk.usersPrefix, usersEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.usersURL, usersEndpoint) req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data)) if err != nil { return err @@ -139,8 +135,7 @@ func (sdk mfSDK) UpdatePassword(oldPass, newPass, token string) error { return err } - url := createURL(sdk.baseURL, sdk.usersPrefix, passwordEndpoint) - + url := fmt.Sprintf("%s/%s", sdk.usersURL, passwordEndpoint) req, err := http.NewRequest(http.MethodPatch, url, bytes.NewReader(data)) if err != nil { return err diff --git a/pkg/sdk/go/users_test.go b/pkg/sdk/go/users_test.go index c18821e3..e7688783 100644 --- a/pkg/sdk/go/users_test.go +++ b/pkg/sdk/go/users_test.go @@ -19,6 +19,7 @@ import ( "github.com/mainflux/mainflux/users/mocks" "github.com/opentracing/opentracing-go/mocktracer" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -49,13 +50,9 @@ func TestCreateUser(t *testing.T) { ts := newUserServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + UsersURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -113,13 +110,9 @@ func TestCreateToken(t *testing.T) { ts := newUserServer(svc) defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + UsersURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) @@ -127,7 +120,8 @@ func TestCreateToken(t *testing.T) { auth := mocks.NewAuthService(map[string]string{user.Email: user.Email}) tkn, _ := auth.Issue(context.Background(), &mainflux.IssueReq{Id: user.ID, Email: user.Email, Type: 0}) token := tkn.GetValue() - mainfluxSDK.CreateUser(user) + _, err := mainfluxSDK.CreateUser(user) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s", err)) cases := []struct { desc string user sdk.User diff --git a/pkg/sdk/go/version.go b/pkg/sdk/go/version.go index 219f0f17..fcf1c3d4 100644 --- a/pkg/sdk/go/version.go +++ b/pkg/sdk/go/version.go @@ -17,7 +17,7 @@ type version struct { } func (sdk mfSDK) Version() (string, error) { - url := fmt.Sprintf("%s/version", sdk.baseURL) + url := fmt.Sprintf("%s/version", sdk.thingsURL) resp, err := sdk.client.Get(url) if err != nil { diff --git a/pkg/sdk/go/version_test.go b/pkg/sdk/go/version_test.go index 97923b5b..87886593 100644 --- a/pkg/sdk/go/version_test.go +++ b/pkg/sdk/go/version_test.go @@ -14,13 +14,9 @@ func TestVersion(t *testing.T) { defer ts.Close() sdkConf := sdk.Config{ - BaseURL: ts.URL, - UsersPrefix: "", - GroupsPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "", - MsgContentType: contentType, - TLSVerification: false, + ThingsURL: ts.URL, + MsgContentType: contentType, + TLSVerification: false, } mainfluxSDK := sdk.NewSDK(sdkConf) diff --git a/provision/config.go b/provision/config.go index b42fabe0..ab1a53e5 100644 --- a/provision/config.go +++ b/provision/config.go @@ -18,9 +18,8 @@ type ServiceConf struct { TLS bool `toml:"tls"` ServerCert string `toml:"server_cert"` ServerKey string `toml:"server_key"` - ThingsLocation string `toml:"things_location"` - UsersLocation string `toml:"users_location"` - MQTTURL string `toml:"mqtt_url"` + ThingsURL string `toml:"things_url"` + UsersURL string `toml:"users_url"` HTTPPort string `toml:"http_port"` MfUser string `toml:"mf_user"` MfPass string `toml:"mf_pass"` diff --git a/tools/provision/provision.go b/tools/provision/provision.go index 0f4641ba..efcce41c 100644 --- a/tools/provision/provision.go +++ b/tools/provision/provision.go @@ -24,7 +24,10 @@ import ( sdk "github.com/mainflux/mainflux/pkg/sdk/go" ) -const defPass = "12345678" +const ( + defPass = "12345678" + defReaderURL = "http://localhost:8905" +) // MfConn - structure describing Mainflux connection set type MfConn struct { @@ -56,14 +59,10 @@ func Provision(conf Config) { msgContentType := string(sdk.CTJSONSenML) sdkConf := sdk.Config{ - BaseURL: conf.Host, - ReaderURL: "http://localhost:8905", - ReaderPrefix: "", - UsersPrefix: "", - ThingsPrefix: "", - HTTPAdapterPrefix: "http", - MsgContentType: sdk.ContentType(msgContentType), - TLSVerification: false, + ThingsURL: conf.Host, + ReaderURL: defReaderURL, + MsgContentType: sdk.ContentType(msgContentType), + TLSVerification: false, } s := sdk.NewSDK(sdkConf)