github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/go/configuration.mustache (about)

     1  package {{packageName}}
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  // contextKeys are used to identify the type of value in the context.
    10  // Since these are string, it is possible to get a short description of the
    11  // context key for logging and debugging using key.String().
    12  
    13  type contextKey string
    14  
    15  func (c contextKey) String() string {
    16  	return "auth " + string(c)
    17  }
    18  
    19  var (
    20  	// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
    21  	ContextOAuth2 = contextKey("token")
    22  
    23  	// ContextBasicAuth takes BasicAuth as authentication for the request.
    24  	ContextBasicAuth = contextKey("basic")
    25  
    26  	// ContextAccessToken takes a string oauth2 access token as authentication for the request.
    27  	ContextAccessToken = contextKey("accesstoken")
    28  
    29  	// ContextAPIKey takes an APIKey as authentication for the request
    30  	ContextAPIKey = contextKey("apikey")
    31  
    32  	{{#withAWSV4Signature}}
    33  	// ContextAWSv4 takes an Access Key and a Secret Key for signing AWS Signature v4.
    34  	ContextAWSv4 = contextKey("awsv4")
    35  	{{/withAWSV4Signature}}
    36  )
    37  
    38  // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
    39  type BasicAuth struct {
    40  	UserName string `json:"userName,omitempty"`
    41  	Password string `json:"password,omitempty"`
    42  }
    43  
    44  // APIKey provides API key based authentication to a request passed via context using ContextAPIKey
    45  type APIKey struct {
    46  	Key    string
    47  	Prefix string
    48  }
    49  
    50  {{#withAWSV4Signature}}
    51  // AWSv4 provides AWS Signature to a request passed via context using ContextAWSv4
    52  // https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
    53  type AWSv4 struct {
    54  		AccessKey string
    55  		SecretKey string
    56  }
    57  {{/withAWSV4Signature}}
    58  
    59  // ServerVariable stores the information about a server variable
    60  type ServerVariable struct {
    61  	Description  string
    62  	DefaultValue string
    63  	EnumValues   []string
    64  }
    65  
    66  // ServerConfiguration stores the information about a server
    67  type ServerConfiguration struct {
    68  	Url string
    69  	Description string
    70  	Variables map[string]ServerVariable
    71  }
    72  
    73  // Configuration stores the configuration of the API client
    74  type Configuration struct {
    75  	BasePath      string            `json:"basePath,omitempty"`
    76  	Host          string            `json:"host,omitempty"`
    77  	Scheme        string            `json:"scheme,omitempty"`
    78  	DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
    79  	UserAgent     string            `json:"userAgent,omitempty"`
    80  	Debug         bool              `json:"debug,omitempty"`
    81  	Servers       []ServerConfiguration
    82  	HTTPClient    *http.Client
    83  }
    84  
    85  func ClientVersion() string {
    86  	return "{{{packageVersion}}}"
    87  }
    88  
    89  func getUserAgent() string {
    90  	agent := "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Phrase Strings go{{/httpUserAgent}} (" + ClientVersion() + ")"
    91  	if ua := os.Getenv("PHRASE_USER_AGENT"); ua != "" {
    92  		agent = ua + "; " + agent
    93  	}
    94  	return agent
    95  }
    96  
    97  func (c *Configuration) SetUserAgent(customUserAgent string) {
    98  	c.UserAgent = fmt.Sprintf("%s (using %s)", customUserAgent, getUserAgent())
    99  }
   100  
   101  // NewConfiguration returns a new Configuration object
   102  func NewConfiguration() *Configuration {
   103  	cfg := &Configuration{
   104  		BasePath:      "{{{basePath}}}",
   105  		DefaultHeader: make(map[string]string),
   106  		UserAgent:     getUserAgent(),
   107  		Debug:         false,
   108  		{{#servers}}
   109  		{{#-first}}
   110  		Servers:       []ServerConfiguration{
   111  		{{/-first}}
   112  			{
   113  				Url: "{{{url}}}",
   114  				Description: "{{{description}}}{{^description}}No description provided{{/description}}",
   115  				{{#variables}}
   116  				{{#-first}}
   117  				Variables: map[string]ServerVariable{
   118  				{{/-first}}
   119  					"{{{name}}}": ServerVariable{
   120  						Description: "{{{description}}}{{^description}}No description provided{{/description}}",
   121  						DefaultValue: "{{{defaultValue}}}",
   122  						{{#enumValues}}
   123  						{{#-first}}
   124  						EnumValues: []string{
   125  						{{/-first}}
   126  							"{{{.}}}",
   127  						{{#-last}}
   128  						},
   129  						{{/-last}}
   130  						{{/enumValues}}
   131  					},
   132  				{{#-last}}
   133  				},
   134  				{{/-last}}
   135  				{{/variables}}
   136  			},
   137  		{{#-last}}
   138  		},
   139  		{{/-last}}
   140  		{{/servers}}
   141  	}
   142  
   143  	return cfg
   144  }
   145  
   146  // AddDefaultHeader adds a new HTTP header to the default header in the request
   147  func (c *Configuration) AddDefaultHeader(key string, value string) {
   148  	c.DefaultHeader[key] = value
   149  }
   150  
   151  // ServerUrl returns URL based on server settings
   152  func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
   153  	if index < 0 || len(c.Servers) <= index {
   154  		return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
   155  	}
   156  	server := c.Servers[index]
   157  	url := server.Url
   158  
   159  	// go through variables and replace placeholders
   160  	for name, variable := range server.Variables {
   161  		if value, ok := variables[name]; ok {
   162  			found := bool(len(variable.EnumValues) == 0)
   163  			for _, enumValue := range variable.EnumValues {
   164  				if value == enumValue {
   165  					found = true
   166  				}
   167  			}
   168  			if !found {
   169  				return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
   170  			}
   171  			url = strings.Replace(url, "{"+name+"}", value, -1)
   172  		} else {
   173  			url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
   174  		}
   175  	}
   176  	return url, nil
   177  }