github.com/aneshas/cli@v0.0.0-20180104210444-aec958fa47db/client/api.go (about)

     1  package client
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"os"
     7  
     8  	fnclient "github.com/fnproject/fn_go/client"
     9  	openapi "github.com/go-openapi/runtime/client"
    10  	"github.com/go-openapi/strfmt"
    11  )
    12  
    13  const (
    14  	envFnToken = "FN_TOKEN"
    15  )
    16  
    17  func Host() string {
    18  	h, err := HostURL()
    19  	if err != nil {
    20  		fmt.Fprint(os.Stderr, err.Error())
    21  		os.Exit(1)
    22  	}
    23  	return h.Host
    24  }
    25  
    26  func HostURL() (*url.URL, error) {
    27  	apiURL := os.Getenv("FN_API_URL")
    28  
    29  	if apiURL == "" {
    30  		if os.Getenv("API_URL") != "" {
    31  			fmt.Fprint(os.Stderr, "Error: API_URL is deprecated, please use FN_API_URL.")
    32  			os.Exit(1)
    33  		}
    34  		apiURL = "http://localhost:8080"
    35  	}
    36  
    37  	return url.Parse(apiURL)
    38  }
    39  
    40  func GetTransportAndRegistry() (*openapi.Runtime, strfmt.Registry) {
    41  	transport := openapi.New(Host(), "/v1", []string{"http"})
    42  	if os.Getenv(envFnToken) != "" {
    43  		transport.DefaultAuthentication = openapi.BearerToken(os.Getenv(envFnToken))
    44  	}
    45  	return transport, strfmt.Default
    46  }
    47  
    48  func APIClient() *fnclient.Fn {
    49  	transport := openapi.New(Host(), "/v1", []string{"http"})
    50  	if os.Getenv(envFnToken) != "" {
    51  		transport.DefaultAuthentication = openapi.BearerToken(os.Getenv(envFnToken))
    52  	}
    53  
    54  	// create the API client, with the transport
    55  	client := fnclient.New(GetTransportAndRegistry())
    56  
    57  	return client
    58  }