env_windows.go 1.6 KB

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