skip to Main Content

I have go code which looks like this

package services

import (
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
    "github.com/irohitb/EmpAdmin/backend/config"
    "github.com/irohitb/EmpAdmin/backend/middleware"
    "github.com/supabase/postgrest-go"
)


func GetAllUsers(env *config.Env, db *postgrest.Client, group *gin.RouterGroup) {
    group.GET("/:services", func (router *gin.Context) {
        services := strings.Split(router.Param("service"), ",")
        user, exists := router.Get("user")
        if !exists {
            router.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "user information not found in context"})
            return
        }
        userToken, exists := user.(*middleware.UserToken)
        if exists {
            workspaceId := userToken.User.WorkspaceID
        }

        
        
        
    })
}

Here VS code complains about

    "github.com/irohitb/EmpAdmin/backend/middleware"

imported but not used error.

which I am using here

*middleware.UserToken

Here is how my middleware looks

package middleware

import (
    "net/http"

    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "github.com/irohitb/EmpAdmin/backend/domain"
)




type UserToken struct {
    jwt.StandardClaims
    User domain.UserToken
}

2

Answers


  1. The repository github.com/irohitb/EmpAdmin seems to be a private one, which could have that kind of side effect.

    Try and add in your VSCode preferences "Go tools env vars":

    {
      "go.toolsEnvVars": {
        "GOPRIVATE": "github.com/*"
      }
    }
    

    Also, as in this answer, check if you have defined elsewhere a variable (or global variable) named middleware, which would override the package middleware.

    Login or Signup to reply.
  2. My argument is in favor of VS Code check that we are not "using" the middleware import.

    By using, it most probably means "Actually using something from that package". e.g., the UserToken struct. Here we are not actually using it, we are just assigning its type to variables which in turns are unused. Apparently, we’re using middleware.UserToken, but not really, nowhere in that function are we are creating a UserToken struct.

    userToken, exists := user.(*middleware.UserToken) 
    // Use userToken here
    if exists {
          workspaceId := userToken.User.WorkspaceID
    }
    

    Merely assigning a type to a variable is not "using" that type. To fix the warning, we need to actually use something from the middleware package: construct a UserToken struct instance.

    // This is an actual usage
    userToken := middleware.UserToken{User: domain.UserToken{WorkspaceID: workspaceId}}
    

    And now the warning will go away, because we’re actually using middleware.UserToken.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search