diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index a9210ffe..aab957ec 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -10,16 +10,17 @@ jobs: name: lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - name: Checkout + uses: actions/checkout@v7 + - name: Set up Go + uses: actions/setup-go@v7 with: - go-version: ^1.23 + go-version-file: go.mod - name: golangci-lint - uses: golangci/golangci-lint-action@v2 + uses: golangci/golangci-lint-action@v9 with: version: latest - skip-go-installation: true args: "--build-tags server --timeout=10m --max-same-issues 20" # Optional: show only new issues if it's a pull request. The default value is `false`. # only-new-issues: true diff --git a/.github/workflows/publish_container_images.yaml b/.github/workflows/publish_container_images.yaml index f8a482a0..889619bd 100644 --- a/.github/workflows/publish_container_images.yaml +++ b/.github/workflows/publish_container_images.yaml @@ -15,25 +15,25 @@ jobs: steps: - name: backend repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v7 with: - go-version: ^1.23 + go-version-file: go.mod - # - uses: docker/setup-qemu-action@v1 - - uses: docker/setup-buildx-action@v1 - - uses: actions/setup-node@v2 + # - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v4 + - uses: actions/setup-node@v7 with: - node-version: "18" + node-version: "22" - name: Login in to docker registry - uses: docker/login-action@v1 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_TOKEN }} - name: Login in to quay.io registry - uses: docker/login-action@v1 + uses: docker/login-action@v4 with: registry: quay.io username: ${{ secrets.QUAY_USERNAME }} @@ -43,7 +43,7 @@ jobs: run: ./scripts/setup_web_console.sh - name: Cache node modules - uses: actions/cache@v4 + uses: actions/cache@v6 env: cache-name: cache-node-modules with: @@ -57,7 +57,7 @@ jobs: TX_TOKEN: '${{ secrets.TRANSIFEX_TOKEN_MC_V2 }}' - name: Cache go modules - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} diff --git a/.github/workflows/publish_executables.yaml b/.github/workflows/publish_executables.yaml index 66ba8705..55b17606 100644 --- a/.github/workflows/publish_executables.yaml +++ b/.github/workflows/publish_executables.yaml @@ -11,21 +11,21 @@ jobs: steps: - name: checkout backend repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v7 with: - go-version: ^1.23 + go-version-file: go.mod - - uses: actions/setup-node@v2 + - uses: actions/setup-node@v7 with: - node-version: "18" + node-version: "22" - name: setup web console repository run: ./scripts/setup_web_console.sh - name: cache node modules - uses: actions/cache@v4 + uses: actions/cache@v6 env: cache-name: cache-node-modules with: @@ -39,7 +39,7 @@ jobs: TX_TOKEN: '${{ secrets.TRANSIFEX_TOKEN_MC_V2 }}' - name: Cache go modules - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} @@ -58,7 +58,7 @@ jobs: sha256sum *.zip >> ./SHA256SUMS.txt - name: Update release notes and executables - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v3 if: startsWith(github.ref, 'refs/tags/') # executes only for new release env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} diff --git a/cmd/client/command/delete/cmd.go b/cmd/client/command/delete/cmd.go index 1e826233..2a666adb 100644 --- a/cmd/client/command/delete/cmd.go +++ b/cmd/client/command/delete/cmd.go @@ -22,8 +22,8 @@ var deleteCmd = &cobra.Command{ func printStatus(err error) { if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } - fmt.Fprintln(rootCmd.IOStreams.Out, "Deleted successfully") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "Deleted successfully") } diff --git a/cmd/client/command/disable/cmd.go b/cmd/client/command/disable/cmd.go index 147b3f2f..22d4ad2a 100644 --- a/cmd/client/command/disable/cmd.go +++ b/cmd/client/command/disable/cmd.go @@ -22,8 +22,8 @@ var disableCmd = &cobra.Command{ func printStatus(err error) { if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } - fmt.Fprintln(rootCmd.IOStreams.Out, "Disabled successfully") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "Disabled successfully") } diff --git a/cmd/client/command/enable/cmd.go b/cmd/client/command/enable/cmd.go index c95aa8fb..92e3672a 100644 --- a/cmd/client/command/enable/cmd.go +++ b/cmd/client/command/enable/cmd.go @@ -22,8 +22,8 @@ var enableCmd = &cobra.Command{ func printStatus(err error) { if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } - fmt.Fprintln(rootCmd.IOStreams.Out, "Enabled successfully") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "Enabled successfully") } diff --git a/cmd/client/command/get/cmd.go b/cmd/client/command/get/cmd.go index 496daf1d..a678a7c7 100644 --- a/cmd/client/command/get/cmd.go +++ b/cmd/client/command/get/cmd.go @@ -112,23 +112,23 @@ func getQueryParams(headers []printer.Header) (map[string]interface{}, error) { func executeGetCmd(headers []printer.Header, listFunc ListFunc, dataType interface{}) { queryParams, err := getQueryParams(headers) if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } result, err := listFunc(queryParams) if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } res, ok := result.Data.([]interface{}) if !ok { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "invalid response type:%T\n", result.Data) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "invalid response type:%T\n", result.Data) return } if len(res) == 0 { - fmt.Fprintln(rootCmd.IOStreams.Out, "No resource found") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "No resource found") return } @@ -141,7 +141,7 @@ func executeGetCmd(headers []printer.Header, listFunc ListFunc, dataType interfa item := reflect.New(reflect.TypeOf(dataType)).Interface() err = utils.MapToStruct(utils.TagNameJSON, data, item) if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error on map to struct. %s", err.Error()) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error on map to struct. %s", err.Error()) continue } diff --git a/cmd/client/command/reboot/reboot_cmd.go b/cmd/client/command/reboot/reboot_cmd.go index c98dd0aa..ed8a15c5 100644 --- a/cmd/client/command/reboot/reboot_cmd.go +++ b/cmd/client/command/reboot/reboot_cmd.go @@ -24,9 +24,9 @@ var nodeRebootCmd = &cobra.Command{ client := rootCmd.GetClient() err := client.ExecuteNodeAction(nodeTY.ActionReboot, args) if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } - fmt.Fprintln(rootCmd.IOStreams.Out, "Nodes reboot command supplied") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "Nodes reboot command supplied") }, } diff --git a/cmd/client/command/reload/cmd.go b/cmd/client/command/reload/cmd.go index df0890cd..9462487b 100644 --- a/cmd/client/command/reload/cmd.go +++ b/cmd/client/command/reload/cmd.go @@ -22,8 +22,8 @@ var reloadCmd = &cobra.Command{ func printStatus(err error) { if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s\n", err) return } - fmt.Fprintln(rootCmd.IOStreams.Out, "Reloaded successfully") + _, _ = fmt.Fprintln(rootCmd.IOStreams.Out, "Reloaded successfully") } diff --git a/cmd/client/command/root/cmd.go b/cmd/client/command/root/cmd.go index 738da24c..db93b716 100644 --- a/cmd/client/command/root/cmd.go +++ b/cmd/client/command/root/cmd.go @@ -68,7 +68,7 @@ func UpdateStreams(cmd *cobra.Command) { func Execute(streams clientTY.IOStreams) { IOStreams = streams if err := Cmd.Execute(); err != nil { - fmt.Fprintln(IOStreams.ErrOut, err) + _, _ = fmt.Fprintln(IOStreams.ErrOut, err) os.Exit(1) } } @@ -85,11 +85,11 @@ func WriteConfigFile() { configBytes, err := yaml.Marshal(CONFIG) if err != nil { - fmt.Fprintf(IOStreams.ErrOut, "error on config file marshal. error:[%s]\n", err.Error()) + _, _ = fmt.Fprintf(IOStreams.ErrOut, "error on config file marshal. error:[%s]\n", err.Error()) } err = os.WriteFile(cfgFile, configBytes, os.ModePerm) if err != nil { - fmt.Fprintf(IOStreams.ErrOut, "error on writing config file to disk, filename:%s, error:[%s]\n", cfgFile, err.Error()) + _, _ = fmt.Fprintf(IOStreams.ErrOut, "error on writing config file to disk, filename:%s, error:[%s]\n", cfgFile, err.Error()) } } @@ -117,7 +117,7 @@ func initConfig() { if err := viper.ReadInConfig(); err == nil { err = viper.Unmarshal(&CONFIG) if err != nil { - fmt.Fprint(IOStreams.ErrOut, "error on unmarshal of config\n", err) + _, _ = fmt.Fprint(IOStreams.ErrOut, "error on unmarshal of config\n", err) } } } diff --git a/cmd/client/command/root/login.go b/cmd/client/command/root/login.go index cad4d162..7734aed3 100644 --- a/cmd/client/command/root/login.go +++ b/cmd/client/command/root/login.go @@ -57,7 +57,7 @@ var loginCmd = &cobra.Command{ if loginUsername == "" { _username, err := promptUsername() if err != nil { - fmt.Fprintln(IOStreams.ErrOut, err.Error()) + _, _ = fmt.Fprintln(IOStreams.ErrOut, err.Error()) return } loginUsername = _username @@ -67,7 +67,7 @@ var loginCmd = &cobra.Command{ if loginPassword == "" { _password, err := promptPassword() if err != nil { - fmt.Fprintln(IOStreams.ErrOut, err.Error()) + _, _ = fmt.Fprintln(IOStreams.ErrOut, err.Error()) return } loginPassword = _password @@ -79,11 +79,11 @@ var loginCmd = &cobra.Command{ client := GetClient() res, err := client.Login(loginUsername, loginPassword, loginToken, loginExpiresIn) if err != nil { - fmt.Fprintln(IOStreams.ErrOut, "error on login", err) + _, _ = fmt.Fprintln(IOStreams.ErrOut, "error on login", err) return } if res != nil { - fmt.Fprintln(IOStreams.ErrOut, "Login successful.") + _, _ = fmt.Fprintln(IOStreams.ErrOut, "Login successful.") CONFIG.URL = args[0] CONFIG.Username = loginUsername CONFIG.Password = res.Token @@ -102,14 +102,14 @@ var logoutCmd = &cobra.Command{ mc logout`, Run: func(cmd *cobra.Command, args []string) { if CONFIG.URL == "" { - fmt.Fprintln(IOStreams.ErrOut, "There is no connection information.") + _, _ = fmt.Fprintln(IOStreams.ErrOut, "There is no connection information.") return } CONFIG.URL = "" CONFIG.Username = "" CONFIG.Password = "" CONFIG.Insecure = false - fmt.Fprintln(IOStreams.Out, "Logout successful.") + _, _ = fmt.Fprintln(IOStreams.Out, "Logout successful.") WriteConfigFile() }, } @@ -125,10 +125,10 @@ func promptUsername() (string, error) { } func promptPassword() (string, error) { - fmt.Fprint(IOStreams.Out, "Password: ") + _, _ = fmt.Fprint(IOStreams.Out, "Password: ") // TODO: should use IOStreams.In in the place of os.Stdin.Fd pw, err := term.ReadPassword(int(os.Stdin.Fd())) - fmt.Fprintln(IOStreams.Out) + _, _ = fmt.Fprintln(IOStreams.Out) if err != nil { return "", err } diff --git a/cmd/client/command/set/cmd.go b/cmd/client/command/set/cmd.go index 468a791a..0e154610 100644 --- a/cmd/client/command/set/cmd.go +++ b/cmd/client/command/set/cmd.go @@ -45,6 +45,6 @@ func executeSetCmd(quickIdPrefix, keyPath string, resources []string, payload st } err := client.ExecuteAction(actions) if err != nil { - fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s", err.Error()) + _, _ = fmt.Fprintf(rootCmd.IOStreams.ErrOut, "error:%s", err.Error()) } } diff --git a/docker/gateway.Dockerfile b/docker/gateway.Dockerfile index 6f8f9a12..16490e65 100644 --- a/docker/gateway.Dockerfile +++ b/docker/gateway.Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=${BUILDPLATFORM} golang:1.23-alpine3.21 AS builder +FROM --platform=${BUILDPLATFORM} golang:1.26-alpine3.24 AS builder RUN mkdir /app ADD . /app WORKDIR /app @@ -14,7 +14,7 @@ ARG TARGETARCH ENV TARGET_BUILD="gateway" RUN scripts/container_binary.sh -FROM alpine:3.21 +FROM alpine:3.24 LABEL maintainer="Jeeva Kandasamy " diff --git a/docker/handler.Dockerfile b/docker/handler.Dockerfile index fe5656cc..76bb719a 100644 --- a/docker/handler.Dockerfile +++ b/docker/handler.Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=${BUILDPLATFORM} golang:1.23-alpine3.21 AS builder +FROM --platform=${BUILDPLATFORM} golang:1.26-alpine3.24 AS builder RUN mkdir /app ADD . /app WORKDIR /app @@ -14,7 +14,7 @@ ARG TARGETARCH ENV TARGET_BUILD="handler" RUN scripts/container_binary.sh -FROM alpine:3.21 +FROM alpine:3.24 LABEL maintainer="Jeeva Kandasamy " diff --git a/docker/server.Dockerfile b/docker/server.Dockerfile index 33549234..a07db47e 100644 --- a/docker/server.Dockerfile +++ b/docker/server.Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.23-alpine3.21 AS builder +FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.26-alpine3.24 AS builder RUN mkdir /app ADD . /app WORKDIR /app @@ -14,7 +14,7 @@ ARG TARGETARCH ENV TARGET_BUILD="server" RUN scripts/container_binary.sh -FROM alpine:3.21 +FROM alpine:3.24 LABEL maintainer="Jeeva Kandasamy " diff --git a/go.mod b/go.mod index 487345d2..a34000d6 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,6 @@ module github.com/mycontroller-org/server/v2 -go 1.23.0 - -toolchain go1.23.7 +go 1.26.2 require ( github.com/Masterminds/semver/v3 v3.2.1 diff --git a/pkg/api/backup/api.go b/pkg/api/backup/api.go index e03fbed7..97779f86 100644 --- a/pkg/api/backup/api.go +++ b/pkg/api/backup/api.go @@ -9,7 +9,6 @@ import ( "github.com/mycontroller-org/server/v2/pkg/utils" filterUtils "github.com/mycontroller-org/server/v2/pkg/utils/filter_sort" busTY "github.com/mycontroller-org/server/v2/plugin/bus/types" - backupRestore "github.com/mycontroller-org/server/v2/plugin/database/storage/backup" backupTY "github.com/mycontroller-org/server/v2/plugin/database/storage/backup" storageTY "github.com/mycontroller-org/server/v2/plugin/database/storage/types" "go.uber.org/zap" @@ -18,12 +17,12 @@ import ( type BackupAPI struct { ctx context.Context logger *zap.Logger - backupRestore *backupRestore.BackupRestore + backupRestore *backupTY.BackupRestore bus busTY.Plugin settingsAPI *settings.SettingsAPI } -func New(ctx context.Context, logger *zap.Logger, backupRestore *backupRestore.BackupRestore, storage storageTY.Plugin, bus busTY.Plugin, enc *encryptionAPI.Encryption) *BackupAPI { +func New(ctx context.Context, logger *zap.Logger, backupRestore *backupTY.BackupRestore, storage storageTY.Plugin, bus busTY.Plugin, enc *encryptionAPI.Encryption) *BackupAPI { return &BackupAPI{ ctx: ctx, logger: logger.Named("backup_api"), diff --git a/pkg/api/firmware/api.go b/pkg/api/firmware/api.go index fdd111e2..99daf963 100644 --- a/pkg/api/firmware/api.go +++ b/pkg/api/firmware/api.go @@ -166,7 +166,7 @@ func (fw *FirmwareAPI) Upload(sourceFile multipart.File, id, filename string) er if err != nil { return err } - defer savedFile.Close() + defer func() { _ = savedFile.Close() }() hash := sha256.New() if _, err := io.Copy(hash, savedFile); err != nil { diff --git a/pkg/api/settings/update_geo_location.go b/pkg/api/settings/update_geo_location.go index a8dcd3c5..add27aff 100644 --- a/pkg/api/settings/update_geo_location.go +++ b/pkg/api/settings/update_geo_location.go @@ -32,7 +32,7 @@ type GeoLocationAPIResponse struct { func (s *SettingsAPI) GetLocation() (*GeoLocationAPIResponse, error) { response, err := http.Get(geoLocationURL) if response != nil { - defer response.Body.Close() + defer func() { _ = response.Body.Close() }() } if err != nil { return nil, err diff --git a/pkg/backup/backup_map.go b/pkg/backup/backup_map.go index e2909dcb..5b603cc4 100644 --- a/pkg/backup/backup_map.go +++ b/pkg/backup/backup_map.go @@ -8,7 +8,6 @@ import ( types "github.com/mycontroller-org/server/v2/pkg/types" "github.com/mycontroller-org/server/v2/pkg/types/config" userTY "github.com/mycontroller-org/server/v2/pkg/types/user" - backupPlugin "github.com/mycontroller-org/server/v2/plugin/database/storage/backup" backupTY "github.com/mycontroller-org/server/v2/plugin/database/storage/backup" "go.uber.org/zap" ) @@ -74,7 +73,7 @@ func GetDirectories(includeSecureShare, includeInsecureShare bool) (map[string]s } // verify MyControllerDataTransformationExportFunc, implements DataTransformerFunc -var _ backupPlugin.DataTransformerFunc = MyControllerDataTransformationExportFunc +var _ backupTY.DataTransformerFunc = MyControllerDataTransformationExportFunc func MyControllerDataTransformationExportFunc(logger *zap.Logger, entityName string, data interface{}, storageExportType string) (interface{}, error) { diff --git a/pkg/command/command.go b/pkg/command/command.go index 992696dc..cbc5107e 100644 --- a/pkg/command/command.go +++ b/pkg/command/command.go @@ -87,7 +87,7 @@ func (c *Command) Stop() error { c.mutex.Lock() defer c.mutex.Unlock() if !c.isRunning { - return errors.New("This command is not started") + return errors.New("this command is not started") } c.stopCh <- true return nil diff --git a/pkg/http_router/middleware/auth.go b/pkg/http_router/middleware/auth.go index 2e5b8cc8..ae488123 100644 --- a/pkg/http_router/middleware/auth.go +++ b/pkg/http_router/middleware/auth.go @@ -79,7 +79,7 @@ func MiddlewareAuthenticationVerification(next http.Handler) http.Handler { } } // authentication required - if err, mcApiContext := IsValidToken(r); err == nil { + if mcApiContext, err := IsValidToken(r); err == nil { // include user details as context ctx := context.WithValue(r.Context(), contextKey, mcApiContext) @@ -100,19 +100,19 @@ func MiddlewareAuthenticationVerification(next http.Handler) http.Handler { // steps to verify the authentication // 1. Verify the token in header // 2. Verify the token in cookie -func IsValidToken(r *http.Request) (error, *McApiContext) { +func IsValidToken(r *http.Request) (*McApiContext, error) { token, claims, err := getJwtToken(r) if err != nil { - return err, nil + return nil, err } if !token.Valid { - return errors.New("invalid token"), nil + return nil, errors.New("invalid token") } // verify the validity expiresAt := convertor.ToInteger(claims[handlerTY.KeyExpiresAt]) if time.Now().Unix() >= expiresAt { - return errors.New("expired token"), nil + return nil, errors.New("expired token") } // clear userID header, might be injected from external @@ -130,7 +130,7 @@ func IsValidToken(r *http.Request) (error, *McApiContext) { UserID: r.Header.Get(handlerTY.HeaderUserID), } - return nil, &mcApiContext + return &mcApiContext, nil } func getJwtToken(r *http.Request) (*jwt.Token, jwt.MapClaims, error) { diff --git a/pkg/http_router/routes/auth/oauth.go b/pkg/http_router/routes/auth/oauth.go index f3a2b36d..bbc232ee 100644 --- a/pkg/http_router/routes/auth/oauth.go +++ b/pkg/http_router/routes/auth/oauth.go @@ -46,7 +46,7 @@ func (oa *OAuthRoutes) landing(w http.ResponseWriter, r *http.Request) { func (oa *OAuthRoutes) login(w http.ResponseWriter, r *http.Request) { userInput, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { handlerUtils.PostErrorResponse(w, err.Error(), http.StatusInternalServerError) return @@ -172,7 +172,7 @@ func (oa *OAuthRoutes) login(w http.ResponseWriter, r *http.Request) { func (oa *OAuthRoutes) token(w http.ResponseWriter, r *http.Request) { inputBytes, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { oa.logger.Error("error on getting data", zap.Error(err)) } @@ -203,7 +203,7 @@ func (oa *OAuthRoutes) token(w http.ResponseWriter, r *http.Request) { } r.Header.Set(handlerTY.HeaderAuthorization, accessToken) - err, _ = middleware.IsValidToken(r) + _, err = middleware.IsValidToken(r) if err != nil { oa.logger.Info("invalid token", zap.Error(err)) http.Error(w, "invalid token", http.StatusUnauthorized) @@ -250,7 +250,7 @@ func (oa *OAuthRoutes) token(w http.ResponseWriter, r *http.Request) { } func (oa *OAuthRoutes) tokenAlexa(w http.ResponseWriter, r *http.Request) { - err, _ := middleware.IsValidToken(r) + _, err := middleware.IsValidToken(r) if err != nil { oa.logger.Info("invalid token", zap.Error(err)) http.Error(w, "invalid token", http.StatusUnauthorized) diff --git a/pkg/http_router/routes/firmware.go b/pkg/http_router/routes/firmware.go index 23cba17b..ee6debce 100644 --- a/pkg/http_router/routes/firmware.go +++ b/pkg/http_router/routes/firmware.go @@ -76,7 +76,7 @@ func (h *Routes) uploadFirmware(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - defer file.Close() // Close the file when we finish + defer func() { _ = file.Close() }() // Close the file when we finish err = h.api.Firmware().Upload(file, id, handler.Filename) if err != nil { diff --git a/pkg/http_router/routes/metric.go b/pkg/http_router/routes/metric.go index 8c437766..c34a21bf 100644 --- a/pkg/http_router/routes/metric.go +++ b/pkg/http_router/routes/metric.go @@ -116,7 +116,7 @@ func (h *Routes) getMetricList(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") d, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/pkg/service/gateway_msg_processor/service.go b/pkg/service/gateway_msg_processor/service.go index ed9a70ee..b745fe2a 100644 --- a/pkg/service/gateway_msg_processor/service.go +++ b/pkg/service/gateway_msg_processor/service.go @@ -17,7 +17,6 @@ import ( sourceTY "github.com/mycontroller-org/server/v2/pkg/types/source" "github.com/mycontroller-org/server/v2/pkg/types/topic" busUtils "github.com/mycontroller-org/server/v2/pkg/utils/bus_utils" - "github.com/mycontroller-org/server/v2/pkg/utils/convertor" converterUtils "github.com/mycontroller-org/server/v2/pkg/utils/convertor" "github.com/mycontroller-org/server/v2/pkg/utils/javascript" loggerUtils "github.com/mycontroller-org/server/v2/pkg/utils/logger" @@ -560,8 +559,8 @@ func (svc *MessageProcessor) updateFieldData( field.Current = fieldTY.Payload{Value: convertedValue, IsReceived: msg.IsReceived, Timestamp: msg.Timestamp} // update no change since - oldValue := convertor.ToString(field.Previous.Value) - newValue := convertor.ToString(field.Current.Value) + oldValue := converterUtils.ToString(field.Previous.Value) + newValue := converterUtils.ToString(field.Current.Value) if oldValue != newValue { field.NoChangeSince = msg.Timestamp } @@ -577,10 +576,7 @@ func (svc *MessageProcessor) updateFieldData( // post field data to event listeners busUtils.PostEvent(svc.logger, svc.bus, topic.TopicEventField, eventTY.TypeUpdated, types.EntityField, field) - updateMetric := true - if field.MetricType == metricTY.MetricTypeNone { - updateMetric = false - } + updateMetric := field.MetricType != metricTY.MetricTypeNone // for binary do not update duplicate values if field.MetricType == metricTY.MetricTypeBinary { updateMetric = field.Current.Timestamp.Equal(field.NoChangeSince) diff --git a/pkg/service/scheduler/listener.go b/pkg/service/scheduler/listener.go index 95947282..3448d5df 100644 --- a/pkg/service/scheduler/listener.go +++ b/pkg/service/scheduler/listener.go @@ -47,7 +47,10 @@ func (svc *SchedulerService) Close() error { svc.unloadAll() svc.eventsQueue.Close() // close core scheduler - svc.coreScheduler.Close() + err := svc.coreScheduler.Close() + if err != nil { + svc.logger.Error("error on closing core scheduler", zap.Error(err)) + } return nil } diff --git a/pkg/types/cusom_datetime/types.go b/pkg/types/cusom_datetime/types.go index 648fb945..b5a889fa 100644 --- a/pkg/types/cusom_datetime/types.go +++ b/pkg/types/cusom_datetime/types.go @@ -18,19 +18,19 @@ const CustomDateFormat = "2006-01-02" // MarshalJSON custom implementation func (cd CustomDate) MarshalJSON() ([]byte, error) { - if cd.Time.IsZero() { + if cd.IsZero() { return []byte("\"\""), nil } - stamp := fmt.Sprintf("\"%s\"", cd.Time.Format(CustomDateFormat)) + stamp := fmt.Sprintf("\"%s\"", cd.Format(CustomDateFormat)) return []byte(stamp), nil } // MarshalYAML implementation func (cd CustomDate) MarshalYAML() (interface{}, error) { - if cd.Time.IsZero() { + if cd.IsZero() { return "", nil } - return cd.Time.Format(CustomDateFormat), nil + return cd.Format(CustomDateFormat), nil } // UnmarshalJSON custom implementation @@ -72,19 +72,19 @@ const customTimeFormat = "15:04:05" // MarshalJSON custom implementation func (ct CustomTime) MarshalJSON() ([]byte, error) { - if ct.Time.IsZero() { + if ct.IsZero() { return []byte("\"\""), nil } - stamp := fmt.Sprintf("\"%s\"", ct.Time.Format(customTimeFormat)) + stamp := fmt.Sprintf("\"%s\"", ct.Format(customTimeFormat)) return []byte(stamp), nil } // MarshalYAML implementation func (ct CustomTime) MarshalYAML() (interface{}, error) { - if ct.Time.IsZero() { + if ct.IsZero() { return "", nil } - return ct.Time.Format(customTimeFormat), nil + return ct.Format(customTimeFormat), nil } // UnmarshalJSON custom implementation diff --git a/pkg/utils/clone/utils.go b/pkg/utils/clone/utils.go index 8df269f2..7849e49a 100644 --- a/pkg/utils/clone/utils.go +++ b/pkg/utils/clone/utils.go @@ -30,7 +30,7 @@ func translateRecursive(copy, original reflect.Value) { // The first cases handle nested structures and translate them recursively // If it is a pointer we need to unwrap and call once again - case reflect.Ptr: + case reflect.Pointer: // To get the actual value of the original we have to call Elem() // At the same time this unwraps the pointer so we don't end up in // an infinite recursion @@ -144,7 +144,7 @@ func UpdateSecrets(source interface{}, secret, encryptionPrefix string, encrypt func updateSecretRecursive(value reflect.Value, secret, encryptionPrefix string, encrypt bool, specialKeys []string) error { switch value.Kind() { - case reflect.Ptr: + case reflect.Pointer: originalValue := value.Elem() // Check if the pointer is nil if !originalValue.IsValid() { diff --git a/pkg/utils/file.go b/pkg/utils/file.go index d02335ce..47051406 100644 --- a/pkg/utils/file.go +++ b/pkg/utils/file.go @@ -82,7 +82,7 @@ func CopyFileForce(src, dst string, overwrite bool) error { if err != nil { return err } - defer source.Close() + defer func() { _ = source.Close() }() if IsFileExists(dst) { if !overwrite { @@ -106,7 +106,7 @@ func CopyFileForce(src, dst string, overwrite bool) error { if err != nil { return err } - defer destination.Close() + defer func() { _ = destination.Close() }() buf := make([]byte, bufferSize) for { @@ -144,7 +144,7 @@ func AppendFile(dir, filename string, data []byte) error { if err != nil { return err } - defer f.Close() + defer func() { _ = f.Close() }() _, err = f.Write(data) return err } diff --git a/pkg/utils/filter_sort/utils.go b/pkg/utils/filter_sort/utils.go index 603d4f1c..ece81948 100644 --- a/pkg/utils/filter_sort/utils.go +++ b/pkg/utils/filter_sort/utils.go @@ -32,7 +32,7 @@ func CloneSlice(src []interface{}) ([]interface{}, error) { // returns reflect.Kind, value, error func GetValueByKeyPath(data interface{}, keyPath string) (reflect.Kind, interface{}, error) { dataVal := reflect.ValueOf(data) - if dataVal.Kind() == reflect.Ptr { + if dataVal.Kind() == reflect.Pointer { dataVal = dataVal.Elem() } @@ -48,7 +48,7 @@ func GetValueByKeyPath(data interface{}, keyPath string) (reflect.Kind, interfac found := false expectedName := strings.ToLower(keys[keyIndex]) //fmt.Printf("\nin loop[%d], key:%s, kind:%v, \nvalue:%+v\n", keyIndex, expectedName, finalVal.Kind(), finalVal) - if finalVal.Kind() == reflect.Ptr || finalVal.Kind() == reflect.Interface { + if finalVal.Kind() == reflect.Pointer || finalVal.Kind() == reflect.Interface { finalVal = finalVal.Elem() //fmt.Printf("\nin loop[%d], key:%s, kind:%v, \nvalue:%+v\n", keyIndex, expectedName, finalVal.Kind(), finalVal) } @@ -94,7 +94,7 @@ func GetValueByKeyPath(data interface{}, keyPath string) (reflect.Kind, interfac } //fmt.Printf("returning, kind:%v, \nvalue:%+v\n\n", finalVal.Kind(), finalVal) - if finalVal.Kind() == reflect.Ptr || finalVal.Kind() == reflect.Interface { + if finalVal.Kind() == reflect.Pointer || finalVal.Kind() == reflect.Interface { if finalVal.IsNil() { return finalVal.Kind(), nil, nil } diff --git a/pkg/utils/http_handler/handler_storage_utils.go b/pkg/utils/http_handler/handler_storage_utils.go index 7421fb31..9936ae68 100644 --- a/pkg/utils/http_handler/handler_storage_utils.go +++ b/pkg/utils/http_handler/handler_storage_utils.go @@ -66,7 +66,7 @@ func UpdateData(w http.ResponseWriter, r *http.Request, entity interface{}, upda } d, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -145,7 +145,7 @@ func LoadEntity(w http.ResponseWriter, r *http.Request, entity interface{}) erro w.Header().Set("Content-Type", "application/json") d, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { return err } diff --git a/pkg/utils/printer/print.go b/pkg/utils/printer/print.go index b3053fd7..90436b47 100644 --- a/pkg/utils/printer/print.go +++ b/pkg/utils/printer/print.go @@ -43,7 +43,7 @@ func Print(out io.Writer, headers []Header, data interface{}, hideHeader bool, o case OutputConsole, OutputConsoleWide: dataConsole, ok := data.([]interface{}) if !ok { - fmt.Fprintln(out, "data not in table format") + _, _ = fmt.Fprintln(out, "data not in table format") return } wideEnabled := false @@ -65,7 +65,7 @@ func Print(out io.Writer, headers []Header, data interface{}, hideHeader bool, o fmt.Println("error on converting to json", err) return } - fmt.Fprint(out, string(jsonBytes)) + _, _ = fmt.Fprint(out, string(jsonBytes)) case OutputYAML: bytes, err := yaml.Marshal(data) @@ -73,7 +73,7 @@ func Print(out io.Writer, headers []Header, data interface{}, hideHeader bool, o fmt.Println("error on converting to yaml", err) return } - fmt.Fprint(out, string(bytes)) + _, _ = fmt.Fprint(out, string(bytes)) } } diff --git a/pkg/utils/quick_id/quick_id.go b/pkg/utils/quick_id/quick_id.go index 99b12841..4c6b2ccd 100644 --- a/pkg/utils/quick_id/quick_id.go +++ b/pkg/utils/quick_id/quick_id.go @@ -163,7 +163,7 @@ func EntityKeyValueMap(quickID string) (string, map[string]string, error) { func GetQuickID(entity interface{}) (string, error) { itemValueType := reflect.ValueOf(entity).Kind() - if itemValueType == reflect.Ptr { + if itemValueType == reflect.Pointer { entity = reflect.ValueOf(entity).Elem().Interface() itemValueType = reflect.ValueOf(entity).Kind() } diff --git a/pkg/utils/ziputils/unzip.go b/pkg/utils/ziputils/unzip.go index 80950d20..c487b20f 100644 --- a/pkg/utils/ziputils/unzip.go +++ b/pkg/utils/ziputils/unzip.go @@ -16,7 +16,7 @@ func Unzip(zipFilename string, destinationDirectory string) error { return err } - defer reader.Close() + defer func() { _ = reader.Close() }() for _, file := range reader.File { fPath := filepath.Join(destinationDirectory, file.Name) @@ -48,13 +48,16 @@ func Unzip(zipFilename string, destinationDirectory string) error { } _, err = io.Copy(outFile, rc) + if err != nil { + return err + } + err = outFile.Close() if err != nil { return err } - outFile.Close() - rc.Close() + err = rc.Close() if err != nil { return err } diff --git a/pkg/utils/ziputils/zip.go b/pkg/utils/ziputils/zip.go index 089bf0e7..0fa342fb 100644 --- a/pkg/utils/ziputils/zip.go +++ b/pkg/utils/ziputils/zip.go @@ -16,7 +16,7 @@ func Zip(logger *zap.Logger, sourceDirectory, zipFilename string) error { logger.Error("error", zap.Error(err)) return err } - defer zipFile.Close() + defer func() { _ = zipFile.Close() }() // Create a new zip archive. writer := zip.NewWriter(zipFile) diff --git a/plugin/bus/embedded/client.go b/plugin/bus/embedded/client.go index 98e381be..d4b889a8 100644 --- a/plugin/bus/embedded/client.go +++ b/plugin/bus/embedded/client.go @@ -11,7 +11,6 @@ import ( "github.com/mycontroller-org/server/v2/pkg/utils" "github.com/mycontroller-org/server/v2/pkg/utils/concurrency" loggerUtils "github.com/mycontroller-org/server/v2/pkg/utils/logger" - busPluginTY "github.com/mycontroller-org/server/v2/plugin/bus/types" busTY "github.com/mycontroller-org/server/v2/plugin/bus/types" "go.uber.org/zap" ) @@ -30,7 +29,7 @@ type Config struct { // Client struct type Client struct { topics map[string][]int64 - subscriptions map[int64]busPluginTY.CallBackFunc + subscriptions map[int64]busTY.CallBackFunc subscriptionCounter int64 mutex *sync.RWMutex pauseFlag concurrency.SafeBool @@ -39,7 +38,7 @@ type Client struct { } // NewClient func -func NewClient(ctx context.Context, config cmap.CustomMap) (busPluginTY.Plugin, error) { +func NewClient(ctx context.Context, config cmap.CustomMap) (busTY.Plugin, error) { logger, err := loggerUtils.FromContext(ctx) if err != nil { return nil, err @@ -53,7 +52,7 @@ func NewClient(ctx context.Context, config cmap.CustomMap) (busPluginTY.Plugin, client := &Client{ topics: make(map[string][]int64), - subscriptions: make(map[int64]busPluginTY.CallBackFunc), + subscriptions: make(map[int64]busTY.CallBackFunc), subscriptionCounter: 0, mutex: &sync.RWMutex{}, pauseFlag: concurrency.SafeBool{}, @@ -75,7 +74,7 @@ func (c *Client) Close() error { // clear all the call backs and topics c.subscriptionCounter = 0 c.topics = make(map[string][]int64) - c.subscriptions = make(map[int64]busPluginTY.CallBackFunc) + c.subscriptions = make(map[int64]busTY.CallBackFunc) return nil } @@ -132,7 +131,7 @@ func (c *Client) Publish(topic string, data interface{}) error { } // Subscribe a topic -func (c *Client) Subscribe(topic string, handler busPluginTY.CallBackFunc) (int64, error) { +func (c *Client) Subscribe(topic string, handler busTY.CallBackFunc) (int64, error) { c.mutex.Lock() defer c.mutex.Unlock() @@ -156,7 +155,7 @@ func (c *Client) Subscribe(topic string, handler busPluginTY.CallBackFunc) (int6 } // QueueSubscribe not supported in embedded bus, just call subscribe -func (c *Client) QueueSubscribe(topic, _queueName string, handler busPluginTY.CallBackFunc) (int64, error) { +func (c *Client) QueueSubscribe(topic, _queueName string, handler busTY.CallBackFunc) (int64, error) { return c.Subscribe(topic, handler) } diff --git a/plugin/bus/natsio/client.go b/plugin/bus/natsio/client.go index 58d9cb13..971b8f22 100644 --- a/plugin/bus/natsio/client.go +++ b/plugin/bus/natsio/client.go @@ -14,7 +14,6 @@ import ( "github.com/mycontroller-org/server/v2/pkg/utils" "github.com/mycontroller-org/server/v2/pkg/utils/concurrency" loggerUtils "github.com/mycontroller-org/server/v2/pkg/utils/logger" - busPluginTY "github.com/mycontroller-org/server/v2/plugin/bus/types" busTY "github.com/mycontroller-org/server/v2/plugin/bus/types" natsIO "github.com/nats-io/nats.go" "go.uber.org/zap" @@ -68,7 +67,7 @@ type Client struct { } // NewClient nats.io client -func NewClient(ctx context.Context, config cmap.CustomMap) (busPluginTY.Plugin, error) { +func NewClient(ctx context.Context, config cmap.CustomMap) (busTY.Plugin, error) { logger, err := loggerUtils.FromContext(ctx) if err != nil { return nil, err @@ -194,12 +193,12 @@ func (c *Client) Publish(topic string, data interface{}) error { } // Subscribe a topic -func (c *Client) Subscribe(topic string, handler busPluginTY.CallBackFunc) (int64, error) { +func (c *Client) Subscribe(topic string, handler busTY.CallBackFunc) (int64, error) { return c.QueueSubscribe(topic, "", handler) } // QueueSubscribe a topic with queue name -func (c *Client) QueueSubscribe(topic, queueName string, handler busPluginTY.CallBackFunc) (int64, error) { +func (c *Client) QueueSubscribe(topic, queueName string, handler busTY.CallBackFunc) (int64, error) { c.mutex.Lock() defer c.mutex.Unlock() @@ -238,7 +237,7 @@ func (c *Client) QueueSubscribe(topic, queueName string, handler busPluginTY.Cal return newSubscriptionID, nil } -func (c *Client) handlerWrapper(handler busPluginTY.CallBackFunc) func(natsMsg *natsIO.Msg) { +func (c *Client) handlerWrapper(handler busTY.CallBackFunc) func(natsMsg *natsIO.Msg) { return func(natsMsg *natsIO.Msg) { c.logger.Debug("receiving message", zap.String("topic", natsMsg.Sub.Subject)) handler(&busTY.BusData{Topic: natsMsg.Subject, Data: natsMsg.Data}) diff --git a/plugin/database/storage/memory/api.go b/plugin/database/storage/memory/api.go index 3653f422..c02bf97b 100644 --- a/plugin/database/storage/memory/api.go +++ b/plugin/database/storage/memory/api.go @@ -64,7 +64,7 @@ func (s *Store) Find(entityName string, out interface{}, filters []storageTY.Fil defer s.mutex.RUnlock() outVal := reflect.ValueOf(out) - if outVal.Kind() != reflect.Ptr { + if outVal.Kind() != reflect.Pointer { return nil, errors.New("results argument must be a pointer to a slice") } diff --git a/plugin/gateway/protocol/protocol_http/client.go b/plugin/gateway/protocol/protocol_http/client.go index 8ddb2fa7..8226ee30 100644 --- a/plugin/gateway/protocol/protocol_http/client.go +++ b/plugin/gateway/protocol/protocol_http/client.go @@ -107,11 +107,11 @@ func (ep *Endpoint) Write(rawMsg *msgTY.RawMessage) error { requestRaw := rawMsg.Others.Get(gwPtl.KeyHTTPRequestConf) if requestRaw == nil { - return fmt.Errorf("There is no requestConfig found. Have you supplied cfg with key: %s?", gwPtl.KeyHTTPRequestConf) + return fmt.Errorf("there is no requestConfig found. Have you supplied cfg with key: %s?", gwPtl.KeyHTTPRequestConf) } reqCfg, ok := requestRaw.(RequestConfig) if !ok { - return fmt.Errorf("Failed to convert request conf, %v", requestRaw) + return fmt.Errorf("failed to convert request conf, %v", requestRaw) } if reqCfg.ResponseCode == 0 { diff --git a/plugin/gateway/protocol/protocol_http/client_helper.go b/plugin/gateway/protocol/protocol_http/client_helper.go index 444b5c01..50998cb6 100644 --- a/plugin/gateway/protocol/protocol_http/client_helper.go +++ b/plugin/gateway/protocol/protocol_http/client_helper.go @@ -52,7 +52,7 @@ func (ep *Endpoint) newRequest(cfg RequestConfig, body interface{}) (*ResponseCo } if resp.StatusCode != cfg.ResponseCode { - return nil, nil, fmt.Errorf("Failed with status code. [url:%v, status: %v, statusCode: %v]", fullPath.String(), resp.Status, resp.StatusCode) + return nil, nil, fmt.Errorf("failed with status code. [url:%v, status: %v, statusCode: %v]", fullPath.String(), resp.Status, resp.StatusCode) } respBodyBytes, err := io.ReadAll(resp.Body) diff --git a/plugin/gateway/provider/generic/protocol_http_generic/protocol.go b/plugin/gateway/provider/generic/protocol_http_generic/protocol.go index 1a550115..4573df23 100644 --- a/plugin/gateway/provider/generic/protocol_http_generic/protocol.go +++ b/plugin/gateway/provider/generic/protocol_http_generic/protocol.go @@ -238,9 +238,10 @@ func (hp *HttpProtocol) executeSupportRuns(client *httpclient.Client, runType st if cfg.Script != "" { // update variables variables := map[string]interface{}{} - if runType == PreRun { + switch runType { + case PreRun: variables[ScriptKeyPreRunResponse] = runResponses - } else if runType == PostRun { + case PostRun: variables[ScriptKeyPreRunResponse] = preRunResponse variables[ScriptKeyPostRunResponse] = runResponses } diff --git a/plugin/gateway/provider/mysensors_v2/event_listener.go b/plugin/gateway/provider/mysensors_v2/event_listener.go index 9054e652..641c3814 100644 --- a/plugin/gateway/provider/mysensors_v2/event_listener.go +++ b/plugin/gateway/provider/mysensors_v2/event_listener.go @@ -70,7 +70,7 @@ func (p *Provider) onEvent(data *busTY.BusData) { } p.logger.Debug("Received an event", zap.Any("event", event)) - if !(event.EntityType == types.EntityNode || event.EntityType == types.EntityFirmware) || + if (event.EntityType != types.EntityNode && event.EntityType != types.EntityFirmware) || event.Entity == nil { return } diff --git a/plugin/gateway/provider/mysensors_v2/ota_impl.go b/plugin/gateway/provider/mysensors_v2/ota_impl.go index 32eb26bf..b9286d2d 100644 --- a/plugin/gateway/provider/mysensors_v2/ota_impl.go +++ b/plugin/gateway/provider/mysensors_v2/ota_impl.go @@ -321,16 +321,18 @@ func (p *Provider) updateFirmwareProgressStatus(node *nodeTY.Node, currentBlock, if otaBlockOrder == OTABlockOrderReverse { percentage = 1 - percentage isRunning = currentBlock != 0 - if currentBlock == lastBlock { + switch currentBlock { + case lastBlock: startTime = time.Now() - } else if currentBlock == 0 { + case 0: endTime = time.Now() } } else { isRunning = currentBlock != lastBlock - if currentBlock == 0 { + switch currentBlock { + case 0: startTime = time.Now() - } else if currentBlock == lastBlock { + case lastBlock: endTime = time.Now() } } diff --git a/plugin/handler/email/smtp.go b/plugin/handler/email/smtp.go index ac759f9c..107c02c5 100644 --- a/plugin/handler/email/smtp.go +++ b/plugin/handler/email/smtp.go @@ -29,11 +29,12 @@ type SmtpClient struct { func NewSMTPClient(ctx context.Context, logger *zap.Logger, handlerCfg *handlerTY.Config, cfg *Config) (Client, error) { var auth smtp.Auth - if cfg.AuthType == AuthTypePlain || cfg.AuthType == "" { + switch cfg.AuthType { + case AuthTypePlain, "": auth = smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host) - } else if cfg.AuthType == AuthTypeCRAMMD5 { + case AuthTypeCRAMMD5: auth = smtp.CRAMMD5Auth(cfg.Username, cfg.Password) - } else { + default: return nil, fmt.Errorf("unknown auth type:%s", cfg.AuthType) } diff --git a/plugin/virtual_assistant/assistant/alexa/api.go b/plugin/virtual_assistant/assistant/alexa/api.go index 311b575f..ed0ce1fc 100644 --- a/plugin/virtual_assistant/assistant/alexa/api.go +++ b/plugin/virtual_assistant/assistant/alexa/api.go @@ -64,7 +64,7 @@ func (a *Assistant) Config() *vaTY.Config { func (a *Assistant) ServeHTTP(w http.ResponseWriter, r *http.Request) { // a.logger.Info("a request from", zap.Any("RequestURI", r.RequestURI), zap.Any("method", r.Method), zap.Any("headers", r.Header), zap.Any("query", r.URL.RawQuery)) d, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { a.logger.Error("error on getting body", zap.Error(err)) http.Error(w, "error on getting body", 500) diff --git a/plugin/virtual_assistant/assistant/alexa/directive.go b/plugin/virtual_assistant/assistant/alexa/directive.go index 7c924798..46d7ed04 100644 --- a/plugin/virtual_assistant/assistant/alexa/directive.go +++ b/plugin/virtual_assistant/assistant/alexa/directive.go @@ -29,11 +29,12 @@ func (a *Assistant) executiveDirective(directive alexaTY.DirectiveOrEvent) *alex // PowerController func (a *Assistant) executeDirectivePowerController(endpointID, directive string) *alexaTY.Response { payload := false - if directive == alexaTY.DirectiveTurnOn { + switch directive { + case alexaTY.DirectiveTurnOn: payload = true - } else if directive == alexaTY.DirectiveTurnOff { + case alexaTY.DirectiveTurnOff: payload = false - } else { + default: return a.getErrorResponse(endpointID, alexaTY.ErrorTypeInvalidDirective, fmt.Sprintf("%s directive not supported for %s", directive, alexaTY.NamespacePowerController)) } return a.executeResourceAction(endpointID, alexaTY.NamespacePowerController, directive, vdTY.DeviceTraitOnOff, payload) diff --git a/plugin/virtual_assistant/assistant/google/api.go b/plugin/virtual_assistant/assistant/google/api.go index f0de5aa9..0aa799a2 100644 --- a/plugin/virtual_assistant/assistant/google/api.go +++ b/plugin/virtual_assistant/assistant/google/api.go @@ -67,7 +67,7 @@ func (a *Assistant) Config() *vaTY.Config { func (a *Assistant) ServeHTTP(w http.ResponseWriter, r *http.Request) { // a.logger.Info("a request from", zap.Any("RequestURI", r.RequestURI), zap.Any("method", r.Method), zap.Any("headers", r.Header), zap.Any("query", r.URL.RawQuery)) d, err := io.ReadAll(r.Body) - defer r.Body.Close() + defer func() { _ = r.Body.Close() }() if err != nil { a.logger.Error("error on getting body", zap.Error(err)) http.Error(w, "error on getting body", 500)