Check Unix user

Asked

Viewed 34 times

2

To check the user name I can easily use:

import (
    "fmt"
    "os"
)

fmt.Println(os.Getenv("USER"))

But to make things a little easier I’d like to add a new role to struct os, so I did it this way:

func (system os) Sudo() bool {
    return system.Getenv("USER") == "root"
}

func main() {
    if !os.Sudo() {
        fmt.Println("You have no permission to run as non-root user. Use sudo")
        os.Exit(1)
    }
}

The mistake I get is:

use of package os without selector

1 answer

0


As far as I know, maybe I’m wrong, there is no way to extend functions or interfaces in Golang, created by other Packages, much less in this case.

First, you must define us imports the os, but that won’t solve the problem.


func (system os) Sudo() bool {
    return system.Getenv("USER") == "root"
}

You actually expect the os is a struct/interface, which in fact it is not. The os is a package.


In your case what you can do is create a new folder, for example "systemOS" and then declare "package systemOS" in it, for example:

package systemOS

import "os"

func Sudo() bool {
    return system.Getenv("USER") == "root"
}    

Now you could call on your main, as long as it gives import on systemOS newly created:

func main() {
    if !systemOS.Sudo() {
        fmt.Println("You have no permission to run as non-root user. Use sudo")
        os.Exit(1)
    }
}

In other cases, you can create a "synonym" (an alias) for another type. For the example become easier I will use the os/user which in it contain a struct of user.User.

package main

import (
    "fmt"
    "os/user"
)

type X user.User

func (u X) IsInkeliz() bool {
    return u.Name == "Inkeliz"
}

func main() {
    acc, err := user.Current()
    if err != nil {
        panic("")
    }

    if !X(*acc).IsInkeliz() {
        fmt.Println("Você não é Inkeliz")
    }
}

The X is a guy who is the same as user.User. Then I convert X(*acc) and I can access the IsInkeliz() I created, within the function I can also access the .Name which is from the original struct (user. User).

Another way to do it would also be to create a Struct:

type X struct {
    y *user.User
}

Then put the acc inside it and could access the y.Name.

However, in all cases you will be creating a new type. I don’t know any way to "extend" the type established by another package without having to create a new type.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.