environment.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package internal
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. "runtime"
  6. )
  7. // Environment describes the application's environment.
  8. type Environment struct {
  9. Compiler string `env:"runtime.Compiler"`
  10. GOARCH string `env:"runtime.GOARCH"`
  11. GOOS string `env:"runtime.GOOS"`
  12. Version string `env:"runtime.Version"`
  13. NumCPU int `env:"runtime.NumCPU"`
  14. }
  15. var (
  16. // SampleEnvironment is useful for testing.
  17. SampleEnvironment = Environment{
  18. Compiler: "comp",
  19. GOARCH: "arch",
  20. GOOS: "goos",
  21. Version: "vers",
  22. NumCPU: 8,
  23. }
  24. )
  25. // NewEnvironment returns a new Environment.
  26. func NewEnvironment() Environment {
  27. return Environment{
  28. Compiler: runtime.Compiler,
  29. GOARCH: runtime.GOARCH,
  30. GOOS: runtime.GOOS,
  31. Version: runtime.Version(),
  32. NumCPU: runtime.NumCPU(),
  33. }
  34. }
  35. // MarshalJSON prepares Environment JSON in the format expected by the collector
  36. // during the connect command.
  37. func (e Environment) MarshalJSON() ([]byte, error) {
  38. var arr [][]interface{}
  39. val := reflect.ValueOf(e)
  40. numFields := val.NumField()
  41. arr = make([][]interface{}, numFields)
  42. for i := 0; i < numFields; i++ {
  43. v := val.Field(i)
  44. t := val.Type().Field(i).Tag.Get("env")
  45. arr[i] = []interface{}{
  46. t,
  47. v.Interface(),
  48. }
  49. }
  50. return json.Marshal(arr)
  51. }