github.com/lulzWill/go-agent@v2.1.2+incompatible/internal/environment.go (about)

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