登录
首页 >  Golang >  Go问答

os/user: 使用标签 osusergo 为 linux/amd64 构建时“GroupIds 需要 cgo”

来源:stackoverflow

时间:2024-04-15 19:00:32 212浏览 收藏

本篇文章向大家介绍《os/user: 使用标签 osusergo 为 linux/amd64 构建时“GroupIds 需要 cgo”》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我正在尝试构建一个静态可执行文件,它使用 os/user 模块来查找特定用户在 linux/amd64 上所属的组。

根据文档,设置 osusergo 构建标记将允许我使用此模块的非 cgo 版本,但该标志似乎没有执行任何操作。

以下是我构建可执行文件的方法:

export cgo_enabled=0
export goos=linux
export goarch=amd64
go build -tags osusergo -o bin/agent

这是我的 go 版本:

$ go version
go version go1.14.4 linux/amd64

以下是我如何使用 os/user 模块的示例:

import (
    "os/user"
)

func GetUserGroupIds(uid string) ([]string, error) {
    u, err := user.LookupId(uid)
    if err != nil {
        return nil, err
    }
    gids, err := u.GroupIds()
    if err != nil {
        return nil, err
    }
    return gids, nil
}

在查找特定用户所属的组时,我收到以下错误:user:groupids 需要 cgo

我没有正确使用 -tags osusergo 吗?


解决方案


阅读源代码后,发现os/user模块的listgroups(u *user)函数没有原生go实现:

// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build dragonfly darwin freebsd !android,linux netbsd openbsd
// +build cgo,!osusergo

package user

import (
    "fmt"
    "strconv"
    "unsafe"
)

/*
#include 
#include 
*/
import "C"

const maxGroups = 2048

func listGroups(u *User) ([]string, error) {
    ug, err := strconv.Atoi(u.Gid)
    if err != nil {
        return nil, fmt.Errorf("user: list groups for %s: invalid gid %q", u.Username, u.Gid)
    }
    userGID := C.gid_t(ug)
    nameC := make([]byte, len(u.Username)+1)
    copy(nameC, u.Username)

    n := C.int(256)
    gidsC := make([]C.gid_t, n)
    rv := getGroupList((*C.char)(unsafe.Pointer(&nameC[0])), userGID, &gidsC[0], &n)
    if rv == -1 {
        // Mac is the only Unix that does not set n properly when rv == -1, so
        // we need to use different logic for Mac vs. the other OS's.
        if err := groupRetry(u.Username, nameC, userGID, &gidsC, &n); err != nil {
            return nil, err
        }
    }
    gidsC = gidsC[:n]
    gids := make([]string, 0, n)
    for _, g := range gidsC[:n] {
        gids = append(gids, strconv.Itoa(int(g)))
    }
    return gids, nil
}

今天关于《os/user: 使用标签 osusergo 为 linux/amd64 构建时“GroupIds 需要 cgo”》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>