github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/syscall/env_windows.go (about) 1 // Copyright 2010 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 // Windows environment variables. 6 7 package syscall 8 9 import ( 10 "unicode/utf16" 11 "unsafe" 12 ) 13 14 func Getenv(key string) (value string, found bool) { 15 keyp, err := UTF16PtrFromString(key) 16 if err != nil { 17 return "", false 18 } 19 n := uint32(100) 20 for { 21 b := make([]uint16, n) 22 n, err = GetEnvironmentVariable(keyp, &b[0], uint32(len(b))) 23 if n == 0 && err == ERROR_ENVVAR_NOT_FOUND { 24 return "", false 25 } 26 if n <= uint32(len(b)) { 27 return string(utf16.Decode(b[:n])), true 28 } 29 } 30 } 31 32 func Setenv(key, value string) error { 33 v, err := UTF16PtrFromString(value) 34 if err != nil { 35 return err 36 } 37 keyp, err := UTF16PtrFromString(key) 38 if err != nil { 39 return err 40 } 41 e := SetEnvironmentVariable(keyp, v) 42 if e != nil { 43 return e 44 } 45 runtimeSetenv(key, value) 46 return nil 47 } 48 49 func Unsetenv(key string) error { 50 keyp, err := UTF16PtrFromString(key) 51 if err != nil { 52 return err 53 } 54 e := SetEnvironmentVariable(keyp, nil) 55 if e != nil { 56 return e 57 } 58 runtimeUnsetenv(key) 59 return nil 60 } 61 62 func Clearenv() { 63 for _, s := range Environ() { 64 // Environment variables can begin with = 65 // so start looking for the separator = at j=1. 66 // https://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx 67 for j := 1; j < len(s); j++ { 68 if s[j] == '=' { 69 Unsetenv(s[0:j]) 70 break 71 } 72 } 73 } 74 } 75 76 func Environ() []string { 77 s, e := GetEnvironmentStrings() 78 if e != nil { 79 return nil 80 } 81 defer FreeEnvironmentStrings(s) 82 r := make([]string, 0, 50) // Empty with room to grow. 83 for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ { 84 if p[i] == 0 { 85 // empty string marks the end 86 if i <= from { 87 break 88 } 89 r = append(r, string(utf16.Decode(p[from:i]))) 90 from = i + 1 91 } 92 } 93 return r 94 }