github.com/newrelic/go-agent@v3.26.0+incompatible/internal/environment.go (about)

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