github.com/govau/cf-common@v0.0.7/env/ups.go (about)

     1  package env
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/cloudfoundry-community/go-cfenv"
     7  )
     8  
     9  // WithUPSLookup configures the VarSet to use the CloudFoundry user-provided
    10  // service with the given name as a lookup source.
    11  func WithUPSLookup(app *cfenv.App, name string) VarSetOpt {
    12  	return func(v *VarSet) {
    13  		v.AppendSource(NewLookupFromUPS(app, name))
    14  	}
    15  }
    16  
    17  // NewLookupFromUPS looks for a CloudFoundry bound service with the given name.
    18  // This allows sourcing environment variables from a user-provided service.
    19  // If no service is found, a passthrough lookup is used that always returns
    20  // false.
    21  func NewLookupFromUPS(app *cfenv.App, name string) Lookup {
    22  	if app == nil {
    23  		return NoopLookup
    24  	}
    25  	service, err := app.Services.WithName(name)
    26  	// The only error WithName will return is that the service was not found,
    27  	// so it is OK that we ignore the error here.
    28  	if err != nil {
    29  		return NoopLookup
    30  	}
    31  	return func(k string) (string, bool) {
    32  		v, ok := service.Credentials[k]
    33  		if !ok {
    34  			return "", false
    35  		}
    36  		// The lookup mechanism expects strings to be returned. However UPS
    37  		// Credentials allow any JSON value. To get around this, we always just
    38  		// format the value as a string. This means that nested values like
    39  		// arrays and objects will lose their meaning and cannot really be used
    40  		// by this library.
    41  		return fmt.Sprintf("%v", v), true
    42  	}
    43  }