github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/src/os/user/lookup.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package user
     6  
     7  import "sync"
     8  
     9  // Current returns the current user.
    10  func Current() (*User, error) {
    11  	cache.Do(func() { cache.u, cache.err = current() })
    12  	if cache.err != nil {
    13  		return nil, cache.err
    14  	}
    15  	u := *cache.u // copy
    16  	return &u, nil
    17  }
    18  
    19  // cache of the current user
    20  var cache struct {
    21  	sync.Once
    22  	u   *User
    23  	err error
    24  }
    25  
    26  // Lookup looks up a user by username. If the user cannot be found, the
    27  // returned error is of type UnknownUserError.
    28  func Lookup(username string) (*User, error) {
    29  	if u, err := Current(); err == nil && u.Username == username {
    30  		return u, err
    31  	}
    32  	return lookupUser(username)
    33  }
    34  
    35  // LookupId looks up a user by userid. If the user cannot be found, the
    36  // returned error is of type UnknownUserIdError.
    37  func LookupId(uid string) (*User, error) {
    38  	if u, err := Current(); err == nil && u.Uid == uid {
    39  		return u, err
    40  	}
    41  	return lookupUserId(uid)
    42  }
    43  
    44  // LookupGroup looks up a group by name. If the group cannot be found, the
    45  // returned error is of type UnknownGroupError.
    46  func LookupGroup(name string) (*Group, error) {
    47  	return lookupGroup(name)
    48  }
    49  
    50  // LookupGroupId looks up a group by groupid. If the group cannot be found, the
    51  // returned error is of type UnknownGroupIdError.
    52  func LookupGroupId(gid string) (*Group, error) {
    53  	return lookupGroupId(gid)
    54  }
    55  
    56  // GroupIds returns the list of group IDs that the user is a member of.
    57  func (u *User) GroupIds() ([]string, error) {
    58  	return listGroups(u)
    59  }